{"id":"JabOnc1cv61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Introduction","summary":"Total.js 4 is a full-stack framework for Node.js written in pure JavaScript, with no dependencies.","markdown":"---\ntitle: Introduction\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Introduction\n\n> Total.js 4 is a full-stack framework for Node.js written in pure JavaScript, with no dependencies.\n\nTotal.js 4 is a full-stack framework for Node.js written in pure JavaScript. It builds web applications, REST APIs, background services, desktop and IoT applications with one package, `total4`, and **no dependencies**: only Node.js.\n\n## What it gives you\n\n- **Routing**: one `ROUTE()` function for pages, REST endpoints, file handlers and WebSockets. See [Routing](../routing/).\n- **Controllers**: the object that answers a request (`this.json()`, `this.view()`, `this.plain()`…).\n- **Schemas and actions**: validated input and operations (`insert`, `update`, `read`, your own) that routes call directly.\n- **Views**: a template engine for HTML with layouts, partials and localization.\n- **Embedded databases**: NoSQL and TextDB, stored in files inside the app.\n- **Localization**: resource files and `@(Text)` markers in views.\n- **Workers, tasks and FlowStream**: background work and visual data flows.\n- **The `total4` command**: templates, translations, bundles and packages.\n\n## How an app is organized\n\nAn app is a folder with a start script (`index.js`) and some of these folders. Total.js loads them when the app starts; none of them is required.\n\n| Folder | What goes in it |\n| --- | --- |\n| `controllers/` | Routes (`exports.install`) and their actions |\n| `schemas/` | Schemas and their actions |\n| `definitions/` | Code that runs at start: helpers, auth, configuration |\n| `views/` | HTML templates |\n| `public/` | Static files: CSS, JavaScript, images |\n| `resources/` | Localization files |\n| `databases/` | Data of NoSQL, TextDB and file storages |\n| `modules/`, `plugins/` | Reusable parts of an app |\n| `workers/`, `tasks/` | Background work |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | JSON schemas, operations, middleware and FlowStream data |\n| `private/` | Files that are never served |\n\n## Versions of this documentation\n\nThis project documents the official Total.js 4: the [totaljs/framework4](https://github.com/totaljs/framework4) repository and the `total4` package on npm (latest **0.0.99**). API entries say **since** which version they exist, so you know what you can use with the version of your app.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnc1cv61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Einführung","summary":"Total.js 4 ist ein Full-Stack-Framework für Node.js, geschrieben in reinem JavaScript und ohne Abhängigkeiten.","markdown":"---\ntitle: \"Einführung\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Einführung\n\n> Total.js 4 ist ein Full-Stack-Framework für Node.js, geschrieben in reinem JavaScript und ohne Abhängigkeiten.\n\nTotal.js 4 ist ein Full-Stack-Framework für Node.js, geschrieben in reinem JavaScript. Damit baust du Webanwendungen, REST-APIs, Hintergrunddienste, Desktop- und IoT-Anwendungen mit einem einzigen Paket, `total4`, und **ohne Abhängigkeiten**: Du brauchst nur Node.js.\n\n## Was es dir bietet\n\n- **Routing**: eine einzige Funktion `ROUTE()` für Seiten, REST-Endpunkte, Datei-Handler und WebSockets. Siehe [Routing](../routing/).\n- **Controller**: das Objekt, das eine Anfrage beantwortet (`this.json()`, `this.view()`, `this.plain()`…).\n- **Schemas und Aktionen**: validierte Eingaben und Operationen (`insert`, `update`, `read`, eigene), die Routen direkt aufrufen.\n- **Views**: eine Template-Engine für HTML mit Layouts, Partials und Lokalisierung.\n- **Eingebettete Datenbanken**: NoSQL und TextDB, in Dateien innerhalb der App gespeichert.\n- **Lokalisierung**: Ressourcendateien und `@(Text)`-Markierungen in Views.\n- **Worker, Tasks und FlowStream**: Hintergrundarbeit und visuelle Datenflüsse.\n- **Der Befehl `total4`**: Templates, Übersetzungen, Bundles und Pakete.\n\n## Wie eine App aufgebaut ist\n\nEine App ist ein Ordner mit einem Startskript (`index.js`) und einigen dieser Ordner. Total.js lädt sie beim Start der App; keiner davon ist Pflicht.\n\n| Ordner | Was hineingehört |\n| --- | --- |\n| `controllers/` | Routen (`exports.install`) und ihre Aktionen |\n| `schemas/` | Schemas und ihre Aktionen |\n| `definitions/` | Code, der beim Start läuft: Helfer, Authentifizierung, Konfiguration |\n| `views/` | HTML-Templates |\n| `public/` | Statische Dateien: CSS, JavaScript, Bilder |\n| `resources/` | Lokalisierungsdateien |\n| `databases/` | Daten von NoSQL, TextDB und Dateispeichern |\n| `modules/`, `plugins/` | Wiederverwendbare Teile einer App |\n| `workers/`, `tasks/` | Hintergrundarbeit |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | JSON-Schemas, Operationen, Middleware und FlowStream-Daten |\n| `private/` | Dateien, die nie ausgeliefert werden |\n\n## Versionen dieser Dokumentation\n\nDieses Projekt dokumentiert das offizielle Total.js 4: das Repository [totaljs/framework4](https://github.com/totaljs/framework4) und das Paket `total4` auf npm (neueste Version **0.0.99**). API-Einträge geben an, **seit** welcher Version es sie gibt, damit du weißt, was du mit der Version deiner App verwenden kannst.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnc1cv61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Introducción","summary":"Total.js 4 es un framework full-stack para Node.js escrito en JavaScript puro, sin dependencias.","markdown":"---\ntitle: \"Introducción\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Introducción\n\n> Total.js 4 es un framework full-stack para Node.js escrito en JavaScript puro, sin dependencias.\n\nTotal.js 4 es un framework full-stack para Node.js escrito en JavaScript puro. Con un solo paquete, `total4`, construye aplicaciones web, API REST, servicios en segundo plano y aplicaciones de escritorio e IoT, y **sin dependencias**: solo Node.js.\n\n## Qué te ofrece\n\n- **Enrutamiento**: una sola función `ROUTE()` para páginas, endpoints REST, manejadores de archivos y WebSockets. Consulta [Enrutamiento](../routing/).\n- **Controladores**: el objeto que responde a una petición (`this.json()`, `this.view()`, `this.plain()`…).\n- **Esquemas y acciones**: entrada validada y operaciones (`insert`, `update`, `read`, las tuyas) que las rutas llaman directamente.\n- **Vistas**: un motor de plantillas para HTML con plantillas (layouts), parciales y localización.\n- **Bases de datos integradas**: NoSQL y TextDB, guardadas en archivos dentro de la app.\n- **Localización**: archivos de recursos y marcadores `@(Text)` en las vistas.\n- **Workers, tareas y FlowStream**: trabajo en segundo plano y flujos de datos visuales.\n- **El comando `total4`**: plantillas, traducciones, bundles y paquetes.\n\n## Cómo se organiza una app\n\nUna app es una carpeta con un script de inicio (`index.js`) y algunas de estas carpetas. Total.js las carga cuando la app arranca; ninguna es obligatoria.\n\n| Carpeta | Qué contiene |\n| --- | --- |\n| `controllers/` | Rutas (`exports.install`) y sus acciones |\n| `schemas/` | Esquemas y sus acciones |\n| `definitions/` | Código que se ejecuta al inicio: helpers, autenticación, configuración |\n| `views/` | Plantillas HTML |\n| `public/` | Archivos estáticos: CSS, JavaScript, imágenes |\n| `resources/` | Archivos de localización |\n| `databases/` | Datos de NoSQL, TextDB y almacenamientos de archivos |\n| `modules/`, `plugins/` | Partes reutilizables de una app |\n| `workers/`, `tasks/` | Trabajo en segundo plano |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | Esquemas JSON, operaciones, middleware y datos de FlowStream |\n| `private/` | Archivos que nunca se sirven |\n\n## Versiones de esta documentación\n\nEste proyecto documenta el Total.js 4 oficial: el repositorio [totaljs/framework4](https://github.com/totaljs/framework4) y el paquete `total4` en npm (última versión **0.0.99**). Las entradas de la API indican **desde** qué versión existen, para que sepas qué puedes usar con la versión de tu app.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnc1cv61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Introduction","summary":"Total.js 4 est un framework full-stack pour Node.js écrit en JavaScript pur, sans dépendances.","markdown":"---\ntitle: Introduction\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Introduction\n\n> Total.js 4 est un framework full-stack pour Node.js écrit en JavaScript pur, sans dépendances.\n\nTotal.js 4 est un framework full-stack pour Node.js écrit en JavaScript pur. Il permet de créer des applications web, des API REST, des services d'arrière-plan, des applications de bureau et IoT avec un seul paquet, `total4`, et **sans dépendances** : seulement Node.js.\n\n## Ce qu'il t'apporte\n\n- **Routage** : une seule fonction `ROUTE()` pour les pages, les endpoints REST, les gestionnaires de fichiers et les WebSockets. Voir [Routage](../routing/).\n- **Contrôleurs** : l'objet qui répond à une requête (`this.json()`, `this.view()`, `this.plain()`…).\n- **Schémas et actions** : des entrées validées et des opérations (`insert`, `update`, `read`, les tiennes) que les routes appellent directement.\n- **Vues** : un moteur de templates HTML avec layouts, vues partielles et localisation.\n- **Bases de données embarquées** : NoSQL et TextDB, stockées dans des fichiers à l'intérieur de l'application.\n- **Localisation** : des fichiers de ressources et des marqueurs `@(Text)` dans les vues.\n- **Workers, tâches et FlowStream** : travail en arrière-plan et flux de données visuels.\n- **La commande `total4`** : templates, traductions, bundles et paquets.\n\n## Organisation d'une application\n\nUne application est un dossier contenant un script de démarrage (`index.js`) et certains de ces dossiers. Total.js les charge au démarrage de l'application ; aucun n'est obligatoire.\n\n| Dossier | Contenu |\n| --- | --- |\n| `controllers/` | Routes (`exports.install`) et leurs actions |\n| `schemas/` | Schémas et leurs actions |\n| `definitions/` | Code exécuté au démarrage : helpers, authentification, configuration |\n| `views/` | Templates HTML |\n| `public/` | Fichiers statiques : CSS, JavaScript, images |\n| `resources/` | Fichiers de localisation |\n| `databases/` | Données de NoSQL, TextDB et des stockages de fichiers |\n| `modules/`, `plugins/` | Parties réutilisables d'une application |\n| `workers/`, `tasks/` | Travail en arrière-plan |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | Schémas JSON, opérations, middleware et données FlowStream |\n| `private/` | Fichiers qui ne sont jamais servis |\n\n## Versions de cette documentation\n\nCe projet documente le Total.js 4 officiel : le dépôt [totaljs/framework4](https://github.com/totaljs/framework4) et le paquet `total4` sur npm (dernière version **0.0.99**). Les entrées de l'API indiquent **depuis** quelle version elles existent, pour que tu saches ce que tu peux utiliser avec la version de ton application.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnc1cv61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Introduzione","summary":"Total.js 4 è un framework full-stack per Node.js scritto in JavaScript puro, senza dipendenze.","markdown":"---\ntitle: Introduzione\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Introduzione\n\n> Total.js 4 è un framework full-stack per Node.js scritto in JavaScript puro, senza dipendenze.\n\nTotal.js 4 è un framework full-stack per Node.js scritto in JavaScript puro. Con un solo pacchetto, `total4`, e **senza dipendenze** (solo Node.js), crea applicazioni web, API REST, servizi in background, applicazioni desktop e IoT.\n\n## Cosa ti offre\n\n- **Routing**: una sola funzione `ROUTE()` per pagine, endpoint REST, gestori di file e WebSocket. Vedi [Routing](../routing/).\n- **Controller**: l'oggetto che risponde a una richiesta (`this.json()`, `this.view()`, `this.plain()`…).\n- **Schemi e azioni**: input validato e operazioni (`insert`, `update`, `read`, le tue) che le route chiamano direttamente.\n- **Viste**: un motore di template per HTML con layout, partial e localizzazione.\n- **Database integrati**: NoSQL e TextDB, salvati in file dentro l'app.\n- **Localizzazione**: file di risorse e marcatori `@(Text)` nelle viste.\n- **Worker, task e FlowStream**: lavoro in background e flussi di dati visuali.\n- **Il comando `total4`**: template, traduzioni, bundle e pacchetti.\n\n## Come è organizzata un'app\n\nUn'app è una cartella con uno script di avvio (`index.js`) e alcune di queste cartelle. Total.js le carica all'avvio dell'app; nessuna è obbligatoria.\n\n| Cartella | Cosa contiene |\n| --- | --- |\n| `controllers/` | Route (`exports.install`) e le loro azioni |\n| `schemas/` | Schemi e le loro azioni |\n| `definitions/` | Codice eseguito all'avvio: helper, autenticazione, configurazione |\n| `views/` | Template HTML |\n| `public/` | File statici: CSS, JavaScript, immagini |\n| `resources/` | File di localizzazione |\n| `databases/` | Dati di NoSQL, TextDB e degli storage di file |\n| `modules/`, `plugins/` | Parti riutilizzabili di un'app |\n| `workers/`, `tasks/` | Lavoro in background |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | JSON schema, operazioni, middleware e dati di FlowStream |\n| `private/` | File che non vengono mai serviti |\n\n## Versioni di questa documentazione\n\nQuesto progetto documenta il Total.js 4 ufficiale: il repository [totaljs/framework4](https://github.com/totaljs/framework4) e il pacchetto `total4` su npm (ultima versione **0.0.99**). Le voci dell'API indicano **da** quale versione esistono, così sai cosa puoi usare con la versione della tua app.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnc1cv61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/introduction/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Úvod","summary":"Total.js 4 je full-stack framework pre Node.js napísaný v čistom JavaScripte, bez závislostí.","markdown":"---\ntitle: \"Úvod\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/introduction/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Úvod\n\n> Total.js 4 je full-stack framework pre Node.js napísaný v čistom JavaScripte, bez závislostí.\n\nTotal.js 4 je full-stack framework pre Node.js napísaný v čistom JavaScripte. Vytvoríš s ním webové aplikácie, REST API, služby na pozadí, desktopové a IoT aplikácie pomocou jedného balíka, `total4`, a **bez závislostí**: stačí Node.js.\n\n## Čo ti dáva\n\n- **Smerovanie**: jedna funkcia `ROUTE()` pre stránky, REST endpointy, obsluhu súborov a WebSockety. Pozri [Smerovanie](../routing/).\n- **Kontroléry**: objekt, ktorý odpovedá na požiadavku (`this.json()`, `this.view()`, `this.plain()`…).\n- **Schémy a akcie**: validovaný vstup a operácie (`insert`, `update`, `read`, vlastné), ktoré trasy volajú priamo.\n- **Views**: šablónovací systém pre HTML s layoutmi, čiastkovými šablónami a lokalizáciou.\n- **Vstavané databázy**: NoSQL a TextDB, uložené v súboroch vnútri aplikácie.\n- **Lokalizácia**: súbory zdrojov a značky `@(Text)` vo views.\n- **Workery, úlohy a FlowStream**: práca na pozadí a vizuálne dátové toky.\n- **Príkaz `total4`**: šablóny, preklady, bundly a balíky.\n\n## Ako je aplikácia usporiadaná\n\nAplikácia je priečinok so spúšťacím skriptom (`index.js`) a niektorými z týchto priečinkov. Total.js ich načíta pri štarte aplikácie; žiadny z nich nie je povinný.\n\n| Priečinok | Čo doň patrí |\n| --- | --- |\n| `controllers/` | Trasy (`exports.install`) a ich akcie |\n| `schemas/` | Schémy a ich akcie |\n| `definitions/` | Kód, ktorý sa spustí pri štarte: pomocné funkcie, autentifikácia, konfigurácia |\n| `views/` | HTML šablóny |\n| `public/` | Statické súbory: CSS, JavaScript, obrázky |\n| `resources/` | Lokalizačné súbory |\n| `databases/` | Dáta NoSQL, TextDB a úložísk súborov |\n| `modules/`, `plugins/` | Znovupoužiteľné časti aplikácie |\n| `workers/`, `tasks/` | Práca na pozadí |\n| `jsonschemas/`, `operations/`, `middleware/`, `flowstreams/` | JSON schémy, operácie, middleware a dáta FlowStream |\n| `private/` | Súbory, ktoré sa nikdy neposielajú klientovi |\n\n## Verzie tejto dokumentácie\n\nTento projekt dokumentuje oficiálny Total.js 4: repozitár [totaljs/framework4](https://github.com/totaljs/framework4) a balík `total4` na npm (najnovšia **0.0.99**). Záznamy API uvádzajú, **od** ktorej verzie existujú, takže vieš, čo môžeš použiť s verziou svojej aplikácie.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Installation and first app","summary":"Install Total.js 4, write the start script and answer your first requests.","markdown":"---\ntitle: Installation and first app\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Installation and first app\n\n> Install Total.js 4, write the start script and answer your first requests.\n\n## Requirements\n\nNode.js. Total.js 4 has no dependencies and does not require a specific version of Node.js; use a current LTS release.\n\n## Install\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## The start script\n\nCreate `index.js`. It is the official start script of Total.js 4, reduced to what you need now:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nRun it:\n\n```bash\nnode index.js\n```\n\nThe app listens on port **8000**. In **debug** mode it restarts by itself when you change a file. In production start it with `node index.js --release`.\n\n## Your first routes\n\nCreate `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nOpen `http://127.0.0.1:8000/` and `http://127.0.0.1:8000/hello/Peter/`. Each action runs with the controller as `this`, and the dynamic parts of the URL arrive as arguments.\n\n## Options of the start script\n\n| Option | What it does |\n| --- | --- |\n| `ip`, `port` | Address and port of the server (default port `8000`) |\n| `unixsocket` | Listens on a Unix socket instead of a port |\n| `config` | Values that override the `config` file |\n| `sleep` | Waits before starting, in milliseconds |\n| `inspector` | Opens the Node.js inspector on a port |\n| `watch` | Extra folders that restart the app in debug mode |\n| `https` | `key` and `cert` to serve HTTPS directly |\n| `cluster`, `cluster_limit` | Runs several processes (`'auto'` scales them) |\n| `servicemode` | Starts without the web server (`--servicemode`) |\n\n## Next\n\nRead [Routing](../routing/) to learn the whole syntax of `ROUTE()`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Installation und erste App","summary":"Installiere Total.js 4, schreibe das Startskript und beantworte deine ersten Anfragen.","markdown":"---\ntitle: Installation und erste App\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Installation und erste App\n\n> Installiere Total.js 4, schreibe das Startskript und beantworte deine ersten Anfragen.\n\n## Voraussetzungen\n\nNode.js. Total.js 4 hat keine Abhängigkeiten und verlangt keine bestimmte Node.js-Version; verwende ein aktuelles LTS-Release.\n\n## Installation\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## Das Startskript\n\nErstelle `index.js`. Das ist das offizielle Startskript von Total.js 4, reduziert auf das, was du jetzt brauchst:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nStarte es:\n\n```bash\nnode index.js\n```\n\nDie App lauscht auf Port **8000**. Im **Debug**-Modus startet sie von selbst neu, wenn du eine Datei änderst. In der Produktion startest du sie mit `node index.js --release`.\n\n## Deine ersten Routen\n\nErstelle `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nÖffne `http://127.0.0.1:8000/` und `http://127.0.0.1:8000/hello/Peter/`. Jede Aktion läuft mit dem Controller als `this`, und die dynamischen Teile der URL kommen als Argumente an.\n\n## Optionen des Startskripts\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `ip`, `port` | Adresse und Port des Servers (Standardport `8000`) |\n| `unixsocket` | Lauscht auf einem Unix-Socket statt auf einem Port |\n| `config` | Werte, die die Datei `config` überschreiben |\n| `sleep` | Wartet vor dem Start, in Millisekunden |\n| `inspector` | Öffnet den Node.js-Inspector auf einem Port |\n| `watch` | Zusätzliche Ordner, die die App im Debug-Modus neu starten |\n| `https` | `key` und `cert`, um HTTPS direkt auszuliefern |\n| `cluster`, `cluster_limit` | Startet mehrere Prozesse (`'auto'` skaliert sie) |\n| `servicemode` | Startet ohne den Webserver (`--servicemode`) |\n\n## Weiter\n\nLies [Routing](../routing/), um die komplette Syntax von `ROUTE()` kennenzulernen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Instalación y primera app","summary":"Instala Total.js 4, escribe el script de inicio y responde a tus primeras peticiones.","markdown":"---\ntitle: \"Instalación y primera app\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Instalación y primera app\n\n> Instala Total.js 4, escribe el script de inicio y responde a tus primeras peticiones.\n\n## Requisitos\n\nNode.js. Total.js 4 no tiene dependencias y no requiere una versión concreta de Node.js; usa una versión LTS actual.\n\n## Instalación\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## El script de inicio\n\nCrea `index.js`. Es el script de inicio oficial de Total.js 4, reducido a lo que necesitas ahora:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nEjecútalo:\n\n```bash\nnode index.js\n```\n\nLa app escucha en el puerto **8000**. En modo **debug** se reinicia sola cuando cambias un archivo. En producción, iníciala con `node index.js --release`.\n\n## Tus primeras rutas\n\nCrea `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nAbre `http://127.0.0.1:8000/` y `http://127.0.0.1:8000/hello/Peter/`. Cada acción se ejecuta con el controlador como `this`, y las partes dinámicas de la URL llegan como argumentos.\n\n## Opciones del script de inicio\n\n| Opción | Qué hace |\n| --- | --- |\n| `ip`, `port` | Dirección y puerto del servidor (puerto por defecto `8000`) |\n| `unixsocket` | Escucha en un socket Unix en lugar de un puerto |\n| `config` | Valores que sobrescriben el archivo `config` |\n| `sleep` | Espera antes de arrancar, en milisegundos |\n| `inspector` | Abre el inspector de Node.js en un puerto |\n| `watch` | Carpetas adicionales que reinician la app en modo debug |\n| `https` | `key` y `cert` para servir HTTPS directamente |\n| `cluster`, `cluster_limit` | Ejecuta varios procesos (`'auto'` los escala) |\n| `servicemode` | Arranca sin el servidor web (`--servicemode`) |\n\n## Siguiente paso\n\nLee [Enrutamiento](../routing/) para aprender toda la sintaxis de `ROUTE()`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Installation et première application","summary":"Installe Total.js 4, écris le script de démarrage et réponds à tes premières requêtes.","markdown":"---\ntitle: \"Installation et première application\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Installation et première application\n\n> Installe Total.js 4, écris le script de démarrage et réponds à tes premières requêtes.\n\n## Prérequis\n\nNode.js. Total.js 4 n'a pas de dépendances et n'exige pas de version précise de Node.js ; utilise une version LTS actuelle.\n\n## Installation\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## Le script de démarrage\n\nCrée `index.js`. C'est le script de démarrage officiel de Total.js 4, réduit à ce dont tu as besoin pour l'instant :\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nLance-le :\n\n```bash\nnode index.js\n```\n\nL'application écoute sur le port **8000**. En mode **debug**, elle redémarre d'elle-même lorsque tu modifies un fichier. En production, démarre-la avec `node index.js --release`.\n\n## Tes premières routes\n\nCrée `controllers/default.js` :\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nOuvre `http://127.0.0.1:8000/` et `http://127.0.0.1:8000/hello/Peter/`. Chaque action s'exécute avec le contrôleur comme `this`, et les parties dynamiques de l'URL arrivent en arguments.\n\n## Options du script de démarrage\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `ip`, `port` | Adresse et port du serveur (port par défaut `8000`) |\n| `unixsocket` | Écoute sur un socket Unix au lieu d'un port |\n| `config` | Valeurs qui remplacent celles du fichier `config` |\n| `sleep` | Attend avant de démarrer, en millisecondes |\n| `inspector` | Ouvre l'inspecteur Node.js sur un port |\n| `watch` | Dossiers supplémentaires qui redémarrent l'application en mode debug |\n| `https` | `key` et `cert` pour servir directement en HTTPS |\n| `cluster`, `cluster_limit` | Lance plusieurs processus (`'auto'` les ajuste automatiquement) |\n| `servicemode` | Démarre sans le serveur web (`--servicemode`) |\n\n## Suite\n\nLis [Routage](../routing/) pour découvrir toute la syntaxe de `ROUTE()`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Installazione e prima app","summary":"Installa Total.js 4, scrivi lo script di avvio e rispondi alle tue prime richieste.","markdown":"---\ntitle: Installazione e prima app\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Installazione e prima app\n\n> Installa Total.js 4, scrivi lo script di avvio e rispondi alle tue prime richieste.\n\n## Requisiti\n\nNode.js. Total.js 4 non ha dipendenze e non richiede una versione specifica di Node.js; usa una versione LTS attuale.\n\n## Installazione\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## Lo script di avvio\n\nCrea `index.js`. È lo script di avvio ufficiale di Total.js 4, ridotto a ciò che ti serve ora:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nEseguilo:\n\n```bash\nnode index.js\n```\n\nL'app è in ascolto sulla porta **8000**. In modalità **debug** si riavvia da sola quando modifichi un file. In produzione avviala con `node index.js --release`.\n\n## Le tue prime route\n\nCrea `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nApri `http://127.0.0.1:8000/` e `http://127.0.0.1:8000/hello/Peter/`. Ogni azione viene eseguita con il controller come `this`, e le parti dinamiche dell'URL arrivano come argomenti.\n\n## Opzioni dello script di avvio\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `ip`, `port` | Indirizzo e porta del server (porta predefinita `8000`) |\n| `unixsocket` | Ascolta su un socket Unix invece che su una porta |\n| `config` | Valori che sovrascrivono il file `config` |\n| `sleep` | Attende prima di avviarsi, in millisecondi |\n| `inspector` | Apre l'inspector di Node.js su una porta |\n| `watch` | Cartelle aggiuntive che riavviano l'app in modalità debug |\n| `https` | `key` e `cert` per servire HTTPS direttamente |\n| `cluster`, `cluster_limit` | Esegue più processi (`'auto'` li scala) |\n| `servicemode` | Si avvia senza il server web (`--servicemode`) |\n\n## Prossimi passi\n\nLeggi [Routing](../routing/) per imparare tutta la sintassi di `ROUTE()`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOnf1ev61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/installation/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Inštalácia a prvá aplikácia","summary":"Nainštaluj Total.js 4, napíš spúšťací skript a odpovedz na svoje prvé požiadavky.","markdown":"---\ntitle: \"Inštalácia a prvá aplikácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/installation/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Inštalácia a prvá aplikácia\n\n> Nainštaluj Total.js 4, napíš spúšťací skript a odpovedz na svoje prvé požiadavky.\n\n## Požiadavky\n\nNode.js. Total.js 4 nemá žiadne závislosti a nevyžaduje konkrétnu verziu Node.js; použi aktuálnu LTS verziu.\n\n## Inštalácia\n\n```bash\nmkdir myapp\ncd myapp\nnpm init -y\nnpm install total4\n```\n\n## Spúšťací skript\n\nVytvor `index.js`. Je to oficiálny spúšťací skript Total.js 4, zredukovaný na to, čo teraz potrebuješ:\n\n```js\nconst options = {};\n\n// options.ip = '127.0.0.1';\n// options.port = parseInt(process.argv[2]);\n// options.config = { name: 'My app' };\n\nvar type = process.argv.indexOf('--release', 1) !== -1 ? 'release' : 'debug';\nrequire('total4/' + type)(options);\n```\n\nSpusti ho:\n\n```bash\nnode index.js\n```\n\nAplikácia počúva na porte **8000**. V režime **debug** sa sama reštartuje, keď zmeníš súbor. V produkcii ju spusti príkazom `node index.js --release`.\n\n## Tvoje prvé trasy\n\nVytvor `controllers/default.js`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /hello/{name}/', hello);\n};\n\nfunction home() {\n\tthis.plain('Hello world');\n}\n\nfunction hello(name) {\n\tthis.json({ hello: name });\n}\n```\n\nOtvor `http://127.0.0.1:8000/` a `http://127.0.0.1:8000/hello/Peter/`. Každá akcia beží s kontrolérom ako `this` a dynamické časti URL prichádzajú ako argumenty.\n\n## Možnosti spúšťacieho skriptu\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `ip`, `port` | Adresa a port servera (predvolený port `8000`) |\n| `unixsocket` | Počúva na Unix sockete namiesto portu |\n| `config` | Hodnoty, ktoré prepíšu súbor `config` |\n| `sleep` | Pred štartom počká, v milisekundách |\n| `inspector` | Otvorí Node.js inspector na porte |\n| `watch` | Ďalšie priečinky, ktoré v režime debug reštartujú aplikáciu |\n| `https` | `key` a `cert` na priame poskytovanie HTTPS |\n| `cluster`, `cluster_limit` | Spustí viac procesov (`'auto'` ich škáluje) |\n| `servicemode` | Spustí sa bez webového servera (`--servicemode`) |\n\n## Ďalej\n\nPrečítaj si [Smerovanie](../routing/), aby si spoznal celú syntax `ROUTE()`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Routing","summary":"Methods, dynamic parameters, signed-in users, schemas, API routes, views and flags of ROUTE().","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> Methods, dynamic parameters, signed-in users, schemas, API routes, views and flags of ROUTE().\n\nEvery route is declared with `ROUTE()`, usually inside `exports.install` of a file in `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nThe first argument describes the route in one line: **method**, **URL**, and optionally a **schema operation**, **middleware**, **roles** and **flags**. The full list of arguments is in the reference of [ROUTE()](../../reference/routing/).\n\n## Methods\n\n`GET` is the default. Write the method before the URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Several methods are separated by commas:\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Dynamic parameters\n\nParts in braces are parameters. They arrive as arguments of the action, in their order, and in `this.params`:\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nA parameter can have a type: `{page:number}`, `{active:boolean}` and `{date:date}` are converted in `this.params`. `{id:uid}` and `{id:guid}` accept only identifiers of that kind.\n\nA `*` at the end of the URL matches the rest of the path:\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Signed-in users\n\n`+` before the method allows only requests that your `AUTH()` delegate accepted, and `-` only the others. A role (`@admin`) implies a signed-in user:\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Schemas and actions\n\nA route can call operations of a schema without writing an action. `*Schema --> operation` validates the request body with the schema and runs the operation:\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nSeveral operations run one after another. `(response)` after one of them says whose result is sent back:\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## API routes\n\n`API` groups many operations behind one URL. The client sends `POST` with `{ \"schema\": \"name/params\", \"data\": {} }`; `+` marks the operations that take data and `-` those that do not:\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Views\n\nAn action can be the name of a view. Without an action, the view is chosen from the URL:\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flags\n\nFlags change how a route works. Write them in the URL after a space, or pass them as an array:\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw`: the body comes as JSON, XML or raw data (the route becomes `POST`).\n- `upload`: the body is `multipart/form-data` with files.\n- `cors`, origins (`https://app.com`) and `credentials`: cross-origin requests.\n- `csrf`, `referer`: checks the CSRF token or the referer.\n- `mobile`, `robot`: only for mobile devices, or only for crawlers.\n- `encrypt`: the answer is encrypted.\n- `delay`: the request has no timeout.\n- `novalidate`: the schema converts the body without validating it.\n- A number: the timeout of the request in milliseconds (default `3000`).\n- `#name` or `&name`: runs a middleware first.\n- `// text`: a description of the route.\n\n## Request size\n\nThe last argument limits the size of the request body, in **kilobytes** (default `10`). It is needed for big JSON bodies and uploads:\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## Files and WebSockets\n\n`FILE` routes handle static-like files and `SOCKET` routes open WebSockets; they have their own pages in the reference.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Subdomains and removing routes\n\nA route only for a subdomain starts with it in brackets: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` removes a route that was declared before.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Routing","summary":"Methoden, dynamische Parameter, angemeldete Benutzer, Schemas, API-Routen, Views und Flags von ROUTE().","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> Methoden, dynamische Parameter, angemeldete Benutzer, Schemas, API-Routen, Views und Flags von ROUTE().\n\nJede Route wird mit `ROUTE()` deklariert, meist innerhalb von `exports.install` einer Datei in `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nDas erste Argument beschreibt die Route in einer Zeile: **Methode**, **URL** und optional eine **Schema-Operation**, **Middleware**, **Rollen** und **Flags**. Die vollständige Liste der Argumente steht in der Referenz von [ROUTE()](../../reference/routing/).\n\n## Methoden\n\n`GET` ist der Standard. Schreibe die Methode vor die URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Mehrere Methoden trennst du durch Kommas:\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Dynamische Parameter\n\nTeile in geschweiften Klammern sind Parameter. Sie kommen als Argumente der Aktion an, in ihrer Reihenfolge, und in `this.params`:\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nEin Parameter kann einen Typ haben: `{page:number}`, `{active:boolean}` und `{date:date}` werden in `this.params` konvertiert. `{id:uid}` und `{id:guid}` akzeptieren nur Bezeichner dieser Art.\n\nEin `*` am Ende der URL passt auf den Rest des Pfads:\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Angemeldete Benutzer\n\n`+` vor der Methode lässt nur Anfragen zu, die dein `AUTH()`-Delegate akzeptiert hat, und `-` nur die anderen. Eine Rolle (`@admin`) setzt einen angemeldeten Benutzer voraus:\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Schemas und Aktionen\n\nEine Route kann Operationen eines Schemas aufrufen, ohne dass du eine Aktion schreibst. `*Schema --> operation` validiert den Body der Anfrage mit dem Schema und führt die Operation aus:\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nMehrere Operationen laufen nacheinander. `(response)` nach einer von ihnen legt fest, wessen Ergebnis zurückgesendet wird:\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## API-Routen\n\n`API` bündelt viele Operationen hinter einer URL. Der Client sendet `POST` mit `{ \"schema\": \"name/params\", \"data\": {} }`; `+` markiert die Operationen, die Daten annehmen, und `-` die, die keine annehmen:\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Views\n\nEine Aktion kann der Name einer View sein. Ohne Aktion wird die View anhand der URL gewählt:\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flags\n\nFlags ändern, wie eine Route arbeitet. Schreibe sie nach einem Leerzeichen in die URL oder übergib sie als Array:\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw`: Der Body kommt als JSON, XML oder Rohdaten (die Route wird zu `POST`).\n- `upload`: Der Body ist `multipart/form-data` mit Dateien.\n- `cors`, Origins (`https://app.com`) und `credentials`: Cross-Origin-Anfragen.\n- `csrf`, `referer`: prüft das CSRF-Token oder den Referer.\n- `mobile`, `robot`: nur für Mobilgeräte oder nur für Crawler.\n- `encrypt`: Die Antwort wird verschlüsselt.\n- `delay`: Die Anfrage hat kein Timeout.\n- `novalidate`: Das Schema konvertiert den Body, ohne ihn zu validieren.\n- Eine Zahl: das Timeout der Anfrage in Millisekunden (Standard `3000`).\n- `#name` oder `&name`: führt zuerst eine Middleware aus.\n- `// text`: eine Beschreibung der Route.\n\n## Größe der Anfrage\n\nDas letzte Argument begrenzt die Größe des Bodys der Anfrage, in **Kilobyte** (Standard `10`). Du brauchst es für große JSON-Bodys und Uploads:\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## Dateien und WebSockets\n\n`FILE`-Routen verarbeiten Dateien ähnlich wie statische Dateien, und `SOCKET`-Routen öffnen WebSockets; sie haben eigene Seiten in der Referenz.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Subdomains und Entfernen von Routen\n\nEine Route nur für eine Subdomain beginnt mit dieser in eckigen Klammern: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` entfernt eine zuvor deklarierte Route.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Enrutamiento","summary":"Métodos, parámetros dinámicos, usuarios autenticados, esquemas, rutas API, vistas y flags de ROUTE().","markdown":"---\ntitle: Enrutamiento\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Enrutamiento\n\n> Métodos, parámetros dinámicos, usuarios autenticados, esquemas, rutas API, vistas y flags de ROUTE().\n\nCada ruta se declara con `ROUTE()`, normalmente dentro de `exports.install` de un archivo en `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nEl primer argumento describe la ruta en una línea: **método**, **URL** y, opcionalmente, una **operación de esquema**, **middleware**, **roles** y **flags**. La lista completa de argumentos está en la referencia de [ROUTE()](../../reference/routing/).\n\n## Métodos\n\n`GET` es el método por defecto. Escribe el método antes de la URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Varios métodos se separan con comas:\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Parámetros dinámicos\n\nLas partes entre llaves son parámetros. Llegan como argumentos de la acción, en su orden, y en `this.params`:\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nUn parámetro puede tener un tipo: `{page:number}`, `{active:boolean}` y `{date:date}` se convierten en `this.params`. `{id:uid}` y `{id:guid}` solo aceptan identificadores de ese tipo.\n\nUn `*` al final de la URL coincide con el resto de la ruta:\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Usuarios autenticados\n\n`+` antes del método permite solo las peticiones que tu delegado `AUTH()` aceptó, y `-` solo las demás. Un rol (`@admin`) implica un usuario autenticado:\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Esquemas y acciones\n\nUna ruta puede llamar a operaciones de un esquema sin escribir una acción. `*Schema --> operation` valida el cuerpo de la petición con el esquema y ejecuta la operación:\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nVarias operaciones se ejecutan una tras otra. `(response)` después de una de ellas indica qué resultado se devuelve:\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## Rutas API\n\n`API` agrupa muchas operaciones detrás de una URL. El cliente envía `POST` con `{ \"schema\": \"name/params\", \"data\": {} }`; `+` marca las operaciones que reciben datos y `-` las que no:\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Vistas\n\nUna acción puede ser el nombre de una vista. Sin acción, la vista se elige a partir de la URL:\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flags\n\nLos flags cambian cómo funciona una ruta. Escríbelos en la URL después de un espacio, o pásalos como un array:\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw`: el cuerpo llega como JSON, XML o datos sin procesar (la ruta pasa a ser `POST`).\n- `upload`: el cuerpo es `multipart/form-data` con archivos.\n- `cors`, orígenes (`https://app.com`) y `credentials`: peticiones de origen cruzado.\n- `csrf`, `referer`: comprueba el token CSRF o el referer.\n- `mobile`, `robot`: solo para dispositivos móviles, o solo para rastreadores.\n- `encrypt`: la respuesta va cifrada.\n- `delay`: la petición no tiene tiempo de espera.\n- `novalidate`: el esquema convierte el cuerpo sin validarlo.\n- Un número: el tiempo de espera de la petición en milisegundos (por defecto `3000`).\n- `#name` o `&name`: ejecuta antes un middleware.\n- `// text`: una descripción de la ruta.\n\n## Tamaño de la petición\n\nEl último argumento limita el tamaño del cuerpo de la petición, en **kilobytes** (por defecto `10`). Es necesario para cuerpos JSON grandes y subidas de archivos:\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## Archivos y WebSockets\n\nLas rutas `FILE` manejan archivos tipo estáticos y las rutas `SOCKET` abren WebSockets; tienen sus propias páginas en la referencia.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Subdominios y eliminación de rutas\n\nUna ruta solo para un subdominio empieza con él entre corchetes: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` elimina una ruta declarada antes.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Routage","summary":"Méthodes, paramètres dynamiques, utilisateurs connectés, schémas, routes API, vues et flags de ROUTE().","markdown":"---\ntitle: Routage\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routage\n\n> Méthodes, paramètres dynamiques, utilisateurs connectés, schémas, routes API, vues et flags de ROUTE().\n\nChaque route est déclarée avec `ROUTE()`, généralement dans `exports.install` d'un fichier de `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nLe premier argument décrit la route en une ligne : **méthode**, **URL** et, en option, une **opération de schéma**, un **middleware**, des **rôles** et des **flags**. La liste complète des arguments se trouve dans la référence de [ROUTE()](../../reference/routing/).\n\n## Méthodes\n\n`GET` est la méthode par défaut. Écris la méthode avant l'URL : `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Plusieurs méthodes sont séparées par des virgules :\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Paramètres dynamiques\n\nLes parties entre accolades sont des paramètres. Elles arrivent en arguments de l'action, dans leur ordre, et dans `this.params` :\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nUn paramètre peut avoir un type : `{page:number}`, `{active:boolean}` et `{date:date}` sont convertis dans `this.params`. `{id:uid}` et `{id:guid}` n'acceptent que des identifiants de ce type.\n\nUn `*` à la fin de l'URL correspond au reste du chemin :\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Utilisateurs connectés\n\n`+` avant la méthode n'autorise que les requêtes acceptées par ton délégué `AUTH()`, et `-` uniquement les autres. Un rôle (`@admin`) implique un utilisateur connecté :\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Schémas et actions\n\nUne route peut appeler des opérations d'un schéma sans écrire d'action. `*Schema --> operation` valide le corps de la requête avec le schéma et exécute l'opération :\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nPlusieurs opérations s'exécutent l'une après l'autre. `(response)` après l'une d'elles indique quel résultat est renvoyé :\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## Routes API\n\n`API` regroupe de nombreuses opérations derrière une seule URL. Le client envoie `POST` avec `{ \"schema\": \"name/params\", \"data\": {} }` ; `+` marque les opérations qui reçoivent des données et `-` celles qui n'en reçoivent pas :\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Vues\n\nUne action peut être le nom d'une vue. Sans action, la vue est choisie d'après l'URL :\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flags\n\nLes flags modifient le fonctionnement d'une route. Écris-les dans l'URL après un espace, ou passe-les sous forme de tableau :\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw` : le corps arrive en JSON, en XML ou en données brutes (la route devient `POST`).\n- `upload` : le corps est en `multipart/form-data` avec des fichiers.\n- `cors`, les origines (`https://app.com`) et `credentials` : requêtes cross-origin.\n- `csrf`, `referer` : vérifie le jeton CSRF ou le referer.\n- `mobile`, `robot` : uniquement pour les appareils mobiles, ou uniquement pour les robots d'indexation.\n- `encrypt` : la réponse est chiffrée.\n- `delay` : la requête n'a pas de délai d'expiration.\n- `novalidate` : le schéma convertit le corps sans le valider.\n- Un nombre : le délai d'expiration de la requête en millisecondes (par défaut `3000`).\n- `#name` ou `&name` : exécute d'abord un middleware.\n- `// text` : une description de la route.\n\n## Taille de la requête\n\nLe dernier argument limite la taille du corps de la requête, en **kilooctets** (par défaut `10`). Il est nécessaire pour les gros corps JSON et les uploads :\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## Fichiers et WebSockets\n\nLes routes `FILE` gèrent des fichiers de type statique et les routes `SOCKET` ouvrent des WebSockets ; elles ont leurs propres pages dans la référence.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Sous-domaines et suppression de routes\n\nUne route réservée à un sous-domaine commence par celui-ci entre crochets : `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` supprime une route déclarée auparavant.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Routing","summary":"Metodi, parametri dinamici, utenti autenticati, schemi, route API, viste e flag di ROUTE().","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> Metodi, parametri dinamici, utenti autenticati, schemi, route API, viste e flag di ROUTE().\n\nOgni route si dichiara con `ROUTE()`, di solito dentro `exports.install` di un file in `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nIl primo argomento descrive la route in una riga: **metodo**, **URL** e, facoltativamente, un'**operazione di schema**, **middleware**, **ruoli** e **flag**. L'elenco completo degli argomenti è nel riferimento di [ROUTE()](../../reference/routing/).\n\n## Metodi\n\n`GET` è il valore predefinito. Scrivi il metodo prima dell'URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Più metodi si separano con virgole:\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Parametri dinamici\n\nLe parti tra parentesi graffe sono parametri. Arrivano come argomenti dell'azione, nel loro ordine, e in `this.params`:\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nUn parametro può avere un tipo: `{page:number}`, `{active:boolean}` e `{date:date}` vengono convertiti in `this.params`. `{id:uid}` e `{id:guid}` accettano solo identificatori di quel tipo.\n\nUn `*` alla fine dell'URL corrisponde al resto del percorso:\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Utenti autenticati\n\n`+` prima del metodo ammette solo le richieste che il tuo delegato `AUTH()` ha accettato, e `-` solo le altre. Un ruolo (`@admin`) implica un utente autenticato:\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Schemi e azioni\n\nUna route può chiamare operazioni di uno schema senza scrivere un'azione. `*Schema --> operation` valida il corpo della richiesta con lo schema ed esegue l'operazione:\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nPiù operazioni vengono eseguite una dopo l'altra. `(response)` dopo una di esse indica quale risultato viene restituito:\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## Route API\n\n`API` raggruppa molte operazioni dietro un solo URL. Il client invia `POST` con `{ \"schema\": \"name/params\", \"data\": {} }`; `+` contrassegna le operazioni che ricevono dati e `-` quelle che non ne ricevono:\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Viste\n\nUn'azione può essere il nome di una vista. Senza azione, la vista viene scelta dall'URL:\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flag\n\nI flag cambiano il funzionamento di una route. Scrivili nell'URL dopo uno spazio, oppure passali come array:\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw`: il corpo arriva come JSON, XML o dati grezzi (la route diventa `POST`).\n- `upload`: il corpo è `multipart/form-data` con file.\n- `cors`, origini (`https://app.com`) e `credentials`: richieste cross-origin.\n- `csrf`, `referer`: verifica il token CSRF o il referer.\n- `mobile`, `robot`: solo per dispositivi mobili, o solo per i crawler.\n- `encrypt`: la risposta è cifrata.\n- `delay`: la richiesta non ha timeout.\n- `novalidate`: lo schema converte il corpo senza validarlo.\n- Un numero: il timeout della richiesta in millisecondi (predefinito `3000`).\n- `#name` o `&name`: esegue prima un middleware.\n- `// text`: una descrizione della route.\n\n## Dimensione della richiesta\n\nL'ultimo argomento limita la dimensione del corpo della richiesta, in **kilobyte** (predefinito `10`). Serve per corpi JSON grandi e per gli upload:\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## File e WebSocket\n\nLe route `FILE` gestiscono file simili a quelli statici e le route `SOCKET` aprono WebSocket; hanno le loro pagine nel riferimento.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Sottodomini e rimozione delle route\n\nUna route solo per un sottodominio inizia con esso tra parentesi quadre: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` rimuove una route dichiarata in precedenza.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOni1gv61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/routing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Smerovanie","summary":"Metódy, dynamické parametre, prihlásení používatelia, schémy, API trasy, views a flagy funkcie ROUTE().","markdown":"---\ntitle: Smerovanie\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Smerovanie\n\n> Metódy, dynamické parametre, prihlásení používatelia, schémy, API trasy, views a flagy funkcie ROUTE().\n\nKaždá trasa sa deklaruje pomocou `ROUTE()`, zvyčajne vnútri `exports.install` súboru v `controllers/`.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n\tROUTE('POST /products/', create);\n};\n```\n\nPrvý argument opisuje trasu na jednom riadku: **metódu**, **URL** a voliteľne **operáciu schémy**, **middleware**, **roly** a **flagy**. Úplný zoznam argumentov nájdeš v referencii [ROUTE()](../../reference/routing/).\n\n## Metódy\n\n`GET` je predvolená. Metódu napíš pred URL: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`. Viac metód sa oddeľuje čiarkami:\n\n```js\nROUTE('GET,POST /contact/', contact);\n```\n\n## Dynamické parametre\n\nČasti v zložených zátvorkách sú parametre. Prichádzajú ako argumenty akcie, v ich poradí, a v `this.params`:\n\n```js\nROUTE('GET /users/{id}/', read);\nROUTE('GET /blog/{year}/{slug}/', article);\n\nfunction article(year, slug) {\n\t// this.params.year, this.params.slug\n}\n```\n\nParameter môže mať typ: `{page:number}`, `{active:boolean}` a `{date:date}` sa v `this.params` skonvertujú. `{id:uid}` a `{id:guid}` prijímajú len identifikátory daného druhu.\n\n`*` na konci URL zodpovedá zvyšku cesty:\n\n```js\nROUTE('GET /docs/*', docs);\n```\n\n## Prihlásení používatelia\n\n`+` pred metódou povolí len požiadavky, ktoré prijal tvoj delegát `AUTH()`, a `-` len ostatné. Rola (`@admin`) predpokladá prihláseného používateľa:\n\n```js\nROUTE('+GET /account/', account);\nROUTE('-GET /login/', login);\nROUTE('+GET /admin/ @admin', admin);\n```\n\n## Schémy a akcie\n\nTrasa môže volať operácie schémy bez toho, aby si písal akciu. `*Schema --> operation` validuje telo požiadavky schémou a spustí operáciu:\n\n```js\nROUTE('POST /api/users/ *Users --> insert');\nROUTE('GET  /api/users/{id}/ *Users --> read');\n```\n\nViac operácií beží jedna po druhej. `(response)` za jednou z nich určuje, ktorej výsledok sa pošle späť:\n\n```js\nROUTE('POST /api/orders/ *Orders --> check insert (response) notify');\n```\n\n## API trasy\n\n`API` zoskupuje veľa operácií za jednou URL. Klient pošle `POST` s `{ \"schema\": \"name/params\", \"data\": {} }`; `+` označuje operácie, ktoré prijímajú dáta, a `-` tie, ktoré nie:\n\n```js\nROUTE('API /api/ -users_list        *Users --> list');\nROUTE('API /api/ -users_read/{id}   *Users --> read');\nROUTE('API /api/ +users_save        *Users --> save');\n```\n\n## Views\n\nAkcia môže byť názov view. Bez akcie sa view vyberie podľa URL:\n\n```js\nROUTE('GET /about/', 'about');   // views/about.html\nROUTE('GET /pricing/');           // views/pricing.html\n```\n\n## Flagy\n\nFlagy menia, ako trasa funguje. Napíš ich do URL za medzeru alebo ich odovzdaj ako pole:\n\n```js\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n- `json`, `xml`, `raw`: telo prichádza ako JSON, XML alebo surové dáta (trasa sa stane `POST`).\n- `upload`: telo je `multipart/form-data` so súbormi.\n- `cors`, pôvody (`https://app.com`) a `credentials`: požiadavky z iných pôvodov (cross-origin).\n- `csrf`, `referer`: kontroluje CSRF token alebo referer.\n- `mobile`, `robot`: len pre mobilné zariadenia alebo len pre crawlery.\n- `encrypt`: odpoveď je zašifrovaná.\n- `delay`: požiadavka nemá časový limit.\n- `novalidate`: schéma skonvertuje telo bez validácie.\n- Číslo: časový limit požiadavky v milisekundách (predvolene `3000`).\n- `#name` alebo `&name`: najprv spustí middleware.\n- `// text`: popis trasy.\n\n## Veľkosť požiadavky\n\nPosledný argument obmedzuje veľkosť tela požiadavky v **kilobajtoch** (predvolene `10`). Je potrebný pre veľké JSON telá a nahrávanie súborov:\n\n```js\nROUTE('POST /api/import/ json', importdata, 1024);   // 1 MB\n```\n\n## Súbory a WebSockety\n\nTrasy `FILE` obsluhujú súbory podobné statickým a trasy `SOCKET` otvárajú WebSockety; v referencii majú vlastné stránky.\n\n```js\nROUTE('FILE /docs/*.pdf', pdf);\nROUTE('SOCKET /chat/', chat);\n```\n\n## Subdomény a odstraňovanie trás\n\nTrasa len pre subdoménu začína subdoménou v hranatých zátvorkách: `ROUTE('[api]/users/', users)`. `ROUTE(url, null)` odstráni trasu, ktorá bola deklarovaná predtým.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Controllers","summary":"The controller is `this` in every route action: it holds the request data and answers the request.","markdown":"---\ntitle: Controllers\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controllers\n\n> The controller is `this` in every route action: it holds the request data and answers the request.\n\nEvery action of a route runs with a **controller** as `this`. The controller holds the data of the request and has the methods that answer it. A new controller is created for each request.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nThe dynamic parts of the URL arrive as arguments of the action, in their order. The full list of properties and methods is in the reference of [Controller](../../reference/controller/).\n\n## Request data\n\n| Property | What it contains |\n| --- | --- |\n| `this.body` | The parsed body of the request (JSON or a form) |\n| `this.query` | The query string as an object (`?page=2` gives `{ page: '2' }`) |\n| `this.params` | The dynamic parameters of the URL, converted by their type (`{page:number}`) |\n| `this.files` | Uploaded files, for routes with the `upload` flag |\n| `this.user` | The user that your `AUTH()` delegate accepted, or `undefined` |\n| `this.headers` | The request headers, with lower-case names |\n| `this.ip` | The IP address of the client (the first `X-Forwarded-For` address behind a proxy) |\n| `this.url` | The path of the URL in lower case, with a trailing slash |\n| `this.uri` | The parsed URL (`pathname`, `query`, `hostname`…) |\n| `this.ua` | A short name of the browser and the system, parsed from `User-Agent` |\n| `this.mobile`, `this.robot` | `true` for mobile devices, or for crawlers |\n| `this.xhr` | `true` when the request has `X-Requested-With: XMLHttpRequest` |\n| `this.referrer` | The `Referer` header, or an empty string |\n| `this.language` | The language set by your localization delegate |\n| `this.req`, `this.res` | The request and the response objects of the framework |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` and `this.body` contain strings: convert numbers and dates yourself, or let a schema do it (see [Routing](../routing/)).\n\n## Uploaded files\n\nA route with the `upload` flag reads `multipart/form-data`. Each item of `this.files` has `name` (the field), `filename`, `type`, `size`, `extension`, and `width` and `height` for images. `move()`, `copy()` and `read()` return a promise when you do not pass a callback:\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nThe framework removes the temporary files when the request ends. Call `this.autoclear(false)` to keep them.\n\n## Answering\n\nAnswer each request **once**. The methods return the controller, so you can call `return this.json(...)` to stop the action.\n\n| Method | Answer |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Plain text; an object is serialized as formatted JSON |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | Any text with your content type |\n| `this.view(name, [model])` | A rendered view from `views/` |\n| `this.file(filename, [download])` | A file from `public/` (or any path that starts with `~`) |\n| `this.binary(buffer, type)` | A buffer |\n| `this.stream(stream, type)` | A readable stream |\n| `this.redirect(url, [permanent])` | A redirect, `302` or `301` |\n| `this.empty()` | An empty body |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | An error as JSON, `400` by default |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## The status code\n\nSet `this.status` before you answer. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` and `empty()` use it; the default is `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` sets the status and answers in one call.\n\n## Success and validation errors\n\n`this.success()` answers `{ \"success\": true }`. With a value it answers `{ \"success\": true, \"value\": ... }`, and `this.success(false)` answers `{ \"success\": false }`.\n\n`this.invalid()` answers an array of errors as JSON with the status `400`. A number as the first argument sets another status:\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nTwo helpers create callbacks in the style `(err, response)`. `this.done()` answers `invalid(err)` on error and `success()` otherwise; `this.done(true)` adds the response as `value`. `this.callback()` answers the response as JSON, or with a view when you pass its name:\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Error pages\n\n`this.throw404()` and its siblings answer with an error page: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` and `throw503()`. They have aliases named `view400()`… `view503()`. The argument is a description of the problem; `throw500(err)` also logs the error.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nTo render your own page, declare a route for the status. The problem is in `this.exception`:\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nWithout such a route the framework renders its own error page.\n\n## Headers and cache\n\n`this.header(name, value)` sets a header of the response. Most answering methods also take an object with headers. `this.nocache()` disables the HTTP cache of the answer:\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookies\n\n`this.cookie(name)` reads a cookie. `this.cookie(name, value, expires, [options])` writes it; `expires` is a text such as `'5 days'`, and options are `domain`, `path` (`/`), `secure`, `httponly` and `samesite` (`Lax` by default):\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Views and layouts\n\n`this.view(name, [model])` renders `views/name.html` inside the layout `views/layout.html`. Routes of `controllers/default.js` find their views in `views/`; routes of another controller, for example `controllers/admin.js`, in `views/admin/`. A name that starts with `~` always starts in `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` chooses another layout; `this.layout('')` renders the view without a layout.\n- `this.title()` and `this.meta(title, [description], [keywords], [image])` set values the layout prints with `@{title}` and `@{meta}`.\n- `this.repository` is an object shared by the view and its layout.\n- `this.view(name, model, true)` returns the HTML as a string instead of answering.\n\nThe template syntax is explained in [Views](../views/).\n\n## Signed-in users\n\n`this.user` is what your `AUTH()` delegate accepted. Routes with `+` run only for signed-in users, so `this.user` always exists there:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Errors in actions\n\nAn exception thrown in an action is logged and the request gets the error page `500`. In callbacks and promises nothing catches the exception for you: catch it and call `this.throw500(err)` or `this.invalid(err)`.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Controller","summary":"Der Controller ist `this` in jeder Aktion einer Route: Er enthält die Daten der Anfrage und beantwortet sie.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Der Controller ist `this` in jeder Aktion einer Route: Er enthält die Daten der Anfrage und beantwortet sie.\n\nJede Aktion einer Route läuft mit einem **Controller** als `this`. Der Controller enthält die Daten der Anfrage und hat die Methoden, die sie beantworten. Für jede Anfrage wird ein neuer Controller erstellt.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nDie dynamischen Teile der URL kommen als Argumente der Aktion an, in ihrer Reihenfolge. Die vollständige Liste der Eigenschaften und Methoden steht in der Referenz von [Controller](../../reference/controller/).\n\n## Daten der Anfrage\n\n| Eigenschaft | Was sie enthält |\n| --- | --- |\n| `this.body` | Der geparste Body der Anfrage (JSON oder ein Formular) |\n| `this.query` | Der Query-String als Objekt (`?page=2` ergibt `{ page: '2' }`) |\n| `this.params` | Die dynamischen Parameter der URL, nach ihrem Typ konvertiert (`{page:number}`) |\n| `this.files` | Hochgeladene Dateien, für Routen mit dem Flag `upload` |\n| `this.user` | Der Benutzer, den dein `AUTH()`-Delegate akzeptiert hat, oder `undefined` |\n| `this.headers` | Die Header der Anfrage, mit kleingeschriebenen Namen |\n| `this.ip` | Die IP-Adresse des Clients (hinter einem Proxy die erste Adresse aus `X-Forwarded-For`) |\n| `this.url` | Der Pfad der URL in Kleinbuchstaben, mit abschließendem Schrägstrich |\n| `this.uri` | Die geparste URL (`pathname`, `query`, `hostname`…) |\n| `this.ua` | Ein Kurzname des Browsers und des Systems, aus `User-Agent` geparst |\n| `this.mobile`, `this.robot` | `true` für Mobilgeräte bzw. für Crawler |\n| `this.xhr` | `true`, wenn die Anfrage `X-Requested-With: XMLHttpRequest` hat |\n| `this.referrer` | Der Header `Referer` oder ein leerer String |\n| `this.language` | Die Sprache, die dein Lokalisierungs-Delegate gesetzt hat |\n| `this.req`, `this.res` | Die Request- und Response-Objekte des Frameworks |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` und `this.body` enthalten Strings: Konvertiere Zahlen und Datumswerte selbst oder überlass das einem Schema (siehe [Routing](../routing/)).\n\n## Hochgeladene Dateien\n\nEine Route mit dem Flag `upload` liest `multipart/form-data`. Jedes Element von `this.files` hat `name` (das Feld), `filename`, `type`, `size`, `extension` und bei Bildern `width` und `height`. `move()`, `copy()` und `read()` geben ein Promise zurück, wenn du keinen Callback übergibst:\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nDas Framework entfernt die temporären Dateien, wenn die Anfrage endet. Rufe `this.autoclear(false)` auf, um sie zu behalten.\n\n## Antworten\n\nBeantworte jede Anfrage **einmal**. Die Methoden geben den Controller zurück, sodass du mit `return this.json(...)` die Aktion beenden kannst.\n\n| Methode | Antwort |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Reiner Text; ein Objekt wird als formatiertes JSON serialisiert |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | Beliebiger Text mit deinem Content-Type |\n| `this.view(name, [model])` | Eine gerenderte View aus `views/` |\n| `this.file(filename, [download])` | Eine Datei aus `public/` (oder ein beliebiger Pfad, der mit `~` beginnt) |\n| `this.binary(buffer, type)` | Ein Buffer |\n| `this.stream(stream, type)` | Ein lesbarer Stream |\n| `this.redirect(url, [permanent])` | Eine Weiterleitung, `302` oder `301` |\n| `this.empty()` | Ein leerer Body |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | Ein Fehler als JSON, standardmäßig `400` |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## Der Statuscode\n\nSetze `this.status`, bevor du antwortest. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` und `empty()` verwenden ihn; der Standard ist `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` setzt den Status und antwortet in einem Aufruf.\n\n## Erfolg und Validierungsfehler\n\n`this.success()` antwortet mit `{ \"success\": true }`. Mit einem Wert antwortet es mit `{ \"success\": true, \"value\": ... }`, und `this.success(false)` antwortet mit `{ \"success\": false }`.\n\n`this.invalid()` antwortet mit einem Array von Fehlern als JSON und dem Status `400`. Eine Zahl als erstes Argument setzt einen anderen Status:\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nZwei Helfer erstellen Callbacks im Stil `(err, response)`. `this.done()` antwortet bei einem Fehler mit `invalid(err)` und sonst mit `success()`; `this.done(true)` fügt die Antwort als `value` hinzu. `this.callback()` antwortet mit der Antwort als JSON oder mit einer View, wenn du ihren Namen übergibst:\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Fehlerseiten\n\n`this.throw404()` und seine Geschwister antworten mit einer Fehlerseite: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` und `throw503()`. Sie haben Aliase namens `view400()`… `view503()`. Das Argument ist eine Beschreibung des Problems; `throw500(err)` protokolliert den Fehler zusätzlich.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nUm eine eigene Seite zu rendern, deklarierst du eine Route für den Status. Das Problem steht in `this.exception`:\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nOhne eine solche Route rendert das Framework seine eigene Fehlerseite.\n\n## Header und Cache\n\n`this.header(name, value)` setzt einen Header der Antwort. Die meisten Antwortmethoden nehmen außerdem ein Objekt mit Headern an. `this.nocache()` deaktiviert den HTTP-Cache der Antwort:\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookies\n\n`this.cookie(name)` liest ein Cookie. `this.cookie(name, value, expires, [options])` schreibt es; `expires` ist ein Text wie `'5 days'`, und die Optionen sind `domain`, `path` (`/`), `secure`, `httponly` und `samesite` (standardmäßig `Lax`):\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Views und Layouts\n\n`this.view(name, [model])` rendert `views/name.html` innerhalb des Layouts `views/layout.html`. Routen aus `controllers/default.js` finden ihre Views in `views/`; Routen eines anderen Controllers, zum Beispiel `controllers/admin.js`, in `views/admin/`. Ein Name, der mit `~` beginnt, beginnt immer in `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` wählt ein anderes Layout; `this.layout('')` rendert die View ohne Layout.\n- `this.title()` und `this.meta(title, [description], [keywords], [image])` setzen Werte, die das Layout mit `@{title}` und `@{meta}` ausgibt.\n- `this.repository` ist ein Objekt, das sich die View und ihr Layout teilen.\n- `this.view(name, model, true)` gibt das HTML als String zurück, statt zu antworten.\n\nDie Template-Syntax wird in [Views](../views/) erklärt.\n\n## Angemeldete Benutzer\n\n`this.user` ist das, was dein `AUTH()`-Delegate akzeptiert hat. Routen mit `+` laufen nur für angemeldete Benutzer, daher existiert `this.user` dort immer:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Fehler in Aktionen\n\nEine in einer Aktion geworfene Exception wird protokolliert, und die Anfrage erhält die Fehlerseite `500`. In Callbacks und Promises fängt niemand die Exception für dich ab: Fange sie selbst ab und rufe `this.throw500(err)` oder `this.invalid(err)` auf.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Controladores","summary":"El controlador es `this` en cada acción de ruta: contiene los datos de la petición y responde a ella.","markdown":"---\ntitle: Controladores\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controladores\n\n> El controlador es `this` en cada acción de ruta: contiene los datos de la petición y responde a ella.\n\nCada acción de una ruta se ejecuta con un **controlador** como `this`. El controlador contiene los datos de la petición y tiene los métodos que la responden. Se crea un controlador nuevo para cada petición.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nLas partes dinámicas de la URL llegan como argumentos de la acción, en su orden. La lista completa de propiedades y métodos está en la referencia de [Controller](../../reference/controller/).\n\n## Datos de la petición\n\n| Propiedad | Qué contiene |\n| --- | --- |\n| `this.body` | El cuerpo de la petición ya procesado (JSON o un formulario) |\n| `this.query` | La query string como objeto (`?page=2` da `{ page: '2' }`) |\n| `this.params` | Los parámetros dinámicos de la URL, convertidos según su tipo (`{page:number}`) |\n| `this.files` | Archivos subidos, para rutas con el flag `upload` |\n| `this.user` | El usuario que tu delegado `AUTH()` aceptó, o `undefined` |\n| `this.headers` | Las cabeceras de la petición, con nombres en minúsculas |\n| `this.ip` | La dirección IP del cliente (la primera dirección de `X-Forwarded-For` detrás de un proxy) |\n| `this.url` | La ruta de la URL en minúsculas, con barra final |\n| `this.uri` | La URL procesada (`pathname`, `query`, `hostname`…) |\n| `this.ua` | Un nombre corto del navegador y del sistema, obtenido de `User-Agent` |\n| `this.mobile`, `this.robot` | `true` para dispositivos móviles, o para rastreadores |\n| `this.xhr` | `true` cuando la petición tiene `X-Requested-With: XMLHttpRequest` |\n| `this.referrer` | La cabecera `Referer`, o un string vacío |\n| `this.language` | El idioma que establece tu delegado de localización |\n| `this.req`, `this.res` | Los objetos de petición y respuesta del framework |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` y `this.body` contienen strings: convierte tú los números y las fechas, o deja que lo haga un esquema (consulta [Enrutamiento](../routing/)).\n\n## Archivos subidos\n\nUna ruta con el flag `upload` lee `multipart/form-data`. Cada elemento de `this.files` tiene `name` (el campo), `filename`, `type`, `size`, `extension`, y `width` y `height` para imágenes. `move()`, `copy()` y `read()` devuelven una promesa cuando no pasas un callback:\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nEl framework elimina los archivos temporales cuando termina la petición. Llama a `this.autoclear(false)` para conservarlos.\n\n## Responder\n\nResponde a cada petición **una sola vez**. Los métodos devuelven el controlador, así que puedes llamar a `return this.json(...)` para detener la acción.\n\n| Método | Respuesta |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Texto plano; un objeto se serializa como JSON formateado |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | Cualquier texto con tu tipo de contenido |\n| `this.view(name, [model])` | Una vista renderizada de `views/` |\n| `this.file(filename, [download])` | Un archivo de `public/` (o cualquier ruta que empiece por `~`) |\n| `this.binary(buffer, type)` | Un buffer |\n| `this.stream(stream, type)` | Un stream legible |\n| `this.redirect(url, [permanent])` | Una redirección, `302` o `301` |\n| `this.empty()` | Un cuerpo vacío |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | Un error como JSON, `400` por defecto |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## El código de estado\n\nEstablece `this.status` antes de responder. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` y `empty()` lo usan; el valor por defecto es `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` establece el estado y responde en una sola llamada.\n\n## Éxito y errores de validación\n\n`this.success()` responde `{ \"success\": true }`. Con un valor responde `{ \"success\": true, \"value\": ... }`, y `this.success(false)` responde `{ \"success\": false }`.\n\n`this.invalid()` responde un array de errores como JSON con el estado `400`. Un número como primer argumento establece otro estado:\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nDos helpers crean callbacks con el estilo `(err, response)`. `this.done()` responde `invalid(err)` si hay error y `success()` en caso contrario; `this.done(true)` añade la respuesta como `value`. `this.callback()` responde con la respuesta como JSON, o con una vista cuando pasas su nombre:\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Páginas de error\n\n`this.throw404()` y sus hermanos responden con una página de error: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` y `throw503()`. Tienen alias llamados `view400()`… `view503()`. El argumento es una descripción del problema; `throw500(err)` además registra el error.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nPara renderizar tu propia página, declara una ruta para el estado. El problema está en `this.exception`:\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nSin esa ruta, el framework renderiza su propia página de error.\n\n## Cabeceras y caché\n\n`this.header(name, value)` establece una cabecera de la respuesta. La mayoría de los métodos de respuesta también aceptan un objeto con cabeceras. `this.nocache()` desactiva la caché HTTP de la respuesta:\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookies\n\n`this.cookie(name)` lee una cookie. `this.cookie(name, value, expires, [options])` la escribe; `expires` es un texto como `'5 days'`, y las opciones son `domain`, `path` (`/`), `secure`, `httponly` y `samesite` (`Lax` por defecto):\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Vistas y plantillas (layouts)\n\n`this.view(name, [model])` renderiza `views/name.html` dentro de la plantilla (layout) `views/layout.html`. Las rutas de `controllers/default.js` buscan sus vistas en `views/`; las rutas de otro controlador, por ejemplo `controllers/admin.js`, en `views/admin/`. Un nombre que empieza por `~` siempre parte de `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` elige otra plantilla; `this.layout('')` renderiza la vista sin plantilla.\n- `this.title()` y `this.meta(title, [description], [keywords], [image])` establecen valores que la plantilla imprime con `@{title}` y `@{meta}`.\n- `this.repository` es un objeto compartido por la vista y su plantilla.\n- `this.view(name, model, true)` devuelve el HTML como string en lugar de responder.\n\nLa sintaxis de las plantillas se explica en [Vistas](../views/).\n\n## Usuarios autenticados\n\n`this.user` es lo que tu delegado `AUTH()` aceptó. Las rutas con `+` solo se ejecutan para usuarios autenticados, así que ahí `this.user` siempre existe:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Errores en las acciones\n\nUna excepción lanzada en una acción se registra y la petición recibe la página de error `500`. En callbacks y promesas nadie captura la excepción por ti: captúrala y llama a `this.throw500(err)` o `this.invalid(err)`.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Contrôleurs","summary":"Le contrôleur est `this` dans chaque action de route : il contient les données de la requête et répond à la requête.","markdown":"---\ntitle: \"Contrôleurs\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Contrôleurs\n\n> Le contrôleur est `this` dans chaque action de route : il contient les données de la requête et répond à la requête.\n\nChaque action d'une route s'exécute avec un **contrôleur** comme `this`. Le contrôleur contient les données de la requête et dispose des méthodes qui y répondent. Un nouveau contrôleur est créé pour chaque requête.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nLes parties dynamiques de l'URL arrivent en arguments de l'action, dans leur ordre. La liste complète des propriétés et méthodes se trouve dans la référence de [Controller](../../reference/controller/).\n\n## Données de la requête\n\n| Propriété | Contenu |\n| --- | --- |\n| `this.body` | Le corps analysé de la requête (JSON ou formulaire) |\n| `this.query` | La query string sous forme d'objet (`?page=2` donne `{ page: '2' }`) |\n| `this.params` | Les paramètres dynamiques de l'URL, convertis selon leur type (`{page:number}`) |\n| `this.files` | Les fichiers uploadés, pour les routes avec le flag `upload` |\n| `this.user` | L'utilisateur accepté par ton délégué `AUTH()`, ou `undefined` |\n| `this.headers` | Les en-têtes de la requête, avec des noms en minuscules |\n| `this.ip` | L'adresse IP du client (la première adresse `X-Forwarded-For` derrière un proxy) |\n| `this.url` | Le chemin de l'URL en minuscules, avec une barre oblique finale |\n| `this.uri` | L'URL analysée (`pathname`, `query`, `hostname`…) |\n| `this.ua` | Un nom court du navigateur et du système, extrait de `User-Agent` |\n| `this.mobile`, `this.robot` | `true` pour les appareils mobiles, ou pour les robots d'indexation |\n| `this.xhr` | `true` lorsque la requête contient `X-Requested-With: XMLHttpRequest` |\n| `this.referrer` | L'en-tête `Referer`, ou une chaîne vide |\n| `this.language` | La langue définie par ton délégué de localisation |\n| `this.req`, `this.res` | Les objets requête et réponse du framework |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` et `this.body` contiennent des chaînes : convertis toi-même les nombres et les dates, ou laisse un schéma le faire (voir [Routage](../routing/)).\n\n## Fichiers uploadés\n\nUne route avec le flag `upload` lit du `multipart/form-data`. Chaque élément de `this.files` possède `name` (le champ), `filename`, `type`, `size`, `extension`, ainsi que `width` et `height` pour les images. `move()`, `copy()` et `read()` renvoient une promesse lorsque tu ne passes pas de callback :\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nLe framework supprime les fichiers temporaires à la fin de la requête. Appelle `this.autoclear(false)` pour les conserver.\n\n## Répondre\n\nRéponds à chaque requête **une seule fois**. Les méthodes renvoient le contrôleur, tu peux donc appeler `return this.json(...)` pour arrêter l'action.\n\n| Méthode | Réponse |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Texte brut ; un objet est sérialisé en JSON formaté |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | N'importe quel texte avec ton type de contenu |\n| `this.view(name, [model])` | Une vue rendue depuis `views/` |\n| `this.file(filename, [download])` | Un fichier de `public/` (ou tout chemin commençant par `~`) |\n| `this.binary(buffer, type)` | Un buffer |\n| `this.stream(stream, type)` | Un flux lisible |\n| `this.redirect(url, [permanent])` | Une redirection, `302` ou `301` |\n| `this.empty()` | Un corps vide |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | Une erreur en JSON, `400` par défaut |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## Le code de statut\n\nDéfinis `this.status` avant de répondre. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` et `empty()` l'utilisent ; la valeur par défaut est `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` définit le statut et répond en un seul appel.\n\n## Succès et erreurs de validation\n\n`this.success()` répond `{ \"success\": true }`. Avec une valeur, il répond `{ \"success\": true, \"value\": ... }`, et `this.success(false)` répond `{ \"success\": false }`.\n\n`this.invalid()` répond un tableau d'erreurs en JSON avec le statut `400`. Un nombre en premier argument définit un autre statut :\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nDeux helpers créent des callbacks dans le style `(err, response)`. `this.done()` répond `invalid(err)` en cas d'erreur et `success()` sinon ; `this.done(true)` ajoute la réponse comme `value`. `this.callback()` renvoie la réponse en JSON, ou avec une vue lorsque tu passes son nom :\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Pages d'erreur\n\n`this.throw404()` et ses semblables répondent avec une page d'erreur : `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` et `throw503()`. Ils ont des alias nommés `view400()`… `view503()`. L'argument est une description du problème ; `throw500(err)` enregistre aussi l'erreur dans le journal.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nPour afficher ta propre page, déclare une route pour le statut. Le problème se trouve dans `this.exception` :\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nSans une telle route, le framework affiche sa propre page d'erreur.\n\n## En-têtes et cache\n\n`this.header(name, value)` définit un en-tête de la réponse. La plupart des méthodes de réponse acceptent aussi un objet d'en-têtes. `this.nocache()` désactive le cache HTTP de la réponse :\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookies\n\n`this.cookie(name)` lit un cookie. `this.cookie(name, value, expires, [options])` l'écrit ; `expires` est un texte comme `'5 days'`, et les options sont `domain`, `path` (`/`), `secure`, `httponly` et `samesite` (`Lax` par défaut) :\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Vues et layouts\n\n`this.view(name, [model])` rend `views/name.html` dans le layout `views/layout.html`. Les routes de `controllers/default.js` trouvent leurs vues dans `views/` ; les routes d'un autre contrôleur, par exemple `controllers/admin.js`, dans `views/admin/`. Un nom qui commence par `~` part toujours de `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` choisit un autre layout ; `this.layout('')` rend la vue sans layout.\n- `this.title()` et `this.meta(title, [description], [keywords], [image])` définissent des valeurs que le layout affiche avec `@{title}` et `@{meta}`.\n- `this.repository` est un objet partagé par la vue et son layout.\n- `this.view(name, model, true)` renvoie le HTML sous forme de chaîne au lieu de répondre.\n\nLa syntaxe des templates est expliquée dans [Vues](../views/).\n\n## Utilisateurs connectés\n\n`this.user` est ce que ton délégué `AUTH()` a accepté. Les routes avec `+` ne s'exécutent que pour les utilisateurs connectés, donc `this.user` y existe toujours :\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Erreurs dans les actions\n\nUne exception levée dans une action est enregistrée dans le journal et la requête reçoit la page d'erreur `500`. Dans les callbacks et les promesses, rien n'intercepte l'exception pour toi : intercepte-la et appelle `this.throw500(err)` ou `this.invalid(err)`.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Controller","summary":"Il controller è `this` in ogni azione di una route: contiene i dati della richiesta e risponde alla richiesta.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Il controller è `this` in ogni azione di una route: contiene i dati della richiesta e risponde alla richiesta.\n\nOgni azione di una route viene eseguita con un **controller** come `this`. Il controller contiene i dati della richiesta e ha i metodi che le rispondono. Per ogni richiesta viene creato un nuovo controller.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nLe parti dinamiche dell'URL arrivano come argomenti dell'azione, nel loro ordine. L'elenco completo di proprietà e metodi è nel riferimento di [Controller](../../reference/controller/).\n\n## Dati della richiesta\n\n| Proprietà | Cosa contiene |\n| --- | --- |\n| `this.body` | Il corpo della richiesta già analizzato (JSON o un form) |\n| `this.query` | La query string come oggetto (`?page=2` dà `{ page: '2' }`) |\n| `this.params` | I parametri dinamici dell'URL, convertiti secondo il loro tipo (`{page:number}`) |\n| `this.files` | I file caricati, per le route con il flag `upload` |\n| `this.user` | L'utente che il tuo delegato `AUTH()` ha accettato, oppure `undefined` |\n| `this.headers` | Gli header della richiesta, con i nomi in minuscolo |\n| `this.ip` | L'indirizzo IP del client (il primo indirizzo di `X-Forwarded-For` dietro un proxy) |\n| `this.url` | Il percorso dell'URL in minuscolo, con la barra finale |\n| `this.uri` | L'URL analizzato (`pathname`, `query`, `hostname`…) |\n| `this.ua` | Un nome breve del browser e del sistema, ricavato da `User-Agent` |\n| `this.mobile`, `this.robot` | `true` per i dispositivi mobili, o per i crawler |\n| `this.xhr` | `true` quando la richiesta ha `X-Requested-With: XMLHttpRequest` |\n| `this.referrer` | L'header `Referer`, oppure una stringa vuota |\n| `this.language` | La lingua impostata dal tuo delegato di localizzazione |\n| `this.req`, `this.res` | Gli oggetti richiesta e risposta del framework |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` e `this.body` contengono stringhe: converti tu numeri e date, oppure lascia che lo faccia uno schema (vedi [Routing](../routing/)).\n\n## File caricati\n\nUna route con il flag `upload` legge `multipart/form-data`. Ogni elemento di `this.files` ha `name` (il campo), `filename`, `type`, `size`, `extension`, e `width` e `height` per le immagini. `move()`, `copy()` e `read()` restituiscono una promise quando non passi una callback:\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nIl framework rimuove i file temporanei quando la richiesta termina. Chiama `this.autoclear(false)` per conservarli.\n\n## Rispondere\n\nRispondi a ogni richiesta **una sola volta**. I metodi restituiscono il controller, quindi puoi chiamare `return this.json(...)` per fermare l'azione.\n\n| Metodo | Risposta |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Testo semplice; un oggetto viene serializzato come JSON formattato |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | Qualsiasi testo con il tuo content type |\n| `this.view(name, [model])` | Una vista renderizzata da `views/` |\n| `this.file(filename, [download])` | Un file da `public/` (o qualsiasi percorso che inizia con `~`) |\n| `this.binary(buffer, type)` | Un buffer |\n| `this.stream(stream, type)` | Uno stream leggibile |\n| `this.redirect(url, [permanent])` | Un redirect, `302` o `301` |\n| `this.empty()` | Un corpo vuoto |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | Un errore come JSON, `400` per impostazione predefinita |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## Il codice di stato\n\nImposta `this.status` prima di rispondere. `json()`, `plain()`, `content()`, `html()`, `jsonstring()` ed `empty()` lo usano; il valore predefinito è `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` imposta lo stato e risponde in una sola chiamata.\n\n## Successo ed errori di validazione\n\n`this.success()` risponde `{ \"success\": true }`. Con un valore risponde `{ \"success\": true, \"value\": ... }`, e `this.success(false)` risponde `{ \"success\": false }`.\n\n`this.invalid()` risponde con un array di errori come JSON e con lo stato `400`. Un numero come primo argomento imposta un altro stato:\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nDue helper creano callback nello stile `(err, response)`. `this.done()` risponde `invalid(err)` in caso di errore e `success()` altrimenti; `this.done(true)` aggiunge la risposta come `value`. `this.callback()` risponde con la risposta come JSON, oppure con una vista quando passi il suo nome:\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Pagine di errore\n\n`this.throw404()` e i suoi simili rispondono con una pagina di errore: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` e `throw503()`. Hanno degli alias chiamati `view400()`… `view503()`. L'argomento è una descrizione del problema; `throw500(err)` registra anche l'errore nel log.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nPer renderizzare una tua pagina, dichiara una route per lo stato. Il problema si trova in `this.exception`:\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nSenza una route di questo tipo il framework renderizza la propria pagina di errore.\n\n## Header e cache\n\n`this.header(name, value)` imposta un header della risposta. La maggior parte dei metodi di risposta accetta anche un oggetto con gli header. `this.nocache()` disattiva la cache HTTP della risposta:\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookie\n\n`this.cookie(name)` legge un cookie. `this.cookie(name, value, expires, [options])` lo scrive; `expires` è un testo come `'5 days'`, e le opzioni sono `domain`, `path` (`/`), `secure`, `httponly` e `samesite` (`Lax` per impostazione predefinita):\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Viste e layout\n\n`this.view(name, [model])` renderizza `views/name.html` dentro il layout `views/layout.html`. Le route di `controllers/default.js` trovano le loro viste in `views/`; le route di un altro controller, per esempio `controllers/admin.js`, in `views/admin/`. Un nome che inizia con `~` parte sempre da `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` sceglie un altro layout; `this.layout('')` renderizza la vista senza layout.\n- `this.title()` e `this.meta(title, [description], [keywords], [image])` impostano valori che il layout stampa con `@{title}` e `@{meta}`.\n- `this.repository` è un oggetto condiviso dalla vista e dal suo layout.\n- `this.view(name, model, true)` restituisce l'HTML come stringa invece di rispondere.\n\nLa sintassi dei template è spiegata in [Viste](../views/).\n\n## Utenti autenticati\n\n`this.user` è ciò che il tuo delegato `AUTH()` ha accettato. Le route con `+` vengono eseguite solo per gli utenti autenticati, quindi lì `this.user` esiste sempre:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Errori nelle azioni\n\nUn'eccezione lanciata in un'azione viene registrata nel log e la richiesta riceve la pagina di errore `500`. Nelle callback e nelle promise nessuno cattura l'eccezione al posto tuo: catturala e chiama `this.throw500(err)` o `this.invalid(err)`.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9E1dU60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/controllers/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Kontroléry","summary":"Kontrolér je `this` v každej akcii trasy: obsahuje dáta požiadavky a odpovedá na ňu.","markdown":"---\ntitle: \"Kontroléry\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/controllers/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Kontroléry\n\n> Kontrolér je `this` v každej akcii trasy: obsahuje dáta požiadavky a odpovedá na ňu.\n\nKaždá akcia trasy beží s **kontrolérom** ako `this`. Kontrolér obsahuje dáta požiadavky a má metódy, ktoré na ňu odpovedajú. Pre každú požiadavku sa vytvorí nový kontrolér.\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/{id}/', detail);\n};\n\nfunction detail(id) {\n\t// id === this.params.id\n\tthis.json({ id: id, ip: this.ip });\n}\n```\n\nDynamické časti URL prichádzajú ako argumenty akcie, v ich poradí. Úplný zoznam vlastností a metód nájdeš v referencii [Controller](../../reference/controller/).\n\n## Dáta požiadavky\n\n| Vlastnosť | Čo obsahuje |\n| --- | --- |\n| `this.body` | Spracované telo požiadavky (JSON alebo formulár) |\n| `this.query` | Query string ako objekt (`?page=2` dáva `{ page: '2' }`) |\n| `this.params` | Dynamické parametre URL, skonvertované podľa ich typu (`{page:number}`) |\n| `this.files` | Nahrané súbory, pre trasy s flagom `upload` |\n| `this.user` | Používateľ, ktorého prijal tvoj delegát `AUTH()`, alebo `undefined` |\n| `this.headers` | Hlavičky požiadavky s názvami malými písmenami |\n| `this.ip` | IP adresa klienta (za proxy prvá adresa z `X-Forwarded-For`) |\n| `this.url` | Cesta URL malými písmenami, s koncovou lomkou |\n| `this.uri` | Spracovaná URL (`pathname`, `query`, `hostname`…) |\n| `this.ua` | Krátky názov prehliadača a systému, získaný z `User-Agent` |\n| `this.mobile`, `this.robot` | `true` pre mobilné zariadenia alebo pre crawlery |\n| `this.xhr` | `true`, keď má požiadavka `X-Requested-With: XMLHttpRequest` |\n| `this.referrer` | Hlavička `Referer` alebo prázdny reťazec |\n| `this.language` | Jazyk nastavený tvojím lokalizačným delegátom |\n| `this.req`, `this.res` | Objekty požiadavky a odpovede frameworku |\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar model = this.body;\n\tvar page = this.query.page;\n\tvar agent = this.headers['user-agent'];\n\tthis.success();\n}\n```\n\n`this.query` a `this.body` obsahujú reťazce: čísla a dátumy si skonvertuj sám alebo to nechaj na schému (pozri [Smerovanie](../routing/)).\n\n## Nahrané súbory\n\nTrasa s flagom `upload` číta `multipart/form-data`. Každá položka `this.files` má `name` (pole), `filename`, `type`, `size`, `extension` a pri obrázkoch `width` a `height`. `move()`, `copy()` a `read()` vrátia promise, keď neodovzdáš callback:\n\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tif (!file || !file.isImage()) {\n\t\tthis.invalid('Send an image');\n\t\treturn;\n\t}\n\tawait file.move(PATH.public('photos/' + file.filename));\n\tthis.success();\n}\n```\n\nFramework odstráni dočasné súbory, keď požiadavka skončí. Zavolaj `this.autoclear(false)`, ak ich chceš ponechať.\n\n## Odpovedanie\n\nNa každú požiadavku odpovedz **raz**. Metódy vracajú kontrolér, takže môžeš zavolať `return this.json(...)` a ukončiť akciu.\n\n| Metóda | Odpoveď |\n| --- | --- |\n| `this.json(obj)` | JSON (`application/json`) |\n| `this.plain(text)` | Čistý text; objekt sa serializuje ako formátovaný JSON |\n| `this.html(body)` | HTML |\n| `this.content(body, type)` | Ľubovoľný text s tvojím typom obsahu |\n| `this.view(name, [model])` | Vykreslené view z `views/` |\n| `this.file(filename, [download])` | Súbor z `public/` (alebo z akejkoľvek cesty, ktorá začína na `~`) |\n| `this.binary(buffer, type)` | Buffer |\n| `this.stream(stream, type)` | Čitateľný stream |\n| `this.redirect(url, [permanent])` | Presmerovanie, `302` alebo `301` |\n| `this.empty()` | Prázdne telo |\n| `this.nocontent()` | `204 No Content` |\n| `this.success([value])` | `{ \"success\": true }` |\n| `this.invalid(error)` | Chyba ako JSON, predvolene `400` |\n\n```js\nfunction download() {\n\tthis.file('invoices/2024.pdf', 'invoice.pdf');\n}\n\nfunction legacy() {\n\tthis.redirect('/new-address/', true);\n}\n```\n\n## Stavový kód\n\nNastav `this.status` predtým, ako odpovieš. Používajú ho `json()`, `plain()`, `content()`, `html()`, `jsonstring()` a `empty()`; predvolená hodnota je `200`.\n\n```js\nfunction create() {\n\tvar item = { id: UID(), name: this.body.name };\n\tthis.status = 201;\n\tthis.json(item);\n}\n```\n\n`this.empty(204)` nastaví stav a odpovie jedným volaním.\n\n## Úspech a validačné chyby\n\n`this.success()` odpovie `{ \"success\": true }`. S hodnotou odpovie `{ \"success\": true, \"value\": ... }` a `this.success(false)` odpovie `{ \"success\": false }`.\n\n`this.invalid()` odpovie poľom chýb ako JSON so stavom `400`. Číslo ako prvý argument nastaví iný stav:\n\n```js\nfunction save() {\n\tif (!this.body.email) {\n\t\tthis.invalid('email', 'The email is required');\n\t\treturn;\n\t}\n\tthis.success(true, { id: UID() });\n}\n```\n\nDve pomocné metódy vytvárajú callbacky v štýle `(err, response)`. `this.done()` pri chybe odpovie `invalid(err)` a inak `success()`; `this.done(true)` pridá odpoveď ako `value`. `this.callback()` odpovie odpoveďou ako JSON alebo pomocou view, keď odovzdáš jeho názov:\n\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n\nfunction remove() {\n\tremoveproduct(this.params.id, this.done());\n}\n```\n\n## Chybové stránky\n\n`this.throw404()` a jej súrodenci odpovedajú chybovou stránkou: `throw400()`, `throw401()`, `throw403()`, `throw404()`, `throw409()`, `throw500()`, `throw501()` a `throw503()`. Majú aliasy s názvami `view400()`… `view503()`. Argument je popis problému; `throw500(err)` chybu aj zaloguje.\n\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nAk chceš vykresliť vlastnú stránku, deklaruj trasu pre daný stav. Problém je v `this.exception`:\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\nBez takejto trasy framework vykreslí vlastnú chybovú stránku.\n\n## Hlavičky a cache\n\n`this.header(name, value)` nastaví hlavičku odpovede. Väčšina metód na odpovedanie prijíma aj objekt s hlavičkami. `this.nocache()` vypne HTTP cache odpovede:\n\n```js\nfunction report() {\n\tthis.nocache();\n\tthis.header('X-Report', 'daily');\n\tthis.plain('...');\n}\n```\n\n## Cookies\n\n`this.cookie(name)` prečíta cookie. `this.cookie(name, value, expires, [options])` ju zapíše; `expires` je text ako `'5 days'` a možnosti sú `domain`, `path` (`/`), `secure`, `httponly` a `samesite` (predvolene `Lax`):\n\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction logout() {\n\tthis.cookie('session', '', '-1 day');\n\tthis.redirect('/');\n}\n```\n\n## Views a layouty\n\n`this.view(name, [model])` vykreslí `views/name.html` vnútri layoutu `views/layout.html`. Trasy z `controllers/default.js` hľadajú svoje views vo `views/`; trasy iného kontroléra, napríklad `controllers/admin.js`, vo `views/admin/`. Názov, ktorý začína na `~`, začína vždy vo `views/`.\n\n```js\nfunction home() {\n\tthis.layout('layout_home');\n\tthis.title('Welcome');\n\tthis.view('index', { products: [] });\n}\n```\n\n- `this.layout(name)` vyberie iný layout; `this.layout('')` vykreslí view bez layoutu.\n- `this.title()` a `this.meta(title, [description], [keywords], [image])` nastavia hodnoty, ktoré layout vypíše pomocou `@{title}` a `@{meta}`.\n- `this.repository` je objekt zdieľaný medzi view a jeho layoutom.\n- `this.view(name, model, true)` vráti HTML ako reťazec namiesto odpovede.\n\nSyntax šablón je vysvetlená vo [Views](../views/).\n\n## Prihlásení používatelia\n\n`this.user` je to, čo prijal tvoj delegát `AUTH()`. Trasy s `+` bežia len pre prihlásených používateľov, takže `this.user` tam vždy existuje:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\tvar token = $.cookie('session');\n\tif (token === 'token')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+GET /account/', account);\n};\n\nfunction account() {\n\tthis.json(this.user);\n}\n```\n\n## Chyby v akciách\n\nVýnimka vyhodená v akcii sa zaloguje a požiadavka dostane chybovú stránku `500`. V callbackoch a promises výnimku nikto nezachytí za teba: zachyť ju a zavolaj `this.throw500(err)` alebo `this.invalid(err)`.\n\n```js\nasync function stats() {\n\ttry {\n\t\tvar data = await loadstats();\n\t\tthis.json(data);\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Schemas and actions","summary":"Declare schemas with typed and validated fields, write operations and actions, use the $ object and call them from routes and code.","markdown":"---\ntitle: Schemas and actions\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Schemas and actions\n\n> Declare schemas with typed and validated fields, write operations and actions, use the $ object and call them from routes and code.\n\nA **schema** describes the data your app receives and the operations that work with it. Total.js converts the request body to the types you declare, validates it, and runs your operation with a `$` object that knows the model, the query, the user and how to answer. Routes call schemas directly, so a REST endpoint often needs no action of its own.\n\nPut schemas in the `schemas/` folder. Total.js loads every file there when the app starts.\n\n## Declaring a schema\n\n`NEWSCHEMA(name, declaration)` creates a schema. The declaration receives the schema and declares its fields and operations:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDeclaring a schema with an existing name replaces the old one. `NEWSCHEMA('Users', null)` removes it. `GETSCHEMA('Users')` returns a declared schema.\n\n## Field types\n\n`schema.define(name, type, [required], [error])` accepts a constructor, a type name (case does not matter), an array or an object:\n\n| Type | What the value becomes |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | A trimmed string. `'String(50)'` cuts it to 50 characters |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | A string with its case changed |\n| `'SafeString'` | A string checked for XSS and SQL injection |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | A string; a required field must have a valid value |\n| `'Color'`, `'Icon'` | A string with a color or an icon name |\n| `'UID'` or `UID`, `'GUID'` or `GUID` | An identifier |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | A decimal number |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | An integer |\n| `'Number2'` | A number; when required, `0` is also valid |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` or `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | A date |\n| `Object`, `'Object'` | Any object |\n| `'name:String, age:Number'` | An object with these fields |\n| `['a', 'b']` | An enum: one of the values |\n| `{ a: 'A', b: 'B' }` | A key-value list: one of the keys |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | An array, of the type in brackets |\n| `'Address'`, `'[Address]'` | Another schema, or an array of it, validated with its own rules |\n\nThe model your operation receives contains only the declared fields, already converted. A schema without fields passes the body as it came.\n\n## Required fields and error messages\n\nThe third argument makes a field required. What \"required\" checks depends on the type:\n\n- a string must not be empty, and `Email`, `Phone`, `URL`, `UID` and similar must be valid;\n- a number must be greater than `0`, and a boolean must be `true`;\n- an array must not be empty.\n\nInstead of `true` you can pass a function `(value, model)` that returns `true`, `false` or an error message. A string as the third argument makes the field required and is its error message:\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nWithout a message, Total.js reads it from the resource set with `schema.setResource()` (the key is the field name), or answers `The field \"name\" is invalid`. A message that starts with `@` is a resource key.\n\n`schema.required(name, fn)` makes a field required only when `fn(model, operations)` returns `true`, for example only on insert.\n\n## Default values\n\n`schema.define()` returns a function that sets the default value. It returns the schema again:\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Classic operations\n\nThe classic way gives the schema up to seven operations. Each one receives `$` and the validated model:\n\n| Method | Operation name in routes |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (or `get`) |\n| `schema.setQuery(fn)` | `query` (or `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` adds an operation with your own name:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Actions: schema.action()\n\n`schema.action(name, options)` is the newer style. One object declares the operation and everything it needs: the input, the query and the URL parameters it accepts, and who may run it. The input is declared inline, so the schema needs no `define()`:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nIn `input`, `query` and `params`, fields are separated by commas, `*` marks a required field, `[String]` is an array, `{a|b}` an enum and `@Name` another schema or action. Instead of an inline declaration you can give the name of a JSON schema from the `jsonschemas/` folder.\n\n| Option | What it does |\n| --- | --- |\n| `action` | The function `($, model)` that runs the action |\n| `name` | A description of the action |\n| `input` | Fields of the request body. Invalid data stops the action |\n| `output` | Fields of the response. Other fields are removed |\n| `query` | Fields of the query string, converted into `$.query` |\n| `params` | Fields of the URL parameters, converted into `$.params` |\n| `user` | `true`: only for a signed-in user, otherwise `401` |\n| `sa` | `true`: only for a super admin (`user.sa` or `user.su`) |\n| `permissions` | `'read,write'`: the user needs one of them in `user.permissions` or `user.roles` |\n| `cache` | Caches the response: `{ query, params, user, language, expire }` |\n\nBoth styles call operations the same way, and you can mix them in one schema.\n\n## The $ object\n\nEvery operation receives `$`. It ends the operation and gives you the request:\n\n| Member | What it is |\n| --- | --- |\n| `$.callback(value)` | Answers with the value; `$.callback(err)` with an error |\n| `$.success([value])` | Answers `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Answers with an error; `$.invalid(404)` with a status code |\n| `$.done([value])` | Returns a callback `(err, response)` that answers with success or the error |\n| `$.successful(fn)` | Returns a callback that runs `fn(response)` only when there is no error |\n| `$.redirect(url)` | Redirects the request |\n| `$.model` | The validated model |\n| `$.query`, `$.params`, `$.id` | The query string, the URL parameters and the first one of them |\n| `$.user`, `$.session` | The signed-in user and the session |\n| `$.keys` | In a `PATCH` request, the fields that were sent |\n| `$.filter` | The query converted with the filter of the operation |\n| `$.controller` | The controller; also `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nCall exactly one of `$.callback()`, `$.success()`, `$.invalid()` or `$.redirect()` per operation:\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Calling operations from routes\n\n`*Schema --> operation` after the URL validates the request body with the schema and runs the operation. The first dynamic parameter becomes `$.id`:\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\n`GET` requests have no body, so there is nothing to validate. In a `PATCH` request, only the fields that were sent are validated. Several operations run one after another, and `(response)` after one of them chooses whose result is sent back:\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nThe whole syntax is in the [Routing](../routing/) guide.\n\n## NEWACTION(): actions without a schema\n\n`NEWACTION(name, options)` declares an action that does not belong to any schema. It takes the same options as `schema.action()`. Name actions with a slash, `Users/create`, to group them:\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nA route calls it with `-->` and no schema:\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nThe option `route: 'API /api/'` declares an API route for the action by itself; the API name is the action name in lowercase with `_` instead of `/` (`users_create`).\n\n## Running operations from code\n\n`CALL()` runs actions and schema operations from anywhere in your code. It starts on the next tick, so you can set options first:\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nInside an operation, `$.action(name, [data])` does the same; a name without `-->` is an operation of the current schema. `EXEC('+Users --> insert', model, callback)` also runs schema operations and returns a promise without a callback. `MAKE('Users', model)` only validates a model.\n\nAll the methods are in the [Schemas](../../reference/schemas/) reference.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Schemas und Aktionen","summary":"Deklariere Schemas mit typisierten und validierten Feldern, schreibe Operationen und Aktionen, verwende das Objekt $ und rufe sie aus Routen und Code auf.","markdown":"---\ntitle: Schemas und Aktionen\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Schemas und Aktionen\n\n> Deklariere Schemas mit typisierten und validierten Feldern, schreibe Operationen und Aktionen, verwende das Objekt $ und rufe sie aus Routen und Code auf.\n\nEin **Schema** beschreibt die Daten, die deine App empfängt, und die Operationen, die damit arbeiten. Total.js konvertiert den Body der Anfrage in die Typen, die du deklarierst, validiert ihn und führt deine Operation mit einem `$`-Objekt aus, das das Modell, die Query, den Benutzer und die Art der Antwort kennt. Routen rufen Schemas direkt auf, daher braucht ein REST-Endpunkt oft keine eigene Aktion.\n\nLege Schemas im Ordner `schemas/` ab. Total.js lädt beim Start der App jede Datei darin.\n\n## Ein Schema deklarieren\n\n`NEWSCHEMA(name, declaration)` erstellt ein Schema. Die Deklaration erhält das Schema und deklariert seine Felder und Operationen:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDeklarierst du ein Schema mit einem bereits vorhandenen Namen, ersetzt es das alte. `NEWSCHEMA('Users', null)` entfernt es. `GETSCHEMA('Users')` gibt ein deklariertes Schema zurück.\n\n## Feldtypen\n\n`schema.define(name, type, [required], [error])` akzeptiert einen Konstruktor, einen Typnamen (Groß- und Kleinschreibung spielt keine Rolle), ein Array oder ein Objekt:\n\n| Typ | Was aus dem Wert wird |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | Ein getrimmter String. `'String(50)'` kürzt ihn auf 50 Zeichen |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | Ein String mit geänderter Groß- und Kleinschreibung |\n| `'SafeString'` | Ein String, der auf XSS und SQL-Injection geprüft wird |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | Ein String; ein Pflichtfeld muss einen gültigen Wert haben |\n| `'Color'`, `'Icon'` | Ein String mit einer Farbe oder einem Icon-Namen |\n| `'UID'` oder `UID`, `'GUID'` oder `GUID` | Ein Bezeichner |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | Eine Dezimalzahl |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | Eine Ganzzahl |\n| `'Number2'` | Eine Zahl; als Pflichtfeld ist auch `0` gültig |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` oder `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | Ein Datum |\n| `Object`, `'Object'` | Ein beliebiges Objekt |\n| `'name:String, age:Number'` | Ein Objekt mit diesen Feldern |\n| `['a', 'b']` | Ein Enum: einer der Werte |\n| `{ a: 'A', b: 'B' }` | Eine Schlüssel-Wert-Liste: einer der Schlüssel |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | Ein Array, vom Typ in den Klammern |\n| `'Address'`, `'[Address]'` | Ein anderes Schema oder ein Array davon, mit seinen eigenen Regeln validiert |\n\nDas Modell, das deine Operation erhält, enthält nur die deklarierten Felder, bereits konvertiert. Ein Schema ohne Felder reicht den Body so weiter, wie er gekommen ist.\n\n## Pflichtfelder und Fehlermeldungen\n\nDas dritte Argument macht ein Feld zum Pflichtfeld. Was „Pflicht“ prüft, hängt vom Typ ab:\n\n- ein String darf nicht leer sein, und `Email`, `Phone`, `URL`, `UID` und Ähnliche müssen gültig sein;\n- eine Zahl muss größer als `0` sein, und ein Boolean muss `true` sein;\n- ein Array darf nicht leer sein.\n\nStatt `true` kannst du eine Funktion `(value, model)` übergeben, die `true`, `false` oder eine Fehlermeldung zurückgibt. Ein String als drittes Argument macht das Feld zum Pflichtfeld und ist seine Fehlermeldung:\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nOhne Meldung liest Total.js sie aus der mit `schema.setResource()` gesetzten Ressource (der Schlüssel ist der Feldname) oder antwortet mit `The field \"name\" is invalid`. Eine Meldung, die mit `@` beginnt, ist ein Ressourcenschlüssel.\n\n`schema.required(name, fn)` macht ein Feld nur dann zum Pflichtfeld, wenn `fn(model, operations)` `true` zurückgibt, zum Beispiel nur beim Einfügen.\n\n## Standardwerte\n\n`schema.define()` gibt eine Funktion zurück, die den Standardwert setzt. Sie gibt wiederum das Schema zurück:\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Klassische Operationen\n\nAuf die klassische Weise erhält das Schema bis zu sieben Operationen. Jede erhält `$` und das validierte Modell:\n\n| Methode | Name der Operation in Routen |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (oder `get`) |\n| `schema.setQuery(fn)` | `query` (oder `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` fügt eine Operation mit einem eigenen Namen hinzu:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Aktionen: schema.action()\n\n`schema.action(name, options)` ist der neuere Stil. Ein einziges Objekt deklariert die Operation und alles, was sie braucht: die Eingabe, die Query und die URL-Parameter, die sie akzeptiert, und wer sie ausführen darf. Die Eingabe wird inline deklariert, daher braucht das Schema kein `define()`:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nIn `input`, `query` und `params` werden Felder durch Kommas getrennt, `*` markiert ein Pflichtfeld, `[String]` ist ein Array, `{a|b}` ein Enum und `@Name` ein anderes Schema oder eine andere Aktion. Statt einer Inline-Deklaration kannst du den Namen eines JSON-Schemas aus dem Ordner `jsonschemas/` angeben.\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `action` | Die Funktion `($, model)`, die die Aktion ausführt |\n| `name` | Eine Beschreibung der Aktion |\n| `input` | Felder des Bodys der Anfrage. Ungültige Daten stoppen die Aktion |\n| `output` | Felder der Antwort. Andere Felder werden entfernt |\n| `query` | Felder des Query-Strings, in `$.query` konvertiert |\n| `params` | Felder der URL-Parameter, in `$.params` konvertiert |\n| `user` | `true`: nur für einen angemeldeten Benutzer, sonst `401` |\n| `sa` | `true`: nur für einen Super-Admin (`user.sa` oder `user.su`) |\n| `permissions` | `'read,write'`: Der Benutzer braucht eine davon in `user.permissions` oder `user.roles` |\n| `cache` | Speichert die Antwort im Cache: `{ query, params, user, language, expire }` |\n\nBeide Stile rufen Operationen auf dieselbe Weise auf, und du kannst sie in einem Schema mischen.\n\n## Das Objekt $\n\nJede Operation erhält `$`. Es beendet die Operation und gibt dir Zugriff auf die Anfrage:\n\n| Member | Was es ist |\n| --- | --- |\n| `$.callback(value)` | Antwortet mit dem Wert; `$.callback(err)` mit einem Fehler |\n| `$.success([value])` | Antwortet mit `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Antwortet mit einem Fehler; `$.invalid(404)` mit einem Statuscode |\n| `$.done([value])` | Gibt einen Callback `(err, response)` zurück, der mit Erfolg oder dem Fehler antwortet |\n| `$.successful(fn)` | Gibt einen Callback zurück, der `fn(response)` nur ausführt, wenn kein Fehler auftritt |\n| `$.redirect(url)` | Leitet die Anfrage weiter |\n| `$.model` | Das validierte Modell |\n| `$.query`, `$.params`, `$.id` | Der Query-String, die URL-Parameter und der erste davon |\n| `$.user`, `$.session` | Der angemeldete Benutzer und die Session |\n| `$.keys` | Bei einer `PATCH`-Anfrage die Felder, die gesendet wurden |\n| `$.filter` | Die Query, mit dem Filter der Operation konvertiert |\n| `$.controller` | Der Controller; außerdem `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nRufe pro Operation genau eines von `$.callback()`, `$.success()`, `$.invalid()` oder `$.redirect()` auf:\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Operationen aus Routen aufrufen\n\n`*Schema --> operation` nach der URL validiert den Body der Anfrage mit dem Schema und führt die Operation aus. Der erste dynamische Parameter wird zu `$.id`:\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\n`GET`-Anfragen haben keinen Body, also gibt es nichts zu validieren. Bei einer `PATCH`-Anfrage werden nur die gesendeten Felder validiert. Mehrere Operationen laufen nacheinander, und `(response)` nach einer von ihnen wählt, wessen Ergebnis zurückgesendet wird:\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nDie komplette Syntax steht im Leitfaden [Routing](../routing/).\n\n## NEWACTION(): Aktionen ohne Schema\n\n`NEWACTION(name, options)` deklariert eine Aktion, die zu keinem Schema gehört. Sie akzeptiert dieselben Optionen wie `schema.action()`. Benenne Aktionen mit einem Schrägstrich, `Users/create`, um sie zu gruppieren:\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nEine Route ruft sie mit `-->` und ohne Schema auf:\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nDie Option `route: 'API /api/'` deklariert von selbst eine API-Route für die Aktion; der API-Name ist der Name der Aktion in Kleinbuchstaben, mit `_` statt `/` (`users_create`).\n\n## Operationen aus Code ausführen\n\n`CALL()` führt Aktionen und Schema-Operationen von überall in deinem Code aus. Es startet im nächsten Tick, sodass du vorher Optionen setzen kannst:\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nInnerhalb einer Operation macht `$.action(name, [data])` dasselbe; ein Name ohne `-->` ist eine Operation des aktuellen Schemas. `EXEC('+Users --> insert', model, callback)` führt ebenfalls Schema-Operationen aus und gibt ohne Callback ein Promise zurück. `MAKE('Users', model)` validiert nur ein Modell.\n\nAlle Methoden stehen in der Referenz [Schemas](../../reference/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Esquemas y acciones","summary":"Declara esquemas con campos tipados y validados, escribe operaciones y acciones, usa el objeto $ y llámalas desde rutas y código.","markdown":"---\ntitle: Esquemas y acciones\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Esquemas y acciones\n\n> Declara esquemas con campos tipados y validados, escribe operaciones y acciones, usa el objeto $ y llámalas desde rutas y código.\n\nUn **esquema** describe los datos que recibe tu app y las operaciones que trabajan con ellos. Total.js convierte el cuerpo de la petición a los tipos que declaras, lo valida y ejecuta tu operación con un objeto `$` que conoce el modelo, la query, el usuario y cómo responder. Las rutas llaman a los esquemas directamente, así que un endpoint REST a menudo no necesita una acción propia.\n\nPon los esquemas en la carpeta `schemas/`. Total.js carga todos los archivos de ahí cuando la app arranca.\n\n## Declarar un esquema\n\n`NEWSCHEMA(name, declaration)` crea un esquema. La declaración recibe el esquema y declara sus campos y operaciones:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDeclarar un esquema con un nombre existente reemplaza el anterior. `NEWSCHEMA('Users', null)` lo elimina. `GETSCHEMA('Users')` devuelve un esquema declarado.\n\n## Tipos de campo\n\n`schema.define(name, type, [required], [error])` acepta un constructor, un nombre de tipo (sin distinguir mayúsculas), un array o un objeto:\n\n| Tipo | En qué se convierte el valor |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | Un string sin espacios en los extremos. `'String(50)'` lo corta a 50 caracteres |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | Un string con las mayúsculas cambiadas |\n| `'SafeString'` | Un string comprobado contra XSS e inyección SQL |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | Un string; un campo obligatorio debe tener un valor válido |\n| `'Color'`, `'Icon'` | Un string con un color o un nombre de icono |\n| `'UID'` o `UID`, `'GUID'` o `GUID` | Un identificador |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | Un número decimal |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | Un entero |\n| `'Number2'` | Un número; si es obligatorio, `0` también es válido |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` o `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | Una fecha |\n| `Object`, `'Object'` | Cualquier objeto |\n| `'name:String, age:Number'` | Un objeto con estos campos |\n| `['a', 'b']` | Un enum: uno de los valores |\n| `{ a: 'A', b: 'B' }` | Una lista clave-valor: una de las claves |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | Un array, del tipo entre corchetes |\n| `'Address'`, `'[Address]'` | Otro esquema, o un array de él, validado con sus propias reglas |\n\nEl modelo que recibe tu operación contiene solo los campos declarados, ya convertidos. Un esquema sin campos pasa el cuerpo tal como llegó.\n\n## Campos obligatorios y mensajes de error\n\nEl tercer argumento hace que un campo sea obligatorio. Lo que comprueba \"obligatorio\" depende del tipo:\n\n- un string no debe estar vacío, y `Email`, `Phone`, `URL`, `UID` y similares deben ser válidos;\n- un número debe ser mayor que `0`, y un booleano debe ser `true`;\n- un array no debe estar vacío.\n\nEn lugar de `true` puedes pasar una función `(value, model)` que devuelva `true`, `false` o un mensaje de error. Un string como tercer argumento hace el campo obligatorio y es su mensaje de error:\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nSin mensaje, Total.js lo lee del recurso establecido con `schema.setResource()` (la clave es el nombre del campo), o responde `The field \"name\" is invalid`. Un mensaje que empieza por `@` es una clave de recurso.\n\n`schema.required(name, fn)` hace un campo obligatorio solo cuando `fn(model, operations)` devuelve `true`, por ejemplo solo al insertar.\n\n## Valores por defecto\n\n`schema.define()` devuelve una función que establece el valor por defecto. Esta devuelve de nuevo el esquema:\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Operaciones clásicas\n\nLa forma clásica da al esquema hasta siete operaciones. Cada una recibe `$` y el modelo validado:\n\n| Método | Nombre de la operación en las rutas |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (o `get`) |\n| `schema.setQuery(fn)` | `query` (o `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` añade una operación con tu propio nombre:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Acciones: schema.action()\n\n`schema.action(name, options)` es el estilo más reciente. Un solo objeto declara la operación y todo lo que necesita: la entrada, la query y los parámetros de URL que acepta, y quién puede ejecutarla. La entrada se declara en línea, así que el esquema no necesita `define()`:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nEn `input`, `query` y `params`, los campos se separan con comas, `*` marca un campo obligatorio, `[String]` es un array, `{a|b}` un enum y `@Name` otro esquema o acción. En lugar de una declaración en línea puedes dar el nombre de un esquema JSON de la carpeta `jsonschemas/`.\n\n| Opción | Qué hace |\n| --- | --- |\n| `action` | La función `($, model)` que ejecuta la acción |\n| `name` | Una descripción de la acción |\n| `input` | Campos del cuerpo de la petición. Los datos no válidos detienen la acción |\n| `output` | Campos de la respuesta. Los demás campos se eliminan |\n| `query` | Campos de la query string, convertidos en `$.query` |\n| `params` | Campos de los parámetros de URL, convertidos en `$.params` |\n| `user` | `true`: solo para un usuario autenticado; si no, `401` |\n| `sa` | `true`: solo para un superadministrador (`user.sa` o `user.su`) |\n| `permissions` | `'read,write'`: el usuario necesita uno de ellos en `user.permissions` o `user.roles` |\n| `cache` | Guarda la respuesta en caché: `{ query, params, user, language, expire }` |\n\nAmbos estilos llaman a las operaciones de la misma forma, y puedes mezclarlos en un esquema.\n\n## El objeto $\n\nCada operación recibe `$`. Termina la operación y te da la petición:\n\n| Miembro | Qué es |\n| --- | --- |\n| `$.callback(value)` | Responde con el valor; `$.callback(err)` con un error |\n| `$.success([value])` | Responde `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Responde con un error; `$.invalid(404)` con un código de estado |\n| `$.done([value])` | Devuelve un callback `(err, response)` que responde con éxito o con el error |\n| `$.successful(fn)` | Devuelve un callback que ejecuta `fn(response)` solo cuando no hay error |\n| `$.redirect(url)` | Redirige la petición |\n| `$.model` | El modelo validado |\n| `$.query`, `$.params`, `$.id` | La query string, los parámetros de URL y el primero de ellos |\n| `$.user`, `$.session` | El usuario autenticado y la sesión |\n| `$.keys` | En una petición `PATCH`, los campos que se enviaron |\n| `$.filter` | La query convertida con el filtro de la operación |\n| `$.controller` | El controlador; también `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nLlama exactamente a uno de `$.callback()`, `$.success()`, `$.invalid()` o `$.redirect()` por operación:\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Llamar a operaciones desde rutas\n\n`*Schema --> operation` después de la URL valida el cuerpo de la petición con el esquema y ejecuta la operación. El primer parámetro dinámico pasa a ser `$.id`:\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\nLas peticiones `GET` no tienen cuerpo, así que no hay nada que validar. En una petición `PATCH` solo se validan los campos enviados. Varias operaciones se ejecutan una tras otra, y `(response)` después de una de ellas elige qué resultado se devuelve:\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nToda la sintaxis está en la guía de [Enrutamiento](../routing/).\n\n## NEWACTION(): acciones sin esquema\n\n`NEWACTION(name, options)` declara una acción que no pertenece a ningún esquema. Acepta las mismas opciones que `schema.action()`. Nombra las acciones con una barra, `Users/create`, para agruparlas:\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nUna ruta la llama con `-->` y sin esquema:\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nLa opción `route: 'API /api/'` declara por sí sola una ruta API para la acción; el nombre en la API es el nombre de la acción en minúsculas con `_` en lugar de `/` (`users_create`).\n\n## Ejecutar operaciones desde el código\n\n`CALL()` ejecuta acciones y operaciones de esquema desde cualquier parte de tu código. Empieza en el siguiente tick, así que puedes establecer opciones antes:\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nDentro de una operación, `$.action(name, [data])` hace lo mismo; un nombre sin `-->` es una operación del esquema actual. `EXEC('+Users --> insert', model, callback)` también ejecuta operaciones de esquema y devuelve una promesa si no hay callback. `MAKE('Users', model)` solo valida un modelo.\n\nTodos los métodos están en la referencia de [Esquemas](../../reference/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Schémas et actions","summary":"Déclare des schémas avec des champs typés et validés, écris des opérations et des actions, utilise l'objet $ et appelle-les depuis les routes et le code.","markdown":"---\ntitle: \"Schémas et actions\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Schémas et actions\n\n> Déclare des schémas avec des champs typés et validés, écris des opérations et des actions, utilise l'objet $ et appelle-les depuis les routes et le code.\n\nUn **schéma** décrit les données que reçoit ton application et les opérations qui les traitent. Total.js convertit le corps de la requête dans les types que tu déclares, le valide et exécute ton opération avec un objet `$` qui connaît le modèle, la requête, l'utilisateur et la manière de répondre. Les routes appellent directement les schémas, si bien qu'un endpoint REST n'a souvent pas besoin de sa propre action.\n\nPlace les schémas dans le dossier `schemas/`. Total.js charge tous les fichiers de ce dossier au démarrage de l'application.\n\n## Déclarer un schéma\n\n`NEWSCHEMA(name, declaration)` crée un schéma. La déclaration reçoit le schéma et déclare ses champs et ses opérations :\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDéclarer un schéma avec un nom existant remplace l'ancien. `NEWSCHEMA('Users', null)` le supprime. `GETSCHEMA('Users')` renvoie un schéma déclaré.\n\n## Types de champs\n\n`schema.define(name, type, [required], [error])` accepte un constructeur, un nom de type (la casse n'a pas d'importance), un tableau ou un objet :\n\n| Type | Ce que devient la valeur |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | Une chaîne sans espaces superflus. `'String(50)'` la coupe à 50 caractères |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | Une chaîne dont la casse est modifiée |\n| `'SafeString'` | Une chaîne vérifiée contre les attaques XSS et les injections SQL |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | Une chaîne ; un champ obligatoire doit avoir une valeur valide |\n| `'Color'`, `'Icon'` | Une chaîne avec une couleur ou un nom d'icône |\n| `'UID'` ou `UID`, `'GUID'` ou `GUID` | Un identifiant |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | Un nombre décimal |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | Un entier |\n| `'Number2'` | Un nombre ; lorsqu'il est obligatoire, `0` est aussi valide |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` ou `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | Une date |\n| `Object`, `'Object'` | N'importe quel objet |\n| `'name:String, age:Number'` | Un objet avec ces champs |\n| `['a', 'b']` | Une énumération : l'une des valeurs |\n| `{ a: 'A', b: 'B' }` | Une liste clé-valeur : l'une des clés |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | Un tableau, du type indiqué entre crochets |\n| `'Address'`, `'[Address]'` | Un autre schéma, ou un tableau de celui-ci, validé avec ses propres règles |\n\nLe modèle que reçoit ton opération ne contient que les champs déclarés, déjà convertis. Un schéma sans champs transmet le corps tel qu'il est arrivé.\n\n## Champs obligatoires et messages d'erreur\n\nLe troisième argument rend un champ obligatoire. Ce que vérifie « obligatoire » dépend du type :\n\n- une chaîne ne doit pas être vide, et `Email`, `Phone`, `URL`, `UID` et similaires doivent être valides ;\n- un nombre doit être supérieur à `0`, et un booléen doit valoir `true` ;\n- un tableau ne doit pas être vide.\n\nÀ la place de `true`, tu peux passer une fonction `(value, model)` qui renvoie `true`, `false` ou un message d'erreur. Une chaîne en troisième argument rend le champ obligatoire et sert de message d'erreur :\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nSans message, Total.js le lit depuis la ressource définie avec `schema.setResource()` (la clé est le nom du champ), ou répond `The field \"name\" is invalid`. Un message qui commence par `@` est une clé de ressource.\n\n`schema.required(name, fn)` rend un champ obligatoire uniquement lorsque `fn(model, operations)` renvoie `true`, par exemple uniquement lors d'une insertion.\n\n## Valeurs par défaut\n\n`schema.define()` renvoie une fonction qui définit la valeur par défaut. Celle-ci renvoie à nouveau le schéma :\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Opérations classiques\n\nLa méthode classique donne au schéma jusqu'à sept opérations. Chacune reçoit `$` et le modèle validé :\n\n| Méthode | Nom de l'opération dans les routes |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (ou `get`) |\n| `schema.setQuery(fn)` | `query` (ou `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` ajoute une opération avec le nom de ton choix :\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Actions : schema.action()\n\n`schema.action(name, options)` est le style le plus récent. Un seul objet déclare l'opération et tout ce dont elle a besoin : l'entrée, la query et les paramètres d'URL qu'elle accepte, et qui peut l'exécuter. L'entrée est déclarée en ligne, le schéma n'a donc pas besoin de `define()` :\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nDans `input`, `query` et `params`, les champs sont séparés par des virgules, `*` marque un champ obligatoire, `[String]` est un tableau, `{a|b}` une énumération et `@Name` un autre schéma ou une autre action. À la place d'une déclaration en ligne, tu peux donner le nom d'un schéma JSON du dossier `jsonschemas/`.\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `action` | La fonction `($, model)` qui exécute l'action |\n| `name` | Une description de l'action |\n| `input` | Champs du corps de la requête. Des données invalides arrêtent l'action |\n| `output` | Champs de la réponse. Les autres champs sont supprimés |\n| `query` | Champs de la query string, convertis dans `$.query` |\n| `params` | Champs des paramètres d'URL, convertis dans `$.params` |\n| `user` | `true` : uniquement pour un utilisateur connecté, sinon `401` |\n| `sa` | `true` : uniquement pour un super administrateur (`user.sa` ou `user.su`) |\n| `permissions` | `'read,write'` : l'utilisateur doit avoir l'une d'elles dans `user.permissions` ou `user.roles` |\n| `cache` | Met la réponse en cache : `{ query, params, user, language, expire }` |\n\nLes deux styles appellent les opérations de la même façon, et tu peux les combiner dans un même schéma.\n\n## L'objet $\n\nChaque opération reçoit `$`. Il termine l'opération et te donne accès à la requête :\n\n| Membre | Ce que c'est |\n| --- | --- |\n| `$.callback(value)` | Répond avec la valeur ; `$.callback(err)` avec une erreur |\n| `$.success([value])` | Répond `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Répond avec une erreur ; `$.invalid(404)` avec un code de statut |\n| `$.done([value])` | Renvoie un callback `(err, response)` qui répond par un succès ou par l'erreur |\n| `$.successful(fn)` | Renvoie un callback qui exécute `fn(response)` uniquement en l'absence d'erreur |\n| `$.redirect(url)` | Redirige la requête |\n| `$.model` | Le modèle validé |\n| `$.query`, `$.params`, `$.id` | La query string, les paramètres d'URL et le premier d'entre eux |\n| `$.user`, `$.session` | L'utilisateur connecté et la session |\n| `$.keys` | Dans une requête `PATCH`, les champs qui ont été envoyés |\n| `$.filter` | La query convertie avec le filtre de l'opération |\n| `$.controller` | Le contrôleur ; également `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nAppelle exactement un seul de `$.callback()`, `$.success()`, `$.invalid()` ou `$.redirect()` par opération :\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Appeler des opérations depuis les routes\n\n`*Schema --> operation` après l'URL valide le corps de la requête avec le schéma et exécute l'opération. Le premier paramètre dynamique devient `$.id` :\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\nLes requêtes `GET` n'ont pas de corps, il n'y a donc rien à valider. Dans une requête `PATCH`, seuls les champs envoyés sont validés. Plusieurs opérations s'exécutent l'une après l'autre, et `(response)` après l'une d'elles choisit quel résultat est renvoyé :\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nToute la syntaxe se trouve dans le guide [Routage](../routing/).\n\n## NEWACTION() : des actions sans schéma\n\n`NEWACTION(name, options)` déclare une action qui n'appartient à aucun schéma. Elle accepte les mêmes options que `schema.action()`. Nomme les actions avec une barre oblique, `Users/create`, pour les regrouper :\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nUne route l'appelle avec `-->` et sans schéma :\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nL'option `route: 'API /api/'` déclare elle-même une route API pour l'action ; le nom de l'API est le nom de l'action en minuscules avec `_` à la place de `/` (`users_create`).\n\n## Exécuter des opérations depuis le code\n\n`CALL()` exécute des actions et des opérations de schéma depuis n'importe quel endroit de ton code. Elle démarre au tick suivant, tu peux donc définir des options auparavant :\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nDans une opération, `$.action(name, [data])` fait de même ; un nom sans `-->` désigne une opération du schéma courant. `EXEC('+Users --> insert', model, callback)` exécute aussi des opérations de schéma et renvoie une promesse sans callback. `MAKE('Users', model)` ne fait que valider un modèle.\n\nToutes les méthodes se trouvent dans la référence [Schémas](../../reference/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Schemi e azioni","summary":"Dichiara schemi con campi tipizzati e validati, scrivi operazioni e azioni, usa l'oggetto $ e chiamali dalle route e dal codice.","markdown":"---\ntitle: Schemi e azioni\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Schemi e azioni\n\n> Dichiara schemi con campi tipizzati e validati, scrivi operazioni e azioni, usa l'oggetto $ e chiamali dalle route e dal codice.\n\nUno **schema** descrive i dati che la tua app riceve e le operazioni che lavorano con essi. Total.js converte il corpo della richiesta nei tipi che dichiari, lo valida ed esegue la tua operazione con un oggetto `$` che conosce il modello, la query, l'utente e come rispondere. Le route chiamano gli schemi direttamente, quindi un endpoint REST spesso non ha bisogno di un'azione propria.\n\nMetti gli schemi nella cartella `schemas/`. Total.js carica ogni file presente lì all'avvio dell'app.\n\n## Dichiarare uno schema\n\n`NEWSCHEMA(name, declaration)` crea uno schema. La dichiarazione riceve lo schema e ne dichiara i campi e le operazioni:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDichiarare uno schema con un nome già esistente sostituisce quello vecchio. `NEWSCHEMA('Users', null)` lo rimuove. `GETSCHEMA('Users')` restituisce uno schema dichiarato.\n\n## Tipi di campo\n\n`schema.define(name, type, [required], [error])` accetta un costruttore, il nome di un tipo (maiuscole e minuscole non contano), un array o un oggetto:\n\n| Tipo | Cosa diventa il valore |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | Una stringa senza spazi iniziali e finali. `'String(50)'` la taglia a 50 caratteri |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | Una stringa con maiuscole e minuscole modificate |\n| `'SafeString'` | Una stringa controllata contro XSS e SQL injection |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | Una stringa; un campo obbligatorio deve avere un valore valido |\n| `'Color'`, `'Icon'` | Una stringa con un colore o il nome di un'icona |\n| `'UID'` o `UID`, `'GUID'` o `GUID` | Un identificatore |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | Un numero decimale |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | Un intero |\n| `'Number2'` | Un numero; quando è obbligatorio, anche `0` è valido |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` o `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | Una data |\n| `Object`, `'Object'` | Qualsiasi oggetto |\n| `'name:String, age:Number'` | Un oggetto con questi campi |\n| `['a', 'b']` | Un enum: uno dei valori |\n| `{ a: 'A', b: 'B' }` | Un elenco chiave-valore: una delle chiavi |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | Un array, del tipo tra parentesi quadre |\n| `'Address'`, `'[Address]'` | Un altro schema, o un array di esso, validato con le sue regole |\n\nIl modello che la tua operazione riceve contiene solo i campi dichiarati, già convertiti. Uno schema senza campi passa il corpo così come è arrivato.\n\n## Campi obbligatori e messaggi di errore\n\nIl terzo argomento rende un campo obbligatorio. Cosa verifica \"obbligatorio\" dipende dal tipo:\n\n- una stringa non deve essere vuota, e `Email`, `Phone`, `URL`, `UID` e simili devono essere validi;\n- un numero deve essere maggiore di `0`, e un booleano deve essere `true`;\n- un array non deve essere vuoto.\n\nAl posto di `true` puoi passare una funzione `(value, model)` che restituisce `true`, `false` o un messaggio di errore. Una stringa come terzo argomento rende il campo obbligatorio ed è il suo messaggio di errore:\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nSenza un messaggio, Total.js lo legge dalla risorsa impostata con `schema.setResource()` (la chiave è il nome del campo), oppure risponde `The field \"name\" is invalid`. Un messaggio che inizia con `@` è una chiave di risorsa.\n\n`schema.required(name, fn)` rende un campo obbligatorio solo quando `fn(model, operations)` restituisce `true`, per esempio solo in inserimento.\n\n## Valori predefiniti\n\n`schema.define()` restituisce una funzione che imposta il valore predefinito. Questa restituisce di nuovo lo schema:\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Operazioni classiche\n\nIl modo classico dà allo schema fino a sette operazioni. Ognuna riceve `$` e il modello validato:\n\n| Metodo | Nome dell'operazione nelle route |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (o `get`) |\n| `schema.setQuery(fn)` | `query` (o `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` aggiunge un'operazione con un nome scelto da te:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Azioni: schema.action()\n\n`schema.action(name, options)` è lo stile più recente. Un solo oggetto dichiara l'operazione e tutto ciò che le serve: l'input, la query e i parametri dell'URL che accetta, e chi può eseguirla. L'input è dichiarato inline, quindi lo schema non ha bisogno di `define()`:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nIn `input`, `query` e `params` i campi sono separati da virgole, `*` contrassegna un campo obbligatorio, `[String]` è un array, `{a|b}` un enum e `@Name` un altro schema o un'altra azione. Al posto di una dichiarazione inline puoi indicare il nome di un JSON schema della cartella `jsonschemas/`.\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `action` | La funzione `($, model)` che esegue l'azione |\n| `name` | Una descrizione dell'azione |\n| `input` | Campi del corpo della richiesta. Dati non validi fermano l'azione |\n| `output` | Campi della risposta. Gli altri campi vengono rimossi |\n| `query` | Campi della query string, convertiti in `$.query` |\n| `params` | Campi dei parametri dell'URL, convertiti in `$.params` |\n| `user` | `true`: solo per un utente autenticato, altrimenti `401` |\n| `sa` | `true`: solo per un super admin (`user.sa` o `user.su`) |\n| `permissions` | `'read,write'`: l'utente ne ha bisogno di uno in `user.permissions` o `user.roles` |\n| `cache` | Mette in cache la risposta: `{ query, params, user, language, expire }` |\n\nEntrambi gli stili chiamano le operazioni nello stesso modo, e puoi mescolarli in uno stesso schema.\n\n## L'oggetto $\n\nOgni operazione riceve `$`. Termina l'operazione e ti dà accesso alla richiesta:\n\n| Membro | Cos'è |\n| --- | --- |\n| `$.callback(value)` | Risponde con il valore; `$.callback(err)` con un errore |\n| `$.success([value])` | Risponde `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Risponde con un errore; `$.invalid(404)` con un codice di stato |\n| `$.done([value])` | Restituisce una callback `(err, response)` che risponde con il successo o con l'errore |\n| `$.successful(fn)` | Restituisce una callback che esegue `fn(response)` solo quando non c'è errore |\n| `$.redirect(url)` | Reindirizza la richiesta |\n| `$.model` | Il modello validato |\n| `$.query`, `$.params`, `$.id` | La query string, i parametri dell'URL e il primo di essi |\n| `$.user`, `$.session` | L'utente autenticato e la sessione |\n| `$.keys` | In una richiesta `PATCH`, i campi che sono stati inviati |\n| `$.filter` | La query convertita con il filtro dell'operazione |\n| `$.controller` | Il controller; inoltre `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nChiama esattamente uno tra `$.callback()`, `$.success()`, `$.invalid()` o `$.redirect()` per ogni operazione:\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Chiamare operazioni dalle route\n\n`*Schema --> operation` dopo l'URL valida il corpo della richiesta con lo schema ed esegue l'operazione. Il primo parametro dinamico diventa `$.id`:\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\nLe richieste `GET` non hanno corpo, quindi non c'è niente da validare. In una richiesta `PATCH` vengono validati solo i campi inviati. Più operazioni vengono eseguite una dopo l'altra, e `(response)` dopo una di esse sceglie quale risultato viene restituito:\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nTutta la sintassi è nella guida [Routing](../routing/).\n\n## NEWACTION(): azioni senza schema\n\n`NEWACTION(name, options)` dichiara un'azione che non appartiene a nessuno schema. Accetta le stesse opzioni di `schema.action()`. Dai alle azioni un nome con una barra, `Users/create`, per raggrupparle:\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nUna route la chiama con `-->` e senza schema:\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nL'opzione `route: 'API /api/'` dichiara da sola una route API per l'azione; il nome API è il nome dell'azione in minuscolo con `_` al posto di `/` (`users_create`).\n\n## Eseguire operazioni dal codice\n\n`CALL()` esegue azioni e operazioni di schema da qualsiasi punto del tuo codice. Parte al tick successivo, quindi puoi prima impostare delle opzioni:\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nDentro un'operazione, `$.action(name, [data])` fa lo stesso; un nome senza `-->` è un'operazione dello schema corrente. Anche `EXEC('+Users --> insert', model, callback)` esegue operazioni di schema e, senza callback, restituisce una promise. `MAKE('Users', model)` si limita a validare un modello.\n\nTutti i metodi sono nel riferimento [Schemi](../../reference/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUAX37U60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Schémy a akcie","summary":"Deklaruj schémy s typovanými a validovanými poľami, napíš operácie a akcie, používaj objekt $ a volaj ich z trás aj z kódu.","markdown":"---\ntitle: \"Schémy a akcie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/schemas/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Schémy a akcie\n\n> Deklaruj schémy s typovanými a validovanými poľami, napíš operácie a akcie, používaj objekt $ a volaj ich z trás aj z kódu.\n\n**Schéma** opisuje dáta, ktoré tvoja aplikácia prijíma, a operácie, ktoré s nimi pracujú. Total.js skonvertuje telo požiadavky na typy, ktoré deklaruješ, zvaliduje ho a spustí tvoju operáciu s objektom `$`, ktorý pozná model, query, používateľa a vie, ako odpovedať. Trasy volajú schémy priamo, takže REST endpoint často nepotrebuje vlastnú akciu.\n\nSchémy daj do priečinka `schemas/`. Total.js pri štarte aplikácie načíta každý súbor v ňom.\n\n## Deklarácia schémy\n\n`NEWSCHEMA(name, declaration)` vytvorí schému. Deklarácia dostane schému a deklaruje jej polia a operácie:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('id', 'UID');\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\tschema.define('age', Number);\n\tschema.define('role', ['admin', 'user']);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nDeklarácia schémy s existujúcim názvom nahradí starú. `NEWSCHEMA('Users', null)` ju odstráni. `GETSCHEMA('Users')` vráti deklarovanú schému.\n\n## Typy polí\n\n`schema.define(name, type, [required], [error])` prijíma konštruktor, názov typu (na veľkosti písmen nezáleží), pole alebo objekt:\n\n| Typ | Čím sa hodnota stane |\n| --- | --- |\n| `String`, `'String'`, `'Text'` | Orezaný reťazec. `'String(50)'` ho skráti na 50 znakov |\n| `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'` | Reťazec so zmenenou veľkosťou písmen |\n| `'SafeString'` | Reťazec skontrolovaný na XSS a SQL injection |\n| `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'` | Reťazec; povinné pole musí mať platnú hodnotu |\n| `'Color'`, `'Icon'` | Reťazec s farbou alebo názvom ikony |\n| `'UID'` alebo `UID`, `'GUID'` alebo `GUID` | Identifikátor |\n| `Number`, `'Number'`, `'Float'`, `'Decimal'`, `'Double'` | Desatinné číslo |\n| `'Int'`, `'Integer'`, `'Byte'`, `'TinyInt'`, `'SmallInt'` | Celé číslo |\n| `'Number2'` | Číslo; keď je povinné, platná je aj `0` |\n| `Boolean`, `'Boolean'`, `'Bool'` | `true` alebo `false` |\n| `Date`, `'Date'`, `'Time'`, `'DateTime'` | Dátum |\n| `Object`, `'Object'` | Ľubovoľný objekt |\n| `'name:String, age:Number'` | Objekt s týmito poľami |\n| `['a', 'b']` | Enum: jedna z hodnôt |\n| `{ a: 'A', b: 'B' }` | Zoznam kľúč-hodnota: jeden z kľúčov |\n| `Array`, `'[]'`, `'[String]'`, `'[Number]'` | Pole typu v hranatých zátvorkách |\n| `'Address'`, `'[Address]'` | Iná schéma alebo jej pole, validované jej vlastnými pravidlami |\n\nModel, ktorý tvoja operácia dostane, obsahuje len deklarované polia, už skonvertované. Schéma bez polí odovzdá telo tak, ako prišlo.\n\n## Povinné polia a chybové hlásenia\n\nTretí argument robí pole povinným. Čo „povinné“ kontroluje, závisí od typu:\n\n- reťazec nesmie byť prázdny a `Email`, `Phone`, `URL`, `UID` a podobné musia byť platné;\n- číslo musí byť väčšie ako `0` a boolean musí byť `true`;\n- pole nesmie byť prázdne.\n\nNamiesto `true` môžeš odovzdať funkciu `(value, model)`, ktorá vráti `true`, `false` alebo chybové hlásenie. Reťazec ako tretí argument urobí pole povinným a je jeho chybovým hlásením:\n\n```js\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('password', 'String(30)', true, 'The password is too short');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\n```\n\nBez hlásenia ho Total.js prečíta zo zdroja nastaveného pomocou `schema.setResource()` (kľúčom je názov poľa) alebo odpovie `The field \"name\" is invalid`. Hlásenie, ktoré začína na `@`, je kľúč zdroja.\n\n`schema.required(name, fn)` urobí pole povinným len vtedy, keď `fn(model, operations)` vráti `true`, napríklad len pri vkladaní.\n\n## Predvolené hodnoty\n\n`schema.define()` vracia funkciu, ktorá nastaví predvolenú hodnotu. Tá opäť vracia schému:\n\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n## Klasické operácie\n\nKlasický spôsob dáva schéme až sedem operácií. Každá dostane `$` a validovaný model:\n\n| Metóda | Názov operácie v trasách |\n| --- | --- |\n| `schema.setSave(fn)` | `save` |\n| `schema.setInsert(fn)` | `insert` |\n| `schema.setUpdate(fn)` | `update` |\n| `schema.setPatch(fn)` | `patch` |\n| `schema.setRead(fn)` | `read` (alebo `get`) |\n| `schema.setQuery(fn)` | `query` (alebo `list`) |\n| `schema.setRemove(fn)` | `remove` |\n\n`schema.addWorkflow(name, fn)` pridá operáciu s vlastným názvom:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\n\tschema.setQuery(function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t});\n\n\tschema.setRead(function($) {\n\t\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n\t});\n\n\tschema.addWorkflow('activate', function($) {\n\t\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t\t$.success();\n\t});\n\n});\n```\n\n## Akcie: schema.action()\n\n`schema.action(name, options)` je novší štýl. Jeden objekt deklaruje operáciu a všetko, čo potrebuje: vstup, query a parametre URL, ktoré prijíma, a kto ju smie spustiť. Vstup sa deklaruje priamo na mieste, takže schéma nepotrebuje `define()`:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nV `input`, `query` a `params` sa polia oddeľujú čiarkami, `*` označuje povinné pole, `[String]` je pole, `{a|b}` enum a `@Name` iná schéma alebo akcia. Namiesto deklarácie na mieste môžeš uviesť názov JSON schémy z priečinka `jsonschemas/`.\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `action` | Funkcia `($, model)`, ktorá vykoná akciu |\n| `name` | Popis akcie |\n| `input` | Polia tela požiadavky. Neplatné dáta akciu zastavia |\n| `output` | Polia odpovede. Ostatné polia sa odstránia |\n| `query` | Polia query stringu, skonvertované do `$.query` |\n| `params` | Polia parametrov URL, skonvertované do `$.params` |\n| `user` | `true`: len pre prihláseného používateľa, inak `401` |\n| `sa` | `true`: len pre super admina (`user.sa` alebo `user.su`) |\n| `permissions` | `'read,write'`: používateľ potrebuje jedno z nich v `user.permissions` alebo `user.roles` |\n| `cache` | Uloží odpoveď do cache: `{ query, params, user, language, expire }` |\n\nOba štýly volajú operácie rovnako a v jednej schéme ich môžeš kombinovať.\n\n## Objekt $\n\nKaždá operácia dostane `$`. Ukončuje operáciu a sprístupňuje ti požiadavku:\n\n| Člen | Čo to je |\n| --- | --- |\n| `$.callback(value)` | Odpovie hodnotou; `$.callback(err)` chybou |\n| `$.success([value])` | Odpovie `{ \"success\": true, \"value\": ... }` |\n| `$.invalid(name, [message])` | Odpovie chybou; `$.invalid(404)` stavovým kódom |\n| `$.done([value])` | Vráti callback `(err, response)`, ktorý odpovie úspechom alebo chybou |\n| `$.successful(fn)` | Vráti callback, ktorý spustí `fn(response)` len vtedy, keď nenastala chyba |\n| `$.redirect(url)` | Presmeruje požiadavku |\n| `$.model` | Validovaný model |\n| `$.query`, `$.params`, `$.id` | Query string, parametre URL a prvý z nich |\n| `$.user`, `$.session` | Prihlásený používateľ a relácia |\n| `$.keys` | V požiadavke `PATCH` polia, ktoré boli odoslané |\n| `$.filter` | Query skonvertované filtrom operácie |\n| `$.controller` | Kontrolér; tiež `$.req`, `$.res`, `$.headers`, `$.ip`, `$.language`, `$.files`, `$.body` |\n\nV každej operácii zavolaj práve jedno z `$.callback()`, `$.success()`, `$.invalid()` alebo `$.redirect()`:\n\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.callback(user);\n\t\telse\n\t\t\t$.invalid(404);\n\t});\n});\n```\n\n## Volanie operácií z trás\n\n`*Schema --> operation` za URL zvaliduje telo požiadavky schémou a spustí operáciu. Prvý dynamický parameter sa stane `$.id`:\n\n```js\nexports.install = function() {\n\tROUTE('GET    /api/users/          *Users --> query');\n\tROUTE('GET    /api/users/{id}/     *Users --> read');\n\tROUTE('POST   /api/users/          *Users --> insert');\n\tROUTE('PATCH  /api/users/{id}/     *Users --> patch');\n\tROUTE('DELETE /api/users/{id}/     *Users --> remove');\n\tROUTE('POST   /api/users/{id}/activate/ *Users --> activate');\n};\n```\n\nPožiadavky `GET` nemajú telo, takže nie je čo validovať. V požiadavke `PATCH` sa validujú len polia, ktoré boli odoslané. Viac operácií beží jedna po druhej a `(response)` za jednou z nich určuje, ktorej výsledok sa pošle späť:\n\n```js\nROUTE('POST /api/users/ *Users --> insert (response) notify');\n```\n\nCelá syntax je v príručke [Smerovanie](../routing/).\n\n## NEWACTION(): akcie bez schémy\n\n`NEWACTION(name, options)` deklaruje akciu, ktorá nepatrí žiadnej schéme. Prijíma rovnaké možnosti ako `schema.action()`. Akcie pomenuj s lomkou, `Users/create`, aby si ich zoskupil:\n\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\nTrasa ju volá pomocou `-->` bez schémy:\n\n```js\nROUTE('POST /api/users/ --> Users/create');\n```\n\nMožnosť `route: 'API /api/'` sama deklaruje API trasu pre akciu; názov API je názov akcie malými písmenami s `_` namiesto `/` (`users_create`).\n\n## Spúšťanie operácií z kódu\n\n`CALL()` spúšťa akcie a operácie schém odkiaľkoľvek v tvojom kóde. Začne v nasledujúcom ticku, takže môžeš najprv nastaviť možnosti:\n\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\t// ...\n});\n\nvar users = await CALL('Users --> list').query({ page: 1 }).promise();\n```\n\nVnútri operácie robí to isté `$.action(name, [data])`; názov bez `-->` je operácia aktuálnej schémy. `EXEC('+Users --> insert', model, callback)` tiež spúšťa operácie schém a bez callbacku vráti promise. `MAKE('Users', model)` model len zvaliduje.\n\nVšetky metódy sú v referencii [Schémy](../../reference/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Views","summary":"HTML templates in views/: expressions, conditions, loops, layouts, partials, sections, helpers and localization.","markdown":"---\ntitle: Views\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Views\n\n> HTML templates in views/: expressions, conditions, loops, layouts, partials, sections, helpers and localization.\n\nA view is an HTML file in `views/` with commands in `@{...}`. Total.js compiles it into a JavaScript function, runs it with a model, wraps the result in a layout and sends it as the response.\n\n## Where views live\n\nViews are `.html` files in `views/`. You name them without the extension.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nA controller looks first in the folder with its own name. In `controllers/users.js`, `this.view('detail')` renders `views/users/detail.html`. When that file does not exist, Total.js tries `views/detail.html`. The controller `default.js` uses `views/` directly.\n\nA prefix changes where the view is looked up:\n\n| Name | File |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, then `views/index.html` |\n| `~index` | `views/index.html`, always from the root of `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | the view of a package |\n| `#plugin/index` | the view of a plugin |\n| `.path/to/file` | an absolute path, without `.html` |\n\n## Render a view\n\nThe simplest route has the name of a view instead of an action:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nFrom an action, call `this.view()` with the name and a model:\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nWithout a name, `this.view(model)` renders the view named after the last part of the URL (`index` for `/`).\n\nA schema operation can render its result as a view. The result becomes the model:\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## The model and the repository\n\nThe model is the second argument of `this.view()`. In the view it is `model` (or `M`):\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\nThe **repository** is an object shared by the view, its partial views and the layout during one request. Use it to pass values that are not part of the model, like a page class. It is `controller.repository` in JavaScript and `repository` (or `R`) in the view:\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nA view can also assign values. The command prints nothing:\n\n```html\n@{repository.page = 'products'}\n```\n\nOther variables you can use in a view: `user`, `session`, `query`, `body` (request body, see the layout section for `@{body}` alone), `config`, `language`, `url`, `controller`.\n\n## Expressions and escaping\n\n`@{expression}` prints the value of any JavaScript expression, **HTML-encoded**. Put `!` in front to print it **raw**:\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nWith `model.name = '<b>Peter</b>'`, `@{model.name}` prints `&lt;b&gt;Peter&lt;/b&gt;`, and `@{!model.name}` prints the bold tag. `null` and `undefined` print nothing.\n\nUse the raw form only for HTML you trust. The output of helpers, `@{json()}` and the form commands is not encoded again.\n\nText that starts with `@{{` is not a command; it is left in the page as it is.\n\n## Conditions\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nThe condition is JavaScript. Close it with `@{fi}` or `@{endif}`.\n\n## Loops\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` is the position of the item, from `0`. An empty array prints nothing. When you loop over an object, each item has `key` and `value`:\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` and `@{break}` work inside the loop, usually in an `@{if}`.\n\n## Layouts\n\nEvery view is rendered inside a layout. The default layout is `views/layout.html` (`default_layout` in the config). `@{body}` prints the rendered view:\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nIf the layout file does not exist, the request ends with an error 500. Create it, or turn the layout off.\n\nChange the layout in the controller or in the view:\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nThe layout gets the same model and repository as the view.\n\n## Partial views\n\n`@{view(name, [model])}` renders another view in place, without a layout. Pass the model if the partial needs it:\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nThe name is resolved like any view, so `partials/product` is `views/partials/product.html` (or inside the folder of the controller). Add an expiration and a key to cache the output: `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Sections\n\nA section is HTML written in the view and printed in the layout, for example scripts of one page:\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nSeveral blocks with the same name are joined. From a controller use `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Helpers\n\nTotal.js has view helpers for common HTML: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` and more. They are listed in the [Views reference](../../reference/views/).\n\nDefine your own helpers in `DEF.helpers`, usually in a file in `definitions/`. In a helper `this` is the controller:\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nCall it by its name:\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nThe output of a helper is not encoded; encode the values yourself when they come from users. `@{helper('price', item.price)}` does the same call.\n\nA helper used by only one view can be written inside it:\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Localization\n\nText in `@(...)` is translated when the view is compiled, with the language of the request (`controller.language`, set by `DEF.onLocale`):\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nThe translation comes from the resource file of the language. When there is none, the text stays as it is. `@(#key)` reads the key `key` from the resource directly. `@{resource('key')}` prints a key of `default.resource`, and `@{resource('en', 'key')}` a key of `en.resource`.\n\n## CSS, JavaScript and images\n\n`@{import()}` writes the tags for static files. Relative names go to the static folders (`/css/`, `/js/`, `/img/`):\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` prints the title and meta tags, `head` the tags added with `@{head()}`. Join files with `+` to merge them into one: `@{import('default.css + ui.css')}`.\n\n## Title and meta tags\n\nSet the title and the description in the controller or in the view, and print them with `@{meta}` (or `@{import('meta')}`) in the layout:\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nThe title gets ` - ` and the name of the app (`CONF.name`) at the end, unless `allow_custom_titles` is `true` in the config.\n\n## Compilation and caching\n\nThe first time a view is used, Total.js reads it, removes HTML comments, minifies the HTML with its inline CSS and JavaScript, translates `@(...)` and compiles it. In **release** mode the compiled view is kept in memory, once per language. In **debug** mode it is compiled on every request, so your changes appear without a restart.\n\nPut `@{nocompress html}` at the top of a view to keep its HTML as written (`css`, `js` and `all` also work).\n\n## Render a view to a string\n\n`VIEW(name, [model], [layout], [repository], [language])` renders a view anywhere and returns HTML, without a layout unless you name one:\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Views","summary":"HTML-Templates in views/: Ausdrücke, Bedingungen, Schleifen, Layouts, Partials, Sections, Helfer und Lokalisierung.","markdown":"---\ntitle: Views\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Views\n\n> HTML-Templates in views/: Ausdrücke, Bedingungen, Schleifen, Layouts, Partials, Sections, Helfer und Lokalisierung.\n\nEine View ist eine HTML-Datei in `views/` mit Befehlen in `@{...}`. Total.js kompiliert sie zu einer JavaScript-Funktion, führt sie mit einem Modell aus, umschließt das Ergebnis mit einem Layout und sendet es als Antwort.\n\n## Wo Views liegen\n\nViews sind `.html`-Dateien in `views/`. Du benennst sie ohne die Endung.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nEin Controller sucht zuerst im Ordner mit seinem eigenen Namen. In `controllers/users.js` rendert `this.view('detail')` die Datei `views/users/detail.html`. Existiert diese Datei nicht, versucht Total.js `views/detail.html`. Der Controller `default.js` verwendet direkt `views/`.\n\nEin Präfix ändert, wo die View gesucht wird:\n\n| Name | Datei |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, dann `views/index.html` |\n| `~index` | `views/index.html`, immer ab der Wurzel von `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | die View eines Pakets |\n| `#plugin/index` | die View eines Plugins |\n| `.path/to/file` | ein absoluter Pfad, ohne `.html` |\n\n## Eine View rendern\n\nDie einfachste Route hat statt einer Aktion den Namen einer View:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nRufe in einer Aktion `this.view()` mit dem Namen und einem Modell auf:\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nOhne Namen rendert `this.view(model)` die View, die nach dem letzten Teil der URL benannt ist (`index` für `/`).\n\nEine Schema-Operation kann ihr Ergebnis als View rendern. Das Ergebnis wird zum Modell:\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## Das Modell und das Repository\n\nDas Modell ist das zweite Argument von `this.view()`. In der View heißt es `model` (oder `M`):\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\nDas **Repository** ist ein Objekt, das sich die View, ihre Partial Views und das Layout während einer Anfrage teilen. Verwende es, um Werte zu übergeben, die nicht zum Modell gehören, etwa eine Seitenklasse. In JavaScript ist es `controller.repository` und in der View `repository` (oder `R`):\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nEine View kann auch Werte zuweisen. Der Befehl gibt nichts aus:\n\n```html\n@{repository.page = 'products'}\n```\n\nWeitere Variablen, die du in einer View verwenden kannst: `user`, `session`, `query`, `body` (Body der Anfrage; zu `@{body}` allein siehe den Abschnitt über Layouts), `config`, `language`, `url`, `controller`.\n\n## Ausdrücke und Escaping\n\n`@{expression}` gibt den Wert eines beliebigen JavaScript-Ausdrucks aus, **HTML-kodiert**. Setze `!` davor, um ihn **roh** auszugeben:\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nMit `model.name = '<b>Peter</b>'` gibt `@{model.name}` den Text `&lt;b&gt;Peter&lt;/b&gt;` aus, und `@{!model.name}` gibt das Fett-Tag aus. `null` und `undefined` geben nichts aus.\n\nVerwende die rohe Form nur für HTML, dem du vertraust. Die Ausgabe von Helfern, `@{json()}` und den Formularbefehlen wird nicht erneut kodiert.\n\nText, der mit `@{{` beginnt, ist kein Befehl; er bleibt unverändert in der Seite.\n\n## Bedingungen\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nDie Bedingung ist JavaScript. Schließe sie mit `@{fi}` oder `@{endif}`.\n\n## Schleifen\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` ist die Position des Elements, ab `0`. Ein leeres Array gibt nichts aus. Wenn du über ein Objekt iterierst, hat jedes Element `key` und `value`:\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` und `@{break}` funktionieren innerhalb der Schleife, meist in einem `@{if}`.\n\n## Layouts\n\nJede View wird innerhalb eines Layouts gerendert. Das Standardlayout ist `views/layout.html` (`default_layout` in der Konfiguration). `@{body}` gibt die gerenderte View aus:\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nExistiert die Layout-Datei nicht, endet die Anfrage mit einem Fehler 500. Erstelle sie oder schalte das Layout aus.\n\nÄndere das Layout im Controller oder in der View:\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nDas Layout erhält dasselbe Modell und dasselbe Repository wie die View.\n\n## Partial Views\n\n`@{view(name, [model])}` rendert an dieser Stelle eine andere View, ohne Layout. Übergib das Modell, wenn das Partial es braucht:\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nDer Name wird wie bei jeder View aufgelöst, daher ist `partials/product` die Datei `views/partials/product.html` (oder innerhalb des Ordners des Controllers). Füge eine Ablaufzeit und einen Schlüssel hinzu, um die Ausgabe zu cachen: `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Sections\n\nEine Section ist HTML, das in der View geschrieben und im Layout ausgegeben wird, zum Beispiel die Skripte einer einzelnen Seite:\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nMehrere Blöcke mit demselben Namen werden zusammengefügt. In einem Controller verwendest du `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Helfer\n\nTotal.js hat View-Helfer für gängiges HTML: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` und weitere. Sie sind in der [Referenz zu Views](../../reference/views/) aufgeführt.\n\nDefiniere eigene Helfer in `DEF.helpers`, meist in einer Datei in `definitions/`. In einem Helfer ist `this` der Controller:\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nRufe ihn über seinen Namen auf:\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nDie Ausgabe eines Helfers wird nicht kodiert; kodiere die Werte selbst, wenn sie von Benutzern stammen. `@{helper('price', item.price)}` macht denselben Aufruf.\n\nEin Helfer, den nur eine View verwendet, kann direkt in ihr geschrieben werden:\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Lokalisierung\n\nText in `@(...)` wird beim Kompilieren der View übersetzt, mit der Sprache der Anfrage (`controller.language`, gesetzt von `DEF.onLocale`):\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nDie Übersetzung kommt aus der Ressourcendatei der Sprache. Gibt es keine, bleibt der Text unverändert. `@(#key)` liest den Schlüssel `key` direkt aus der Ressource. `@{resource('key')}` gibt einen Schlüssel aus `default.resource` aus, und `@{resource('en', 'key')}` einen Schlüssel aus `en.resource`.\n\n## CSS, JavaScript und Bilder\n\n`@{import()}` schreibt die Tags für statische Dateien. Relative Namen verweisen auf die statischen Ordner (`/css/`, `/js/`, `/img/`):\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` gibt den Titel und die Meta-Tags aus, `head` die mit `@{head()}` hinzugefügten Tags. Verbinde Dateien mit `+`, um sie zu einer zusammenzuführen: `@{import('default.css + ui.css')}`.\n\n## Titel und Meta-Tags\n\nSetze Titel und Beschreibung im Controller oder in der View und gib sie im Layout mit `@{meta}` (oder `@{import('meta')}`) aus:\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nDer Titel erhält am Ende ` - ` und den Namen der App (`CONF.name`), außer `allow_custom_titles` ist in der Konfiguration `true`.\n\n## Kompilierung und Caching\n\nWenn eine View zum ersten Mal verwendet wird, liest Total.js sie, entfernt HTML-Kommentare, minifiziert das HTML samt Inline-CSS und -JavaScript, übersetzt `@(...)` und kompiliert sie. Im **Release**-Modus wird die kompilierte View im Speicher gehalten, einmal pro Sprache. Im **Debug**-Modus wird sie bei jeder Anfrage kompiliert, sodass deine Änderungen ohne Neustart erscheinen.\n\nSetze `@{nocompress html}` an den Anfang einer View, um ihr HTML so zu behalten, wie es geschrieben ist (`css`, `js` und `all` funktionieren ebenfalls).\n\n## Eine View in einen String rendern\n\n`VIEW(name, [model], [layout], [repository], [language])` rendert eine View an beliebiger Stelle und gibt HTML zurück, ohne Layout, außer du gibst eines an:\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Vistas","summary":"Plantillas HTML en views/: expresiones, condiciones, bucles, plantillas (layouts), vistas parciales, secciones, helpers y localización.","markdown":"---\ntitle: Vistas\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Vistas\n\n> Plantillas HTML en views/: expresiones, condiciones, bucles, plantillas (layouts), vistas parciales, secciones, helpers y localización.\n\nUna vista es un archivo HTML en `views/` con comandos en `@{...}`. Total.js la compila en una función JavaScript, la ejecuta con un modelo, envuelve el resultado en una plantilla (layout) y lo envía como respuesta.\n\n## Dónde están las vistas\n\nLas vistas son archivos `.html` en `views/`. Las nombras sin la extensión.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nUn controlador busca primero en la carpeta con su propio nombre. En `controllers/users.js`, `this.view('detail')` renderiza `views/users/detail.html`. Cuando ese archivo no existe, Total.js prueba `views/detail.html`. El controlador `default.js` usa `views/` directamente.\n\nUn prefijo cambia dónde se busca la vista:\n\n| Nombre | Archivo |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, luego `views/index.html` |\n| `~index` | `views/index.html`, siempre desde la raíz de `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | la vista de un paquete |\n| `#plugin/index` | la vista de un plugin |\n| `.path/to/file` | una ruta absoluta, sin `.html` |\n\n## Renderizar una vista\n\nLa ruta más simple tiene el nombre de una vista en lugar de una acción:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nDesde una acción, llama a `this.view()` con el nombre y un modelo:\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nSin nombre, `this.view(model)` renderiza la vista con el nombre de la última parte de la URL (`index` para `/`).\n\nUna operación de esquema puede renderizar su resultado como vista. El resultado pasa a ser el modelo:\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## El modelo y el repositorio\n\nEl modelo es el segundo argumento de `this.view()`. En la vista es `model` (o `M`):\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\nEl **repositorio** es un objeto compartido por la vista, sus vistas parciales y la plantilla durante una petición. Úsalo para pasar valores que no forman parte del modelo, como la clase de una página. Es `controller.repository` en JavaScript y `repository` (o `R`) en la vista:\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nUna vista también puede asignar valores. El comando no imprime nada:\n\n```html\n@{repository.page = 'products'}\n```\n\nOtras variables que puedes usar en una vista: `user`, `session`, `query`, `body` (cuerpo de la petición; consulta la sección de plantillas para `@{body}` solo), `config`, `language`, `url`, `controller`.\n\n## Expresiones y escape\n\n`@{expression}` imprime el valor de cualquier expresión JavaScript, **codificado como HTML**. Pon `!` delante para imprimirlo **sin procesar**:\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nCon `model.name = '<b>Peter</b>'`, `@{model.name}` imprime `&lt;b&gt;Peter&lt;/b&gt;`, y `@{!model.name}` imprime la etiqueta de negrita. `null` y `undefined` no imprimen nada.\n\nUsa la forma sin procesar solo para HTML de confianza. La salida de los helpers, de `@{json()}` y de los comandos de formulario no se vuelve a codificar.\n\nEl texto que empieza por `@{{` no es un comando; se deja en la página tal cual.\n\n## Condiciones\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nLa condición es JavaScript. Ciérrala con `@{fi}` o `@{endif}`.\n\n## Bucles\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` es la posición del elemento, desde `0`. Un array vacío no imprime nada. Cuando recorres un objeto, cada elemento tiene `key` y `value`:\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` y `@{break}` funcionan dentro del bucle, normalmente en un `@{if}`.\n\n## Plantillas (layouts)\n\nCada vista se renderiza dentro de una plantilla. La plantilla por defecto es `views/layout.html` (`default_layout` en la configuración). `@{body}` imprime la vista renderizada:\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nSi el archivo de la plantilla no existe, la petición termina con un error 500. Créalo o desactiva la plantilla.\n\nCambia la plantilla en el controlador o en la vista:\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nLa plantilla recibe el mismo modelo y el mismo repositorio que la vista.\n\n## Vistas parciales\n\n`@{view(name, [model])}` renderiza otra vista en su lugar, sin plantilla. Pasa el modelo si la vista parcial lo necesita:\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nEl nombre se resuelve como el de cualquier vista, así que `partials/product` es `views/partials/product.html` (o dentro de la carpeta del controlador). Añade una expiración y una clave para guardar la salida en caché: `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Secciones\n\nUna sección es HTML escrito en la vista e impreso en la plantilla, por ejemplo los scripts de una página:\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nVarios bloques con el mismo nombre se unen. Desde un controlador usa `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Helpers\n\nTotal.js tiene helpers de vista para el HTML habitual: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` y más. Están en la [referencia de Vistas](../../reference/views/).\n\nDefine tus propios helpers en `DEF.helpers`, normalmente en un archivo de `definitions/`. En un helper, `this` es el controlador:\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nLlámalo por su nombre:\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nLa salida de un helper no se codifica; codifica tú los valores cuando vienen de usuarios. `@{helper('price', item.price)}` hace la misma llamada.\n\nUn helper que usa una sola vista puede escribirse dentro de ella:\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Localización\n\nEl texto en `@(...)` se traduce cuando se compila la vista, con el idioma de la petición (`controller.language`, establecido por `DEF.onLocale`):\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nLa traducción viene del archivo de recursos del idioma. Cuando no hay ninguna, el texto se queda como está. `@(#key)` lee la clave `key` directamente del recurso. `@{resource('key')}` imprime una clave de `default.resource`, y `@{resource('en', 'key')}` una clave de `en.resource`.\n\n## CSS, JavaScript e imágenes\n\n`@{import()}` escribe las etiquetas para archivos estáticos. Los nombres relativos van a las carpetas estáticas (`/css/`, `/js/`, `/img/`):\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` imprime el título y las etiquetas meta, `head` las etiquetas añadidas con `@{head()}`. Une archivos con `+` para combinarlos en uno: `@{import('default.css + ui.css')}`.\n\n## Título y etiquetas meta\n\nEstablece el título y la descripción en el controlador o en la vista, e imprímelos con `@{meta}` (o `@{import('meta')}`) en la plantilla:\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nAl título se le añade ` - ` y el nombre de la app (`CONF.name`) al final, salvo que `allow_custom_titles` sea `true` en la configuración.\n\n## Compilación y caché\n\nLa primera vez que se usa una vista, Total.js la lee, elimina los comentarios HTML, minifica el HTML con su CSS y JavaScript en línea, traduce `@(...)` y la compila. En modo **release** la vista compilada se guarda en memoria, una vez por idioma. En modo **debug** se compila en cada petición, así que tus cambios aparecen sin reiniciar.\n\nPon `@{nocompress html}` al principio de una vista para conservar su HTML tal como está escrito (`css`, `js` y `all` también funcionan).\n\n## Renderizar una vista a un string\n\n`VIEW(name, [model], [layout], [repository], [language])` renderiza una vista en cualquier lugar y devuelve HTML, sin plantilla salvo que nombres una:\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Vues","summary":"Templates HTML dans views/ : expressions, conditions, boucles, layouts, vues partielles, sections, helpers et localisation.","markdown":"---\ntitle: Vues\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Vues\n\n> Templates HTML dans views/ : expressions, conditions, boucles, layouts, vues partielles, sections, helpers et localisation.\n\nUne vue est un fichier HTML de `views/` contenant des commandes dans `@{...}`. Total.js la compile en une fonction JavaScript, l'exécute avec un modèle, place le résultat dans un layout et l'envoie comme réponse.\n\n## Où se trouvent les vues\n\nLes vues sont des fichiers `.html` dans `views/`. Tu les nommes sans l'extension.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nUn contrôleur cherche d'abord dans le dossier qui porte son nom. Dans `controllers/users.js`, `this.view('detail')` rend `views/users/detail.html`. Lorsque ce fichier n'existe pas, Total.js essaie `views/detail.html`. Le contrôleur `default.js` utilise directement `views/`.\n\nUn préfixe change l'endroit où la vue est recherchée :\n\n| Nom | Fichier |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, puis `views/index.html` |\n| `~index` | `views/index.html`, toujours depuis la racine de `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | la vue d'un paquet |\n| `#plugin/index` | la vue d'un plugin |\n| `.path/to/file` | un chemin absolu, sans `.html` |\n\n## Rendre une vue\n\nLa route la plus simple contient le nom d'une vue à la place d'une action :\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nDepuis une action, appelle `this.view()` avec le nom et un modèle :\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nSans nom, `this.view(model)` rend la vue nommée d'après la dernière partie de l'URL (`index` pour `/`).\n\nUne opération de schéma peut rendre son résultat sous forme de vue. Le résultat devient le modèle :\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## Le modèle et le repository\n\nLe modèle est le deuxième argument de `this.view()`. Dans la vue, c'est `model` (ou `M`) :\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\nLe **repository** est un objet partagé par la vue, ses vues partielles et le layout pendant une requête. Utilise-le pour transmettre des valeurs qui ne font pas partie du modèle, comme une classe de page. C'est `controller.repository` en JavaScript et `repository` (ou `R`) dans la vue :\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nUne vue peut aussi affecter des valeurs. La commande n'affiche rien :\n\n```html\n@{repository.page = 'products'}\n```\n\nAutres variables utilisables dans une vue : `user`, `session`, `query`, `body` (corps de la requête ; voir la section sur les layouts pour `@{body}` seul), `config`, `language`, `url`, `controller`.\n\n## Expressions et échappement\n\n`@{expression}` affiche la valeur de n'importe quelle expression JavaScript, **encodée en HTML**. Place `!` devant pour l'afficher **brute** :\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nAvec `model.name = '<b>Peter</b>'`, `@{model.name}` affiche `&lt;b&gt;Peter&lt;/b&gt;`, et `@{!model.name}` affiche la balise en gras. `null` et `undefined` n'affichent rien.\n\nN'utilise la forme brute que pour du HTML de confiance. La sortie des helpers, de `@{json()}` et des commandes de formulaire n'est pas encodée une seconde fois.\n\nUn texte qui commence par `@{{` n'est pas une commande ; il reste tel quel dans la page.\n\n## Conditions\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nLa condition est du JavaScript. Ferme-la avec `@{fi}` ou `@{endif}`.\n\n## Boucles\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` est la position de l'élément, à partir de `0`. Un tableau vide n'affiche rien. Lorsque tu parcours un objet, chaque élément possède `key` et `value` :\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` et `@{break}` fonctionnent dans la boucle, généralement dans un `@{if}`.\n\n## Layouts\n\nChaque vue est rendue dans un layout. Le layout par défaut est `views/layout.html` (`default_layout` dans la configuration). `@{body}` affiche la vue rendue :\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nSi le fichier de layout n'existe pas, la requête se termine par une erreur 500. Crée-le, ou désactive le layout.\n\nChange le layout dans le contrôleur ou dans la vue :\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nLe layout reçoit le même modèle et le même repository que la vue.\n\n## Vues partielles\n\n`@{view(name, [model])}` rend une autre vue à cet endroit, sans layout. Passe le modèle si la vue partielle en a besoin :\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nLe nom est résolu comme pour n'importe quelle vue : `partials/product` correspond donc à `views/partials/product.html` (ou au dossier du contrôleur). Ajoute une durée d'expiration et une clé pour mettre la sortie en cache : `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Sections\n\nUne section est du HTML écrit dans la vue et affiché dans le layout, par exemple les scripts d'une page :\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nPlusieurs blocs portant le même nom sont réunis. Depuis un contrôleur, utilise `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Helpers\n\nTotal.js propose des helpers de vue pour le HTML courant : `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` et d'autres. Ils sont listés dans la [référence des Vues](../../reference/views/).\n\nDéfinis tes propres helpers dans `DEF.helpers`, généralement dans un fichier de `definitions/`. Dans un helper, `this` est le contrôleur :\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nAppelle-le par son nom :\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nLa sortie d'un helper n'est pas encodée ; encode toi-même les valeurs lorsqu'elles proviennent des utilisateurs. `@{helper('price', item.price)}` effectue le même appel.\n\nUn helper utilisé par une seule vue peut être écrit à l'intérieur de celle-ci :\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Localisation\n\nLe texte dans `@(...)` est traduit lors de la compilation de la vue, dans la langue de la requête (`controller.language`, définie par `DEF.onLocale`) :\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nLa traduction provient du fichier de ressources de la langue. Lorsqu'il n'y en a pas, le texte reste tel quel. `@(#key)` lit directement la clé `key` dans la ressource. `@{resource('key')}` affiche une clé de `default.resource`, et `@{resource('en', 'key')}` une clé de `en.resource`.\n\n## CSS, JavaScript et images\n\n`@{import()}` écrit les balises des fichiers statiques. Les noms relatifs pointent vers les dossiers statiques (`/css/`, `/js/`, `/img/`) :\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` affiche le titre et les balises meta, `head` les balises ajoutées avec `@{head()}`. Joins des fichiers avec `+` pour les fusionner en un seul : `@{import('default.css + ui.css')}`.\n\n## Titre et balises meta\n\nDéfinis le titre et la description dans le contrôleur ou dans la vue, et affiche-les avec `@{meta}` (ou `@{import('meta')}`) dans le layout :\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nLe titre reçoit ` - ` suivi du nom de l'application (`CONF.name`) à la fin, sauf si `allow_custom_titles` vaut `true` dans la configuration.\n\n## Compilation et cache\n\nLa première fois qu'une vue est utilisée, Total.js la lit, supprime les commentaires HTML, minifie le HTML avec son CSS et son JavaScript en ligne, traduit `@(...)` et la compile. En mode **release**, la vue compilée est conservée en mémoire, une fois par langue. En mode **debug**, elle est compilée à chaque requête, tes modifications apparaissent donc sans redémarrage.\n\nPlace `@{nocompress html}` en haut d'une vue pour conserver son HTML tel qu'il est écrit (`css`, `js` et `all` fonctionnent aussi).\n\n## Rendre une vue sous forme de chaîne\n\n`VIEW(name, [model], [layout], [repository], [language])` rend une vue n'importe où et renvoie du HTML, sans layout sauf si tu en nommes un :\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Viste","summary":"Template HTML in views/: espressioni, condizioni, cicli, layout, viste parziali, sezioni, helper e localizzazione.","markdown":"---\ntitle: Viste\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Viste\n\n> Template HTML in views/: espressioni, condizioni, cicli, layout, viste parziali, sezioni, helper e localizzazione.\n\nUna vista è un file HTML in `views/` con comandi in `@{...}`. Total.js la compila in una funzione JavaScript, la esegue con un modello, avvolge il risultato in un layout e lo invia come risposta.\n\n## Dove si trovano le viste\n\nLe viste sono file `.html` in `views/`. Le indichi per nome, senza estensione.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nUn controller cerca prima nella cartella con il suo stesso nome. In `controllers/users.js`, `this.view('detail')` renderizza `views/users/detail.html`. Quando quel file non esiste, Total.js prova `views/detail.html`. Il controller `default.js` usa direttamente `views/`.\n\nUn prefisso cambia il punto in cui viene cercata la vista:\n\n| Nome | File |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, poi `views/index.html` |\n| `~index` | `views/index.html`, sempre dalla radice di `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | la vista di un pacchetto |\n| `#plugin/index` | la vista di un plugin |\n| `.path/to/file` | un percorso assoluto, senza `.html` |\n\n## Renderizzare una vista\n\nLa route più semplice ha il nome di una vista al posto di un'azione:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nDa un'azione, chiama `this.view()` con il nome e un modello:\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nSenza nome, `this.view(model)` renderizza la vista che ha il nome dell'ultima parte dell'URL (`index` per `/`).\n\nUn'operazione di schema può renderizzare il suo risultato come vista. Il risultato diventa il modello:\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## Il modello e il repository\n\nIl modello è il secondo argomento di `this.view()`. Nella vista è `model` (o `M`):\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\nIl **repository** è un oggetto condiviso dalla vista, dalle sue viste parziali e dal layout durante una richiesta. Usalo per passare valori che non fanno parte del modello, come una classe della pagina. È `controller.repository` in JavaScript e `repository` (o `R`) nella vista:\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nUna vista può anche assegnare valori. Il comando non stampa nulla:\n\n```html\n@{repository.page = 'products'}\n```\n\nAltre variabili che puoi usare in una vista: `user`, `session`, `query`, `body` (il corpo della richiesta; per `@{body}` da solo vedi la sezione sui layout), `config`, `language`, `url`, `controller`.\n\n## Espressioni ed escaping\n\n`@{expression}` stampa il valore di qualsiasi espressione JavaScript, **codificato in HTML**. Metti `!` davanti per stamparlo **grezzo**:\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nCon `model.name = '<b>Peter</b>'`, `@{model.name}` stampa `&lt;b&gt;Peter&lt;/b&gt;`, e `@{!model.name}` stampa il tag in grassetto. `null` e `undefined` non stampano nulla.\n\nUsa la forma grezza solo per HTML di cui ti fidi. L'output degli helper, di `@{json()}` e dei comandi dei form non viene codificato di nuovo.\n\nIl testo che inizia con `@{{` non è un comando; resta nella pagina così com'è.\n\n## Condizioni\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nLa condizione è JavaScript. Chiudila con `@{fi}` o `@{endif}`.\n\n## Cicli\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` è la posizione dell'elemento, a partire da `0`. Un array vuoto non stampa nulla. Quando cicli su un oggetto, ogni elemento ha `key` e `value`:\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` e `@{break}` funzionano dentro il ciclo, di solito in un `@{if}`.\n\n## Layout\n\nOgni vista viene renderizzata dentro un layout. Il layout predefinito è `views/layout.html` (`default_layout` nella configurazione). `@{body}` stampa la vista renderizzata:\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nSe il file del layout non esiste, la richiesta termina con un errore 500. Crealo, oppure disattiva il layout.\n\nCambia il layout nel controller o nella vista:\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nIl layout riceve lo stesso modello e lo stesso repository della vista.\n\n## Viste parziali\n\n`@{view(name, [model])}` renderizza un'altra vista sul posto, senza layout. Passa il modello se la vista parziale ne ha bisogno:\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nIl nome si risolve come per qualsiasi vista, quindi `partials/product` è `views/partials/product.html` (o dentro la cartella del controller). Aggiungi una scadenza e una chiave per mettere in cache l'output: `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Sezioni\n\nUna sezione è HTML scritto nella vista e stampato nel layout, per esempio gli script di una pagina:\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nPiù blocchi con lo stesso nome vengono uniti. Da un controller usa `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Helper\n\nTotal.js ha helper di vista per l'HTML più comune: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` e altri. Sono elencati nel [riferimento delle viste](../../reference/views/).\n\nDefinisci i tuoi helper in `DEF.helpers`, di solito in un file in `definitions/`. In un helper `this` è il controller:\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nChiamalo per nome:\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nL'output di un helper non viene codificato; codifica tu i valori quando provengono dagli utenti. `@{helper('price', item.price)}` fa la stessa chiamata.\n\nUn helper usato da una sola vista può essere scritto al suo interno:\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Localizzazione\n\nIl testo in `@(...)` viene tradotto quando la vista viene compilata, con la lingua della richiesta (`controller.language`, impostata da `DEF.onLocale`):\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nLa traduzione proviene dal file di risorse della lingua. Quando non c'è, il testo resta com'è. `@(#key)` legge direttamente la chiave `key` dalla risorsa. `@{resource('key')}` stampa una chiave di `default.resource`, e `@{resource('en', 'key')}` una chiave di `en.resource`.\n\n## CSS, JavaScript e immagini\n\n`@{import()}` scrive i tag per i file statici. I nomi relativi puntano alle cartelle statiche (`/css/`, `/js/`, `/img/`):\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` stampa il titolo e i meta tag, `head` i tag aggiunti con `@{head()}`. Unisci i file con `+` per fonderli in uno solo: `@{import('default.css + ui.css')}`.\n\n## Titolo e meta tag\n\nImposta il titolo e la descrizione nel controller o nella vista, e stampali con `@{meta}` (o `@{import('meta')}`) nel layout:\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nAl titolo vengono aggiunti alla fine ` - ` e il nome dell'app (`CONF.name`), a meno che `allow_custom_titles` sia `true` nella configurazione.\n\n## Compilazione e cache\n\nLa prima volta che una vista viene usata, Total.js la legge, rimuove i commenti HTML, minifica l'HTML insieme al CSS e al JavaScript inline, traduce `@(...)` e la compila. In modalità **release** la vista compilata resta in memoria, una volta per lingua. In modalità **debug** viene compilata a ogni richiesta, quindi le tue modifiche appaiono senza riavviare.\n\nMetti `@{nocompress html}` all'inizio di una vista per mantenere il suo HTML così come è scritto (funzionano anche `css`, `js` e `all`).\n\n## Renderizzare una vista in una stringa\n\n`VIEW(name, [model], [layout], [repository], [language])` renderizza una vista ovunque e restituisce HTML, senza layout a meno che tu non ne indichi uno:\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBk4VU60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/views/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Views","summary":"HTML šablóny vo views/: výrazy, podmienky, cykly, layouty, čiastkové views, sekcie, pomocné funkcie a lokalizácia.","markdown":"---\ntitle: Views\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Views\n\n> HTML šablóny vo views/: výrazy, podmienky, cykly, layouty, čiastkové views, sekcie, pomocné funkcie a lokalizácia.\n\nView je HTML súbor vo `views/` s príkazmi v `@{...}`. Total.js ho skompiluje do JavaScriptovej funkcie, spustí ju s modelom, obalí výsledok layoutom a pošle ho ako odpoveď.\n\n## Kde sú views uložené\n\nViews sú súbory `.html` vo `views/`. Pomenúvaš ich bez prípony.\n\n```text\nviews/\n\tlayout.html\n\tindex.html\n\tcontact.html\n\tusers/\n\t\tindex.html\n\t\tdetail.html\n```\n\nKontrolér hľadá najprv v priečinku s vlastným názvom. V `controllers/users.js` vykreslí `this.view('detail')` súbor `views/users/detail.html`. Keď tento súbor neexistuje, Total.js skúsi `views/detail.html`. Kontrolér `default.js` používa priamo `views/`.\n\nPrefix mení, kde sa view hľadá:\n\n| Názov | Súbor |\n| --- | --- |\n| `index` | `views/<controller>/index.html`, potom `views/index.html` |\n| `~index` | `views/index.html`, vždy z koreňa `views/` |\n| `=admin/index` | `themes/admin/views/index.html` |\n| `@index` | view balíka |\n| `#plugin/index` | view pluginu |\n| `.path/to/file` | absolútna cesta, bez `.html` |\n\n## Vykreslenie view\n\nNajjednoduchšia trasa má namiesto akcie názov view:\n\n```js\nexports.install = function() {\n\tROUTE('GET /', 'index');\n\tROUTE('GET /contact/', 'contact');\n};\n```\n\nZ akcie zavolaj `this.view()` s názvom a modelom:\n\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tvar model = { name: 'Shop', items: [{ name: 'Apple', price: 1.2 }, { name: 'Pear', price: 0.9 }] };\n\tthis.view('products', model);\n}\n```\n\nBez názvu vykreslí `this.view(model)` view pomenované podľa poslednej časti URL (`index` pre `/`).\n\nOperácia schémy môže svoj výsledok vykresliť ako view. Výsledok sa stane modelom:\n\n```js\nROUTE('GET /products/ *Products --> list', 'products');\n```\n\n## Model a repository\n\nModel je druhý argument `this.view()`. Vo view je to `model` (alebo `M`):\n\n```html\n<h1>@{model.name}</h1>\n<p>@{model.items.length} products</p>\n```\n\n**Repository** je objekt zdieľaný počas jednej požiadavky medzi view, jeho čiastkovými views a layoutom. Používaj ho na odovzdanie hodnôt, ktoré nie sú súčasťou modelu, napríklad triedy stránky. V JavaScripte je to `controller.repository` a vo view `repository` (alebo `R`):\n\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products', model);\n}\n```\n\n```html\n<body class=\"@{repository.page}\">\n```\n\nView môže hodnoty aj priraďovať. Príkaz nič nevypíše:\n\n```html\n@{repository.page = 'products'}\n```\n\nĎalšie premenné, ktoré môžeš vo view použiť: `user`, `session`, `query`, `body` (telo požiadavky, samotné `@{body}` pozri v sekcii o layoutoch), `config`, `language`, `url`, `controller`.\n\n## Výrazy a escapovanie\n\n`@{expression}` vypíše hodnotu ľubovoľného JavaScriptového výrazu, **zakódovanú pre HTML**. Pridaj pred ňu `!`, ak ju chceš vypísať **surovú**:\n\n```html\n<p>@{model.name}</p>\n<p>@{model.price.format(2)}</p>\n<div>@{!model.html}</div>\n```\n\nPri `model.name = '<b>Peter</b>'` vypíše `@{model.name}` text `&lt;b&gt;Peter&lt;/b&gt;` a `@{!model.name}` vypíše tučnú značku. `null` a `undefined` nevypíšu nič.\n\nSurovú formu používaj len pre HTML, ktorému dôveruješ. Výstup pomocných funkcií, `@{json()}` a formulárových príkazov sa znova nekóduje.\n\nText, ktorý začína na `@{{`, nie je príkaz; zostane na stránke tak, ako je.\n\n## Podmienky\n\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\nPodmienka je JavaScript. Uzavri ju pomocou `@{fi}` alebo `@{endif}`.\n\n## Cykly\n\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}: @{item.price}</li>\n\t@{end}\n</ul>\n```\n\n`index` je pozícia položky, od `0`. Prázdne pole nevypíše nič. Keď prechádzaš objekt, každá položka má `key` a `value`:\n\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\n`@{continue}` a `@{break}` fungujú vnútri cyklu, zvyčajne v `@{if}`.\n\n## Layouty\n\nKaždé view sa vykresľuje vnútri layoutu. Predvolený layout je `views/layout.html` (`default_layout` v konfigurácii). `@{body}` vypíše vykreslené view:\n\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\nAk súbor layoutu neexistuje, požiadavka skončí chybou 500. Vytvor ho alebo layout vypni.\n\nLayout zmeníš v kontroléri alebo vo view:\n\n```js\nfunction admin() {\n\tthis.layout('admin');     // views/admin.html\n\tthis.view('dashboard');\n}\n\nfunction plain() {\n\tthis.layout('');          // no layout\n\tthis.view('plain');\n}\n```\n\n```html\n@{layout('admin')}\n```\n\nLayout dostane rovnaký model a repository ako view.\n\n## Čiastkové views\n\n`@{view(name, [model])}` vykreslí na mieste iné view, bez layoutu. Ak čiastkové view potrebuje model, odovzdaj ho:\n\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nNázov sa rieši ako pri každom view, takže `partials/product` je `views/partials/product.html` (alebo v priečinku kontroléra). Pridaj expiráciu a kľúč, ak chceš výstup uložiť do cache: `@{view('menu', model, '5 minutes', 'menu')}`.\n\n## Sekcie\n\nSekcia je HTML napísané vo view a vypísané v layoute, napríklad skripty jednej stránky:\n\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\n```html\n\t@{body}\n\t@{section('scripts')}\n</body>\n```\n\nViac blokov s rovnakým názvom sa spojí. Z kontroléra použi `this.section('scripts', '<script src=\"/js/chart.js\"></script>')`.\n\n## Pomocné funkcie\n\nTotal.js má pomocné funkcie pre views na bežné HTML: `@{import()}`, `@{options()}`, `@{checked()}`, `@{text()}`, `@{json()}` a ďalšie. Sú uvedené v [referencii Views](../../reference/views/).\n\nVlastné pomocné funkcie definuj v `DEF.helpers`, zvyčajne v súbore v `definitions/`. V pomocnej funkcii je `this` kontrolér:\n\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n```\n\nZavolaj ju jej názvom:\n\n```html\n<span>@{price(item.price, 'USD')}</span>\n```\n\nVýstup pomocnej funkcie sa nekóduje; hodnoty od používateľov si zakóduj sám. `@{helper('price', item.price)}` urobí rovnaké volanie.\n\nPomocnú funkciu, ktorú používa len jedno view, môžeš napísať priamo v ňom:\n\n```html\n@{helper badge(text)}\n\t<span class=\"badge\">@{text}</span>\n@{end}\n\n@{badge('New')}\n```\n\n## Lokalizácia\n\nText v `@(...)` sa preloží pri kompilácii view, v jazyku požiadavky (`controller.language`, nastavený cez `DEF.onLocale`):\n\n```html\n<h1>@(Products)</h1>\n<button>@(Add to cart)</button>\n```\n\nPreklad pochádza zo súboru zdrojov daného jazyka. Keď preklad neexistuje, text zostane tak, ako je. `@(#key)` prečíta kľúč `key` priamo zo zdroja. `@{resource('key')}` vypíše kľúč z `default.resource` a `@{resource('en', 'key')}` kľúč z `en.resource`.\n\n## CSS, JavaScript a obrázky\n\n`@{import()}` zapíše značky pre statické súbory. Relatívne názvy smerujú do statických priečinkov (`/css/`, `/js/`, `/img/`):\n\n```html\n@{import('meta', 'head', 'default.css', 'ui.css', 'default.js', 'favicon.ico')}\n```\n\n`meta` vypíše titulok a meta značky, `head` značky pridané pomocou `@{head()}`. Spoj súbory pomocou `+`, ak ich chceš zlúčiť do jedného: `@{import('default.css + ui.css')}`.\n\n## Titulok a meta značky\n\nNastav titulok a popis v kontroléri alebo vo view a vypíš ich v layoute pomocou `@{meta}` (alebo `@{import('meta')}`):\n\n```js\nfunction detail() {\n\tthis.title('Apple');\n\tthis.description('Fresh apples from our farm');\n\tthis.view('detail', model);\n}\n```\n\n```html\n@{title(model.name)}\n@{description(model.summary)}\n```\n\nTitulok dostane na koniec ` - ` a názov aplikácie (`CONF.name`), pokiaľ v konfigurácii nie je `allow_custom_titles` nastavené na `true`.\n\n## Kompilácia a cache\n\nPri prvom použití view ho Total.js prečíta, odstráni HTML komentáre, minifikuje HTML aj s vloženým CSS a JavaScriptom, preloží `@(...)` a skompiluje ho. V režime **release** sa skompilované view drží v pamäti, raz pre každý jazyk. V režime **debug** sa kompiluje pri každej požiadavke, takže tvoje zmeny sa prejavia bez reštartu.\n\nDaj `@{nocompress html}` na začiatok view, ak chceš ponechať jeho HTML tak, ako je napísané (funguje aj `css`, `js` a `all`).\n\n## Vykreslenie view do reťazca\n\n`VIEW(name, [model], [layout], [repository], [language])` vykreslí view kdekoľvek a vráti HTML, bez layoutu, pokiaľ nejaký neuvedieš:\n\n```js\nvar html = VIEW('emails/order', order);\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Configuration","summary":"How Total.js loads the config files and .env files, how values are parsed, and how to read and change them through CONF.","markdown":"---\ntitle: Configuration\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuration\n\n> How Total.js loads the config files and .env files, how values are parsed, and how to read and change them through CONF.\n\nTotal.js reads the configuration of an application from plain text files in its root directory. Every value ends up in the global object `CONF`, which you can read from any file of the application.\n\n## The config files\n\nTotal.js loads up to two files when the application starts:\n\n| File | When |\n| --- | --- |\n| `config` | always |\n| `config-debug` | only in debug mode |\n| `config-release` | only in release mode |\n\nThe mode-specific file is read after `config`, so its values replace the values from `config`. Keep the common settings in `config` and put only the differences in `config-debug` or `config-release`.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nBefore the config files, Total.js loads the `.env` files (see below). In debug mode the watcher restarts the application when you save one of the config files.\n\n## Syntax\n\nEach line is `key : value`. Total.js splits the line at the first `:`, so a value can contain more colons, for example a URL. Spaces around the key and the value are removed.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nRules:\n\n- Empty lines are skipped.\n- A line that starts with `#` or `//` is a comment. Do not put comments at the end of a line, they become part of the value.\n- A line without `:` is skipped.\n- The keys `debug` and `resources` are ignored in the file.\n\n## How values are parsed\n\nWithout a type, Total.js guesses the type from the value:\n\n| Value | Result |\n| --- | --- |\n| `8000` | the number `8000` |\n| `0.5` | the number `0.5` |\n| `true`, `false` | a boolean |\n| `0042` | the string `\"0042\"` (a leading zero keeps the string) |\n| `1,5` | the string `\"1,5\"` |\n| `-1` | the string `\"-1\"` |\n| anything else | a string |\n\nMany built-in keys have a fixed type. Keys like `default_request_timeout` or `default_request_maxlength` are always parsed as integers, and keys like `allow_gzip` or `allow_compile` are booleans: `true`, `1` and `on` mean `true`, everything else means `false`. `version`, `secret`, `secret_uid` and `secret_encryption` always stay strings.\n\n## Typed values\n\nPut the type in brackets after the key to control the parsing:\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Type | Result |\n| --- | --- |\n| `string` | the raw text |\n| `number`, `float`, `double`, `currency` | a number |\n| `boolean`, `bool` | `true` when the value contains `true`, `on`, `1` or `enabled` |\n| `array` | a list split by commas, trimmed |\n| `json` | parsed JSON |\n| `object`, `eval` | a JavaScript expression, evaluated |\n| `date`, `datetime`, `time` | a `Date` |\n| `env`, `environment` | the value of the environment variable with that name |\n| `random` | a new random string of the given length (default 10) on every start |\n| `generate`, `hash` | a random string that is created once and kept |\n\nValues for `generate` and `hash` are stored in `databases/config.json`, so they stay the same after a restart. Use them for secrets that must not change, but that you do not want to write into the file.\n\nA value that starts with `base64 ` or `hex ` is decoded first:\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Environment variables\n\nNext to the config files you can keep `.env` files with `KEY=value` lines. Total.js loads `.env` and then `.env-debug` or `.env-release`. A variable that already exists in `process.env` is never replaced, so the real environment wins.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nQuotes around a value are removed and `\\n` becomes a new line. Lines starting with `#` or `//` are comments.\n\nRead a variable in the config with the `(env)` type:\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nIn code you can also use `process.env` directly.\n\n## Reading the configuration\n\n`CONF` is a plain object. Read keys as properties:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nKeys with a dot or other characters need the bracket notation, for example `CONF['security.txt']`. In views, `CONF` is available too: `@{CONF.name}`.\n\nYou can assign a value in code, but the change is not written to the files and some keys are only read once at start (`default_port`, `directory_*`, `default_timezone`):\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Changing the configuration at runtime\n\n`LOADCONFIG()` merges new values into `CONF`. It accepts an object, a string in the config syntax or an array of `{ id, type, value }` items, which is handy when the settings are stored in a database:\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Options of the start script\n\nThe start script can pass values with `options.config`. They are applied before the config files are read, so a key in `config` replaces them:\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Threads\n\nAn application started with threads loads `/threads/<name>/.env`, `/threads/<name>/config` and the mode-specific files of that folder after the files of the root.\n\n## Common keys\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nThe reference lists every key with its default value.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Konfiguration","summary":"Wie Total.js die Konfigurationsdateien und .env-Dateien lädt, wie Werte geparst werden und wie du sie über CONF liest und änderst.","markdown":"---\ntitle: Konfiguration\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Konfiguration\n\n> Wie Total.js die Konfigurationsdateien und .env-Dateien lädt, wie Werte geparst werden und wie du sie über CONF liest und änderst.\n\nTotal.js liest die Konfiguration einer Anwendung aus Textdateien in ihrem Stammverzeichnis. Jeder Wert landet im globalen Objekt `CONF`, das du aus jeder Datei der Anwendung lesen kannst.\n\n## Die Konfigurationsdateien\n\nTotal.js lädt beim Start der Anwendung bis zu zwei Dateien:\n\n| Datei | Wann |\n| --- | --- |\n| `config` | immer |\n| `config-debug` | nur im Debug-Modus |\n| `config-release` | nur im Release-Modus |\n\nDie modusspezifische Datei wird nach `config` gelesen, ihre Werte ersetzen also die Werte aus `config`. Lege die gemeinsamen Einstellungen in `config` ab und schreibe nur die Unterschiede in `config-debug` oder `config-release`.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nVor den Konfigurationsdateien lädt Total.js die `.env`-Dateien (siehe unten). Im Debug-Modus startet der Watcher die Anwendung neu, wenn du eine der Konfigurationsdateien speicherst.\n\n## Syntax\n\nJede Zeile ist `key : value`. Total.js teilt die Zeile am ersten `:`, ein Wert kann also weitere Doppelpunkte enthalten, zum Beispiel eine URL. Leerzeichen um den Schlüssel und den Wert werden entfernt.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nRegeln:\n\n- Leere Zeilen werden übersprungen.\n- Eine Zeile, die mit `#` oder `//` beginnt, ist ein Kommentar. Setze keine Kommentare ans Zeilenende, sie werden Teil des Wertes.\n- Eine Zeile ohne `:` wird übersprungen.\n- Die Schlüssel `debug` und `resources` werden in der Datei ignoriert.\n\n## Wie Werte geparst werden\n\nOhne Typ errät Total.js den Typ aus dem Wert:\n\n| Wert | Ergebnis |\n| --- | --- |\n| `8000` | die Zahl `8000` |\n| `0.5` | die Zahl `0.5` |\n| `true`, `false` | ein Boolean |\n| `0042` | der String `\"0042\"` (eine führende Null behält den String) |\n| `1,5` | der String `\"1,5\"` |\n| `-1` | der String `\"-1\"` |\n| alles andere | ein String |\n\nViele eingebaute Schlüssel haben einen festen Typ. Schlüssel wie `default_request_timeout` oder `default_request_maxlength` werden immer als Ganzzahlen geparst, und Schlüssel wie `allow_gzip` oder `allow_compile` sind Booleans: `true`, `1` und `on` bedeuten `true`, alles andere bedeutet `false`. `version`, `secret`, `secret_uid` und `secret_encryption` bleiben immer Strings.\n\n## Typisierte Werte\n\nSetze den Typ in Klammern hinter den Schlüssel, um das Parsen zu steuern:\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Typ | Ergebnis |\n| --- | --- |\n| `string` | der unveränderte Text |\n| `number`, `float`, `double`, `currency` | eine Zahl |\n| `boolean`, `bool` | `true`, wenn der Wert `true`, `on`, `1` oder `enabled` enthält |\n| `array` | eine an Kommas getrennte Liste, getrimmt |\n| `json` | geparstes JSON |\n| `object`, `eval` | ein JavaScript-Ausdruck, ausgewertet |\n| `date`, `datetime`, `time` | ein `Date` |\n| `env`, `environment` | der Wert der Umgebungsvariablen mit diesem Namen |\n| `random` | bei jedem Start ein neuer zufälliger String der angegebenen Länge (Standard 10) |\n| `generate`, `hash` | ein zufälliger String, der einmal erzeugt und behalten wird |\n\nWerte für `generate` und `hash` werden in `databases/config.json` gespeichert, sie bleiben also nach einem Neustart gleich. Verwende sie für Secrets, die sich nicht ändern dürfen, die du aber nicht in die Datei schreiben willst.\n\nEin Wert, der mit `base64 ` oder `hex ` beginnt, wird zuerst dekodiert:\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Umgebungsvariablen\n\nNeben den Konfigurationsdateien kannst du `.env`-Dateien mit `KEY=value`-Zeilen anlegen. Total.js lädt `.env` und dann `.env-debug` oder `.env-release`. Eine Variable, die bereits in `process.env` existiert, wird nie ersetzt, die echte Umgebung hat also Vorrang.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nAnführungszeichen um einen Wert werden entfernt und `\\n` wird zu einem Zeilenumbruch. Zeilen, die mit `#` oder `//` beginnen, sind Kommentare.\n\nLies eine Variable in der Konfiguration mit dem Typ `(env)`:\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nIm Code kannst du auch direkt `process.env` verwenden.\n\n## Die Konfiguration lesen\n\n`CONF` ist ein einfaches Objekt. Lies Schlüssel als Eigenschaften:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nSchlüssel mit einem Punkt oder anderen Zeichen brauchen die Klammernotation, zum Beispiel `CONF['security.txt']`. In Views ist `CONF` ebenfalls verfügbar: `@{CONF.name}`.\n\nDu kannst im Code einen Wert zuweisen, aber die Änderung wird nicht in die Dateien geschrieben, und manche Schlüssel werden nur einmal beim Start gelesen (`default_port`, `directory_*`, `default_timezone`):\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Die Konfiguration zur Laufzeit ändern\n\n`LOADCONFIG()` führt neue Werte in `CONF` zusammen. Es akzeptiert ein Objekt, einen String in der Konfigurationssyntax oder ein Array aus `{ id, type, value }`-Einträgen, was praktisch ist, wenn die Einstellungen in einer Datenbank gespeichert sind:\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Optionen des Startskripts\n\nDas Startskript kann Werte mit `options.config` übergeben. Sie werden angewendet, bevor die Konfigurationsdateien gelesen werden, ein Schlüssel in `config` ersetzt sie also:\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Threads\n\nEine mit Threads gestartete Anwendung lädt `/threads/<name>/.env`, `/threads/<name>/config` und die modusspezifischen Dateien dieses Ordners nach den Dateien des Stammverzeichnisses.\n\n## Häufige Schlüssel\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nDie Referenz listet jeden Schlüssel mit seinem Standardwert auf.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Configuración","summary":"Cómo carga Total.js los archivos de configuración y los archivos .env, cómo se parsean los valores y cómo leerlos y cambiarlos a través de CONF.","markdown":"---\ntitle: \"Configuración\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuración\n\n> Cómo carga Total.js los archivos de configuración y los archivos .env, cómo se parsean los valores y cómo leerlos y cambiarlos a través de CONF.\n\nTotal.js lee la configuración de una aplicación desde archivos de texto plano en su directorio raíz. Todos los valores acaban en el objeto global `CONF`, que puedes leer desde cualquier archivo de la aplicación.\n\n## Los archivos de configuración\n\nTotal.js carga hasta dos archivos cuando arranca la aplicación:\n\n| Archivo | Cuándo |\n| --- | --- |\n| `config` | siempre |\n| `config-debug` | solo en modo debug |\n| `config-release` | solo en modo release |\n\nEl archivo específico del modo se lee después de `config`, así que sus valores reemplazan a los de `config`. Mantén los ajustes comunes en `config` y pon solo las diferencias en `config-debug` o `config-release`.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nAntes de los archivos de configuración, Total.js carga los archivos `.env` (ver más abajo). En modo debug, el watcher reinicia la aplicación cuando guardas uno de los archivos de configuración.\n\n## Sintaxis\n\nCada línea es `key : value`. Total.js divide la línea en el primer `:`, así que un valor puede contener más dos puntos, por ejemplo una URL. Los espacios alrededor de la clave y del valor se eliminan.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nReglas:\n\n- Las líneas vacías se omiten.\n- Una línea que empieza por `#` o `//` es un comentario. No pongas comentarios al final de una línea: pasan a formar parte del valor.\n- Una línea sin `:` se omite.\n- Las claves `debug` y `resources` se ignoran en el archivo.\n\n## Cómo se parsean los valores\n\nSin tipo, Total.js deduce el tipo a partir del valor:\n\n| Valor | Resultado |\n| --- | --- |\n| `8000` | el número `8000` |\n| `0.5` | el número `0.5` |\n| `true`, `false` | un booleano |\n| `0042` | la cadena `\"0042\"` (un cero inicial conserva la cadena) |\n| `1,5` | la cadena `\"1,5\"` |\n| `-1` | la cadena `\"-1\"` |\n| cualquier otra cosa | una cadena |\n\nMuchas claves integradas tienen un tipo fijo. Claves como `default_request_timeout` o `default_request_maxlength` siempre se parsean como enteros, y claves como `allow_gzip` o `allow_compile` son booleanos: `true`, `1` y `on` significan `true`, todo lo demás significa `false`. `version`, `secret`, `secret_uid` y `secret_encryption` siempre se quedan como cadenas.\n\n## Valores con tipo\n\nPon el tipo entre paréntesis después de la clave para controlar el parseo:\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Tipo | Resultado |\n| --- | --- |\n| `string` | el texto sin procesar |\n| `number`, `float`, `double`, `currency` | un número |\n| `boolean`, `bool` | `true` cuando el valor contiene `true`, `on`, `1` o `enabled` |\n| `array` | una lista separada por comas, sin espacios sobrantes |\n| `json` | JSON parseado |\n| `object`, `eval` | una expresión JavaScript, evaluada |\n| `date`, `datetime`, `time` | un `Date` |\n| `env`, `environment` | el valor de la variable de entorno con ese nombre |\n| `random` | una nueva cadena aleatoria de la longitud indicada (por defecto 10) en cada arranque |\n| `generate`, `hash` | una cadena aleatoria que se crea una vez y se conserva |\n\nLos valores de `generate` y `hash` se guardan en `databases/config.json`, así que se mantienen iguales tras un reinicio. Úsalos para secretos que no deben cambiar, pero que no quieres escribir en el archivo.\n\nUn valor que empieza por `base64 ` o `hex ` se decodifica primero:\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Variables de entorno\n\nJunto a los archivos de configuración puedes tener archivos `.env` con líneas `KEY=value`. Total.js carga `.env` y luego `.env-debug` o `.env-release`. Una variable que ya existe en `process.env` nunca se reemplaza, así que el entorno real tiene prioridad.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nLas comillas alrededor de un valor se eliminan y `\\n` se convierte en un salto de línea. Las líneas que empiezan por `#` o `//` son comentarios.\n\nLee una variable en la configuración con el tipo `(env)`:\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nEn el código también puedes usar `process.env` directamente.\n\n## Leer la configuración\n\n`CONF` es un objeto plano. Lee las claves como propiedades:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nLas claves con un punto u otros caracteres necesitan la notación de corchetes, por ejemplo `CONF['security.txt']`. En las vistas, `CONF` también está disponible: `@{CONF.name}`.\n\nPuedes asignar un valor en el código, pero el cambio no se escribe en los archivos y algunas claves solo se leen una vez al arrancar (`default_port`, `directory_*`, `default_timezone`):\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Cambiar la configuración en tiempo de ejecución\n\n`LOADCONFIG()` combina valores nuevos en `CONF`. Acepta un objeto, una cadena con la sintaxis de configuración o un array de elementos `{ id, type, value }`, lo que resulta práctico cuando los ajustes se guardan en una base de datos:\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Opciones del script de arranque\n\nEl script de arranque puede pasar valores con `options.config`. Se aplican antes de leer los archivos de configuración, así que una clave en `config` los reemplaza:\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Hilos\n\nUna aplicación arrancada con hilos carga `/threads/<name>/.env`, `/threads/<name>/config` y los archivos específicos del modo de esa carpeta después de los archivos de la raíz.\n\n## Claves comunes\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nLa referencia lista cada clave con su valor por defecto.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Configuration","summary":"Comment Total.js charge les fichiers de configuration et les fichiers .env, comment les valeurs sont analysées, et comment les lire et les modifier via CONF.","markdown":"---\ntitle: Configuration\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuration\n\n> Comment Total.js charge les fichiers de configuration et les fichiers .env, comment les valeurs sont analysées, et comment les lire et les modifier via CONF.\n\nTotal.js lit la configuration d'une application à partir de simples fichiers texte situés dans son répertoire racine. Chaque valeur aboutit dans l'objet global `CONF`, que tu peux lire depuis n'importe quel fichier de l'application.\n\n## Les fichiers de configuration\n\nTotal.js charge jusqu'à deux fichiers au démarrage de l'application :\n\n| Fichier | Quand |\n| --- | --- |\n| `config` | toujours |\n| `config-debug` | uniquement en mode debug |\n| `config-release` | uniquement en mode release |\n\nLe fichier propre au mode est lu après `config` : ses valeurs remplacent donc celles de `config`. Garde les réglages communs dans `config` et ne place que les différences dans `config-debug` ou `config-release`.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nAvant les fichiers de configuration, Total.js charge les fichiers `.env` (voir ci-dessous). En mode debug, le watcher redémarre l'application lorsque tu enregistres l'un des fichiers de configuration.\n\n## Syntaxe\n\nChaque ligne est de la forme `key : value`. Total.js coupe la ligne au premier `:` : une valeur peut donc contenir d'autres deux-points, par exemple une URL. Les espaces autour de la clé et de la valeur sont supprimés.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nRègles :\n\n- Les lignes vides sont ignorées.\n- Une ligne qui commence par `#` ou `//` est un commentaire. Ne place pas de commentaires en fin de ligne : ils feraient partie de la valeur.\n- Une ligne sans `:` est ignorée.\n- Les clés `debug` et `resources` sont ignorées dans le fichier.\n\n## Analyse des valeurs\n\nSans type, Total.js devine le type à partir de la valeur :\n\n| Valeur | Résultat |\n| --- | --- |\n| `8000` | le nombre `8000` |\n| `0.5` | le nombre `0.5` |\n| `true`, `false` | un booléen |\n| `0042` | la chaîne `\"0042\"` (un zéro initial conserve la chaîne) |\n| `1,5` | la chaîne `\"1,5\"` |\n| `-1` | la chaîne `\"-1\"` |\n| tout le reste | une chaîne |\n\nDe nombreuses clés intégrées ont un type fixe. Des clés comme `default_request_timeout` ou `default_request_maxlength` sont toujours analysées comme des entiers, et des clés comme `allow_gzip` ou `allow_compile` sont des booléens : `true`, `1` et `on` signifient `true`, tout le reste signifie `false`. `version`, `secret`, `secret_uid` et `secret_encryption` restent toujours des chaînes.\n\n## Valeurs typées\n\nPlace le type entre parenthèses après la clé pour contrôler l'analyse :\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Type | Résultat |\n| --- | --- |\n| `string` | le texte brut |\n| `number`, `float`, `double`, `currency` | un nombre |\n| `boolean`, `bool` | `true` lorsque la valeur contient `true`, `on`, `1` ou `enabled` |\n| `array` | une liste découpée par des virgules, sans espaces superflus |\n| `json` | du JSON analysé |\n| `object`, `eval` | une expression JavaScript, évaluée |\n| `date`, `datetime`, `time` | une `Date` |\n| `env`, `environment` | la valeur de la variable d'environnement portant ce nom |\n| `random` | une nouvelle chaîne aléatoire de la longueur indiquée (10 par défaut) à chaque démarrage |\n| `generate`, `hash` | une chaîne aléatoire créée une seule fois puis conservée |\n\nLes valeurs de `generate` et `hash` sont stockées dans `databases/config.json` : elles restent donc identiques après un redémarrage. Utilise-les pour des secrets qui ne doivent pas changer, mais que tu ne veux pas écrire dans le fichier.\n\nUne valeur qui commence par `base64 ` ou `hex ` est d'abord décodée :\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Variables d'environnement\n\nÀ côté des fichiers de configuration, tu peux conserver des fichiers `.env` avec des lignes `KEY=value`. Total.js charge `.env`, puis `.env-debug` ou `.env-release`. Une variable qui existe déjà dans `process.env` n'est jamais remplacée : c'est donc l'environnement réel qui l'emporte.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nLes guillemets autour d'une valeur sont supprimés et `\\n` devient un saut de ligne. Les lignes qui commencent par `#` ou `//` sont des commentaires.\n\nLis une variable dans la configuration avec le type `(env)` :\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nDans le code, tu peux aussi utiliser directement `process.env`.\n\n## Lire la configuration\n\n`CONF` est un objet simple. Lis les clés comme des propriétés :\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nLes clés contenant un point ou d'autres caractères nécessitent la notation entre crochets, par exemple `CONF['security.txt']`. Dans les vues, `CONF` est également disponible : `@{CONF.name}`.\n\nTu peux affecter une valeur dans le code, mais la modification n'est pas écrite dans les fichiers et certaines clés ne sont lues qu'une fois au démarrage (`default_port`, `directory_*`, `default_timezone`) :\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Modifier la configuration à l'exécution\n\n`LOADCONFIG()` fusionne de nouvelles valeurs dans `CONF`. Elle accepte un objet, une chaîne dans la syntaxe de configuration ou un tableau d'éléments `{ id, type, value }`, ce qui est pratique lorsque les réglages sont stockés dans une base de données :\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Options du script de démarrage\n\nLe script de démarrage peut passer des valeurs avec `options.config`. Elles sont appliquées avant la lecture des fichiers de configuration : une clé de `config` les remplace donc :\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Threads\n\nUne application démarrée avec des threads charge `/threads/<name>/.env`, `/threads/<name>/config` et les fichiers propres au mode de ce dossier, après les fichiers de la racine.\n\n## Clés courantes\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nLa référence liste chaque clé avec sa valeur par défaut.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Configurazione","summary":"Come Total.js carica i file di configurazione e i file .env, come vengono analizzati i valori e come leggerli e modificarli tramite CONF.","markdown":"---\ntitle: Configurazione\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configurazione\n\n> Come Total.js carica i file di configurazione e i file .env, come vengono analizzati i valori e come leggerli e modificarli tramite CONF.\n\nTotal.js legge la configurazione di un'applicazione da file di testo semplice nella sua directory radice. Ogni valore finisce nell'oggetto globale `CONF`, che puoi leggere da qualsiasi file dell'applicazione.\n\n## I file di configurazione\n\nTotal.js carica fino a due file all'avvio dell'applicazione:\n\n| File | Quando |\n| --- | --- |\n| `config` | sempre |\n| `config-debug` | solo in modalità debug |\n| `config-release` | solo in modalità release |\n\nIl file specifico della modalità viene letto dopo `config`, quindi i suoi valori sostituiscono quelli di `config`. Tieni le impostazioni comuni in `config` e metti solo le differenze in `config-debug` o `config-release`.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nPrima dei file di configurazione, Total.js carica i file `.env` (vedi sotto). In modalità debug il watcher riavvia l'applicazione quando salvi uno dei file di configurazione.\n\n## Sintassi\n\nOgni riga è `key : value`. Total.js divide la riga al primo `:`, quindi un valore può contenere altri due punti, per esempio un URL. Gli spazi intorno alla chiave e al valore vengono rimossi.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nRegole:\n\n- Le righe vuote vengono saltate.\n- Una riga che inizia con `#` o `//` è un commento. Non mettere commenti alla fine di una riga, diventano parte del valore.\n- Una riga senza `:` viene saltata.\n- Le chiavi `debug` e `resources` vengono ignorate nel file.\n\n## Come vengono analizzati i valori\n\nSenza un tipo, Total.js deduce il tipo dal valore:\n\n| Valore | Risultato |\n| --- | --- |\n| `8000` | il numero `8000` |\n| `0.5` | il numero `0.5` |\n| `true`, `false` | un booleano |\n| `0042` | la stringa `\"0042\"` (uno zero iniziale mantiene la stringa) |\n| `1,5` | la stringa `\"1,5\"` |\n| `-1` | la stringa `\"-1\"` |\n| qualsiasi altra cosa | una stringa |\n\nMolte chiavi predefinite hanno un tipo fisso. Chiavi come `default_request_timeout` o `default_request_maxlength` vengono sempre analizzate come interi, e chiavi come `allow_gzip` o `allow_compile` sono booleani: `true`, `1` e `on` significano `true`, tutto il resto significa `false`. `version`, `secret`, `secret_uid` e `secret_encryption` restano sempre stringhe.\n\n## Valori tipizzati\n\nMetti il tipo tra parentesi dopo la chiave per controllare l'analisi:\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Tipo | Risultato |\n| --- | --- |\n| `string` | il testo grezzo |\n| `number`, `float`, `double`, `currency` | un numero |\n| `boolean`, `bool` | `true` quando il valore contiene `true`, `on`, `1` o `enabled` |\n| `array` | un elenco diviso dalle virgole, senza spazi iniziali e finali |\n| `json` | JSON analizzato |\n| `object`, `eval` | un'espressione JavaScript, valutata |\n| `date`, `datetime`, `time` | una `Date` |\n| `env`, `environment` | il valore della variabile d'ambiente con quel nome |\n| `random` | una nuova stringa casuale della lunghezza indicata (predefinita 10) a ogni avvio |\n| `generate`, `hash` | una stringa casuale creata una volta e conservata |\n\nI valori per `generate` e `hash` vengono salvati in `databases/config.json`, così restano uguali dopo un riavvio. Usali per segreti che non devono cambiare, ma che non vuoi scrivere nel file.\n\nUn valore che inizia con `base64 ` o `hex ` viene prima decodificato:\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Variabili d'ambiente\n\nAccanto ai file di configurazione puoi tenere file `.env` con righe `KEY=value`. Total.js carica `.env` e poi `.env-debug` o `.env-release`. Una variabile che esiste già in `process.env` non viene mai sostituita, quindi vince l'ambiente reale.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nLe virgolette intorno a un valore vengono rimosse e `\\n` diventa un a capo. Le righe che iniziano con `#` o `//` sono commenti.\n\nLeggi una variabile nella configurazione con il tipo `(env)`:\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nNel codice puoi anche usare direttamente `process.env`.\n\n## Leggere la configurazione\n\n`CONF` è un oggetto semplice. Leggi le chiavi come proprietà:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nLe chiavi con un punto o altri caratteri richiedono la notazione con parentesi quadre, per esempio `CONF['security.txt']`. Anche nelle viste `CONF` è disponibile: `@{CONF.name}`.\n\nPuoi assegnare un valore nel codice, ma la modifica non viene scritta nei file e alcune chiavi vengono lette una sola volta all'avvio (`default_port`, `directory_*`, `default_timezone`):\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Modificare la configurazione a runtime\n\n`LOADCONFIG()` unisce nuovi valori in `CONF`. Accetta un oggetto, una stringa nella sintassi della configurazione o un array di elementi `{ id, type, value }`, comodo quando le impostazioni sono salvate in un database:\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Opzioni dello script di avvio\n\nLo script di avvio può passare valori con `options.config`. Vengono applicati prima della lettura dei file di configurazione, quindi una chiave in `config` li sostituisce:\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Thread\n\nUn'applicazione avviata con i thread carica `/threads/<name>/.env`, `/threads/<name>/config` e i file specifici della modalità di quella cartella dopo i file della radice.\n\n## Chiavi comuni\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nIl riferimento elenca ogni chiave con il suo valore predefinito.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWtv1cO61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/configuration/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Konfigurácia","summary":"Ako Total.js načítava konfiguračné súbory a súbory .env, ako sa hodnoty parsujú a ako ich čítať a meniť cez CONF.","markdown":"---\ntitle: \"Konfigurácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Konfigurácia\n\n> Ako Total.js načítava konfiguračné súbory a súbory .env, ako sa hodnoty parsujú a ako ich čítať a meniť cez CONF.\n\nTotal.js číta konfiguráciu aplikácie z obyčajných textových súborov v jej koreňovom adresári. Každá hodnota skončí v globálnom objekte `CONF`, ktorý môžeš čítať z ktoréhokoľvek súboru aplikácie.\n\n## Konfiguračné súbory\n\nPri štarte aplikácie Total.js načíta najviac dva súbory:\n\n| Súbor | Kedy |\n| --- | --- |\n| `config` | vždy |\n| `config-debug` | iba v režime debug |\n| `config-release` | iba v režime release |\n\nSúbor pre konkrétny režim sa číta po `config`, takže jeho hodnoty nahradia hodnoty z `config`. Spoločné nastavenia drž v `config` a do `config-debug` alebo `config-release` daj iba rozdiely.\n\n```text\nconfig\nconfig-debug\nconfig-release\ncontrollers/\ndefinitions/\nindex.js\n```\n\nPred konfiguračnými súbormi Total.js načíta súbory `.env` (pozri nižšie). V režime debug watcher reštartuje aplikáciu, keď uložíš niektorý z konfiguračných súborov.\n\n## Syntax\n\nKaždý riadok je `key : value`. Total.js rozdelí riadok pri prvej `:`, takže hodnota môže obsahovať ďalšie dvojbodky, napríklad URL. Medzery okolo kľúča a hodnoty sa odstránia.\n\n```text\n// Application\nname                    : My Shop\nversion                 : 1.2.0\nauthor                  : Peter\n\n# Server\ndefault_port            : 8000\ndefault_timezone        : Europe/Bratislava\ndefault_request_timeout : 5000\n\nurl                     : https://www.example.com\n```\n\nPravidlá:\n\n- Prázdne riadky sa preskočia.\n- Riadok, ktorý začína `#` alebo `//`, je komentár. Nedávaj komentáre na koniec riadka, stanú sa súčasťou hodnoty.\n- Riadok bez `:` sa preskočí.\n- Kľúče `debug` a `resources` sa v súbore ignorujú.\n\n## Ako sa hodnoty parsujú\n\nBez typu Total.js odhadne typ podľa hodnoty:\n\n| Hodnota | Výsledok |\n| --- | --- |\n| `8000` | číslo `8000` |\n| `0.5` | číslo `0.5` |\n| `true`, `false` | boolovská hodnota |\n| `0042` | reťazec `\"0042\"` (úvodná nula zachová reťazec) |\n| `1,5` | reťazec `\"1,5\"` |\n| `-1` | reťazec `\"-1\"` |\n| čokoľvek iné | reťazec |\n\nMnohé vstavané kľúče majú pevný typ. Kľúče ako `default_request_timeout` alebo `default_request_maxlength` sa vždy parsujú ako celé čísla a kľúče ako `allow_gzip` alebo `allow_compile` sú boolovské: `true`, `1` a `on` znamenajú `true`, všetko ostatné znamená `false`. `version`, `secret`, `secret_uid` a `secret_encryption` zostávajú vždy reťazcami.\n\n## Typové hodnoty\n\nAk chceš riadiť parsovanie, daj typ do zátvoriek za kľúč:\n\n```text\nlimit (number)      : -1\nprice (currency)    : 9.90\ncode (string)       : 0042\nnewsletter (bool)   : enabled\nlanguages (array)   : en, sk, de\napi (json)          : { \"url\": \"https://api.example.com\", \"retries\": 3 }\nsmtp (object)       : { port: 465, secure: true }\nstarted (date)      : 2024-01-01\ndatabase (env)      : DATABASE_URL\ntoken (random)      : 20\npassword (generate) : 16\n```\n\n| Typ | Výsledok |\n| --- | --- |\n| `string` | nespracovaný text |\n| `number`, `float`, `double`, `currency` | číslo |\n| `boolean`, `bool` | `true`, keď hodnota obsahuje `true`, `on`, `1` alebo `enabled` |\n| `array` | zoznam rozdelený čiarkami, orezaný |\n| `json` | sparsovaný JSON |\n| `object`, `eval` | JavaScript výraz, vyhodnotený |\n| `date`, `datetime`, `time` | `Date` |\n| `env`, `environment` | hodnota premennej prostredia s týmto názvom |\n| `random` | nový náhodný reťazec zadanej dĺžky (predvolene 10) pri každom štarte |\n| `generate`, `hash` | náhodný reťazec, ktorý sa vytvorí raz a zachová sa |\n\nHodnoty pre `generate` a `hash` sa ukladajú do `databases/config.json`, takže po reštarte zostanú rovnaké. Použi ich pre tajné kľúče, ktoré sa nesmú meniť, ale ktoré nechceš zapisovať do súboru.\n\nHodnota, ktorá začína `base64 ` alebo `hex `, sa najprv dekóduje:\n\n```text\nmail_password : base64 c2VjcmV0\n```\n\n## Premenné prostredia\n\nPopri konfiguračných súboroch môžeš mať súbory `.env` s riadkami `KEY=value`. Total.js načíta `.env` a potom `.env-debug` alebo `.env-release`. Premenná, ktorá už existuje v `process.env`, sa nikdy nenahradí, takže skutočné prostredie má prednosť.\n\n```text\n# .env\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nAPP_ROOT=/shop/\nWELCOME=\"Hello\\nworld\"\n```\n\nÚvodzovky okolo hodnoty sa odstránia a `\\n` sa zmení na nový riadok. Riadky, ktoré začínajú `#` alebo `//`, sú komentáre.\n\nPremennú načítaš v konfigurácii pomocou typu `(env)`:\n\n```text\ndatabase (env)     : DATABASE_URL\ndefault_root (env) : APP_ROOT\n```\n\nV kóde môžeš použiť aj priamo `process.env`.\n\n## Čítanie konfigurácie\n\n`CONF` je obyčajný objekt. Kľúče čítaj ako vlastnosti:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version, url: CONF.url });\n}\n```\n\nKľúče s bodkou alebo inými znakmi potrebujú zápis s hranatými zátvorkami, napríklad `CONF['security.txt']`. `CONF` je dostupný aj v pohľadoch: `@{CONF.name}`.\n\nHodnotu môžeš priradiť v kóde, ale zmena sa nezapíše do súborov a niektoré kľúče sa čítajú iba raz pri štarte (`default_port`, `directory_*`, `default_timezone`):\n\n```js\nCONF.allow_gzip = false;\n```\n\n## Zmena konfigurácie za behu\n\n`LOADCONFIG()` zlúči nové hodnoty do `CONF`. Prijíma objekt, reťazec v konfiguračnej syntaxi alebo pole položiek `{ id, type, value }`, čo sa hodí, keď sú nastavenia uložené v databáze:\n\n```js\nLOADCONFIG({ name: 'My Shop', allow_tms: true });\n\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n\nLOADCONFIG([\n\t{ id: 'mail_smtp', type: 'string', value: 'smtp.example.com' },\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' }\n]);\n```\n\n## Možnosti štartovacieho skriptu\n\nŠtartovací skript môže odovzdať hodnoty cez `options.config`. Použijú sa pred načítaním konfiguračných súborov, takže kľúč v `config` ich nahradí:\n\n```js\nvar options = {};\noptions.config = { name: 'Total.js' };\nrequire('total4/debug')(options);\n```\n\n## Vlákna\n\nAplikácia spustená s vláknami načíta `/threads/<name>/.env`, `/threads/<name>/config` a súbory pre konkrétny režim z tohto priečinka po súboroch z koreňa.\n\n## Bežné kľúče\n\n```text\nname                     : My Shop\nversion                  : 1.0.0\nurl                      : https://www.example.com\nsecret                   : replace-me\ndefault_timezone         : utc\ndefault_root             : /shop/\ndefault_request_maxlength: 1024\ndefault_cors             : example.com, app.example.com\nallow_tms                : true\nmail_smtp                : smtp.example.com\nmail_smtp_options        : { port: 465, secure: true, user: 'info@example.com', password: '***' }\nmail_from                : info@example.com\nlogger                   : true\n```\n\nReferencia uvádza každý kľúč s jeho predvolenou hodnotou.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Authorization and sessions","summary":"Sign in requests with the AUTH() delegate, limit routes with the + and - flags, and keep sessions in cookies, tokens or the SESSION() store.","markdown":"---\ntitle: Authorization and sessions\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Authorization and sessions\n\n> Sign in requests with the AUTH() delegate, limit routes with the + and - flags, and keep sessions in cookies, tokens or the SESSION() store.\n\nTotal.js signs in requests with one delegate. You register it with `AUTH()`, the framework calls it for every request (and for every WebSocket connection), and the delegate answers either \"this is the user\" or \"nobody is signed in\". Routes then decide with a flag whether they run for signed-in visitors, for anonymous visitors or for both.\n\nPut the delegate in a file in the `definitions/` folder, for example `definitions/auth.js`.\n\n## The AUTH() delegate\n\n`AUTH(function($) { ... })` receives a `$` object with the request data: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` and more. Call `$.success(user)` when the request belongs to a user, or `$.invalid()` when it does not:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nThe object you pass to `$.success()` becomes `controller.user` in actions, `$.user` in schemas and `client.user` in WebSockets. Keep it small: it is the same object for the whole request.\n\n`$.cancel()` stops the processing when you have already answered the request yourself, for example with a redirect from `$.res`.\n\n## Route flags: + and -\n\nStart the URL with `+` for routes that need a signed-in user, and with `-` for routes only anonymous visitors can see. A route without a flag runs for both:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nThe prefix `🔒` works like `+`. In the flags array you can write `'authorize'`, `'authorized'` or `'logged'` instead of `+`, and `'unauthorize'`, `'unauthorized'` or `'unlogged'` instead of `-`. WebSocket routes accept the same prefixes.\n\nYou can declare the same URL twice, once with `+` and once with `-`, and Total.js picks the route that matches the visitor. When a route exists only for the other state, the visitor gets `401`; when no route exists at all, `404`. A WebSocket that does not match is closed with `4001`.\n\nThe flags only take effect when an `AUTH()` delegate is registered. Without one, the framework does not check them.\n\n## Roles\n\nA flag that starts with `@` is a role. Total.js keeps it in `controller.route.flags` and treats the route as one that needs a signed-in user, but it does not compare roles for you. Check them in the action, for example with `UNAUTHORIZED()`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` looks for the roles in `user.permissions` or `user.roles` (an array or an object). It returns `false` when the user has one of them, or has `sa` or `su` set to a truthy value. Otherwise it calls `$.invalid(401)` and returns `true`.\n\n## Signing in and out with cookies\n\nA cookie holds an encrypted token. `ENCRYPTREQ()` encrypts a value together with the browser's user agent (and the IP address in strict mode), so a stolen cookie does not work in another browser:\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` reads a cookie and `controller.cookie(name, value, expires, [options])` writes one. Options are `domain`, `path` (default `/`), `secure`, `httponly` and `samesite`. `CONF.default_cookies_samesite` (default `'Lax'`) and `CONF.default_cookies_secure` (default `false`) set the defaults.\n\n## The built-in session mechanism\n\nPass an object to `AUTH()` instead of a function, and Total.js runs a cookie session for you. It decrypts the cookie, keeps the user data in memory and calls `onread` only when the data is not cached:\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` adds methods to the object you pass, so keep a reference to it. Sign the user in with `opt.authcookie()`, and sign out with `opt.logout()`:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nAfter you change a user in the database, call `opt.refresh(userid)` to drop the cached data, so the next request reads it again, or `opt.update(userid, fn)` to change the cached data in place.\n\n## SESSION(): a session store\n\n`SESSION([name])` returns a named session store (the default name is `default`). It keeps sessions in memory, writes their metadata to `databases/sessions.txt` and loads it again after a restart. The user data is not written to the file: after a restart, or after the data is released, the store asks the `ondata` delegate for it:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nCreate the session when the user signs in, and remove it when the user signs out:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nFor an API with tokens instead of cookies, use `session.settoken()` and `session.gettoken()`. Methods that end with `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`) work with the user ID instead of the session ID, so you can update or end all sessions of a user at once.\n\nEvery 10 minutes the framework removes expired sessions and releases the data of sessions unused for `CONF.allow_sessions_unused` (default `'-20 minutes'`).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Autorisierung und Sessions","summary":"Melde Requests mit dem Delegate AUTH() an, beschränke Routen mit den Flags + und - und speichere Sessions in Cookies, Tokens oder im Store SESSION().","markdown":"---\ntitle: Autorisierung und Sessions\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorisierung und Sessions\n\n> Melde Requests mit dem Delegate AUTH() an, beschränke Routen mit den Flags + und - und speichere Sessions in Cookies, Tokens oder im Store SESSION().\n\nTotal.js meldet Requests mit einem einzigen Delegate an. Du registrierst es mit `AUTH()`, das Framework ruft es für jeden Request (und für jede WebSocket-Verbindung) auf, und das Delegate antwortet entweder „das ist der Benutzer“ oder „niemand ist angemeldet“. Die Routen entscheiden dann mit einem Flag, ob sie für angemeldete Besucher, für anonyme Besucher oder für beide laufen.\n\nLege das Delegate in eine Datei im Ordner `definitions/`, zum Beispiel `definitions/auth.js`.\n\n## Das Delegate AUTH()\n\n`AUTH(function($) { ... })` erhält ein Objekt `$` mit den Daten des Requests: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` und mehr. Rufe `$.success(user)` auf, wenn der Request zu einem Benutzer gehört, oder `$.invalid()`, wenn nicht:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nDas Objekt, das du an `$.success()` übergibst, wird zu `controller.user` in Actions, zu `$.user` in Schemas und zu `client.user` in WebSockets. Halte es klein: Es ist für den ganzen Request dasselbe Objekt.\n\n`$.cancel()` beendet die Verarbeitung, wenn du den Request bereits selbst beantwortet hast, zum Beispiel mit einer Weiterleitung über `$.res`.\n\n## Routen-Flags: + und -\n\nBeginne die URL mit `+` für Routen, die einen angemeldeten Benutzer brauchen, und mit `-` für Routen, die nur anonyme Besucher sehen dürfen. Eine Route ohne Flag läuft für beide:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nDas Präfix `🔒` funktioniert wie `+`. Im Flags-Array kannst du statt `+` auch `'authorize'`, `'authorized'` oder `'logged'` schreiben und statt `-` auch `'unauthorize'`, `'unauthorized'` oder `'unlogged'`. WebSocket-Routen akzeptieren dieselben Präfixe.\n\nDu kannst dieselbe URL zweimal deklarieren, einmal mit `+` und einmal mit `-`, und Total.js wählt die Route, die zum Besucher passt. Existiert eine Route nur für den anderen Zustand, erhält der Besucher `401`; existiert gar keine Route, `404`. Ein WebSocket, der nicht passt, wird mit `4001` geschlossen.\n\nDie Flags wirken nur, wenn ein Delegate `AUTH()` registriert ist. Ohne es prüft das Framework sie nicht.\n\n## Rollen\n\nEin Flag, das mit `@` beginnt, ist eine Rolle. Total.js speichert es in `controller.route.flags` und behandelt die Route als eine, die einen angemeldeten Benutzer braucht, vergleicht die Rollen aber nicht für dich. Prüfe sie in der Action, zum Beispiel mit `UNAUTHORIZED()`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` sucht die Rollen in `user.permissions` oder `user.roles` (ein Array oder ein Objekt). Es gibt `false` zurück, wenn der Benutzer eine davon hat oder wenn `sa` oder `su` einen truthy Wert hat. Andernfalls ruft es `$.invalid(401)` auf und gibt `true` zurück.\n\n## An- und Abmelden mit Cookies\n\nEin Cookie enthält ein verschlüsseltes Token. `ENCRYPTREQ()` verschlüsselt einen Wert zusammen mit dem User-Agent des Browsers (und im Strict-Modus mit der IP-Adresse), sodass ein gestohlenes Cookie in einem anderen Browser nicht funktioniert:\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` liest ein Cookie und `controller.cookie(name, value, expires, [options])` schreibt eines. Die Optionen sind `domain`, `path` (Standard `/`), `secure`, `httponly` und `samesite`. `CONF.default_cookies_samesite` (Standard `'Lax'`) und `CONF.default_cookies_secure` (Standard `false`) legen die Standardwerte fest.\n\n## Der eingebaute Session-Mechanismus\n\nÜbergib an `AUTH()` ein Objekt statt einer Funktion, und Total.js betreibt für dich eine Cookie-Session. Es entschlüsselt das Cookie, hält die Benutzerdaten im Speicher und ruft `onread` nur auf, wenn die Daten nicht im Cache liegen:\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` fügt dem übergebenen Objekt Methoden hinzu, also behalte eine Referenz darauf. Melde den Benutzer mit `opt.authcookie()` an und mit `opt.logout()` ab:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nNachdem du einen Benutzer in der Datenbank geändert hast, rufe `opt.refresh(userid)` auf, um die gecachten Daten zu verwerfen, damit der nächste Request sie neu liest, oder `opt.update(userid, fn)`, um die gecachten Daten direkt zu ändern.\n\n## SESSION(): ein Session-Store\n\n`SESSION([name])` gibt einen benannten Session-Store zurück (der Standardname ist `default`). Er hält Sessions im Speicher, schreibt ihre Metadaten nach `databases/sessions.txt` und lädt sie nach einem Neustart wieder. Die Benutzerdaten werden nicht in die Datei geschrieben: Nach einem Neustart oder nachdem die Daten freigegeben wurden, fragt der Store das Delegate `ondata` danach:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nErstelle die Session, wenn sich der Benutzer anmeldet, und entferne sie, wenn er sich abmeldet:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nFür eine API mit Tokens statt Cookies verwendest du `session.settoken()` und `session.gettoken()`. Methoden, die auf `2` enden (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`), arbeiten mit der Benutzer-ID statt mit der Session-ID, sodass du alle Sessions eines Benutzers auf einmal aktualisieren oder beenden kannst.\n\nAlle 10 Minuten entfernt das Framework abgelaufene Sessions und gibt die Daten von Sessions frei, die seit `CONF.allow_sessions_unused` (Standard `'-20 minutes'`) nicht verwendet wurden.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Autorización y sesiones","summary":"Autentica peticiones con el delegado AUTH(), limita rutas con los flags + y -, y guarda sesiones en cookies, tokens o en el almacén SESSION().","markdown":"---\ntitle: \"Autorización y sesiones\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorización y sesiones\n\n> Autentica peticiones con el delegado AUTH(), limita rutas con los flags + y -, y guarda sesiones en cookies, tokens o en el almacén SESSION().\n\nTotal.js autentica las peticiones con un único delegado. Lo registras con `AUTH()`, el framework lo llama en cada petición (y en cada conexión WebSocket), y el delegado responde \"este es el usuario\" o \"no hay nadie autenticado\". Después, las rutas deciden con un flag si se ejecutan para visitantes autenticados, para visitantes anónimos o para ambos.\n\nPon el delegado en un archivo de la carpeta `definitions/`, por ejemplo `definitions/auth.js`.\n\n## El delegado AUTH()\n\n`AUTH(function($) { ... })` recibe un objeto `$` con los datos de la petición: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` y más. Llama a `$.success(user)` cuando la petición pertenece a un usuario, o a `$.invalid()` cuando no:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nEl objeto que pasas a `$.success()` se convierte en `controller.user` en las acciones, en `$.user` en los esquemas y en `client.user` en los WebSockets. Mantenlo pequeño: es el mismo objeto durante toda la petición.\n\n`$.cancel()` detiene el procesamiento cuando ya has respondido tú mismo a la petición, por ejemplo con una redirección desde `$.res`.\n\n## Flags de ruta: + y -\n\nEmpieza la URL con `+` para las rutas que necesitan un usuario autenticado, y con `-` para las rutas que solo pueden ver los visitantes anónimos. Una ruta sin flag se ejecuta para ambos:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nEl prefijo `🔒` funciona como `+`. En el array de flags puedes escribir `'authorize'`, `'authorized'` o `'logged'` en lugar de `+`, y `'unauthorize'`, `'unauthorized'` o `'unlogged'` en lugar de `-`. Las rutas WebSocket aceptan los mismos prefijos.\n\nPuedes declarar la misma URL dos veces, una con `+` y otra con `-`, y Total.js elige la ruta que corresponde al visitante. Cuando una ruta existe solo para el otro estado, el visitante recibe `401`; cuando no existe ninguna ruta, `404`. Un WebSocket que no coincide se cierra con `4001`.\n\nLos flags solo tienen efecto cuando hay un delegado `AUTH()` registrado. Sin él, el framework no los comprueba.\n\n## Roles\n\nUn flag que empieza con `@` es un rol. Total.js lo guarda en `controller.route.flags` y trata la ruta como una que necesita un usuario autenticado, pero no compara los roles por ti. Compruébalos en la acción, por ejemplo con `UNAUTHORIZED()`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` busca los roles en `user.permissions` o `user.roles` (un array o un objeto). Devuelve `false` cuando el usuario tiene uno de ellos, o tiene `sa` o `su` con un valor verdadero. En caso contrario, llama a `$.invalid(401)` y devuelve `true`.\n\n## Iniciar y cerrar sesión con cookies\n\nUna cookie guarda un token cifrado. `ENCRYPTREQ()` cifra un valor junto con el user agent del navegador (y la dirección IP en modo estricto), así que una cookie robada no funciona en otro navegador:\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` lee una cookie y `controller.cookie(name, value, expires, [options])` escribe una. Las opciones son `domain`, `path` (por defecto `/`), `secure`, `httponly` y `samesite`. `CONF.default_cookies_samesite` (por defecto `'Lax'`) y `CONF.default_cookies_secure` (por defecto `false`) definen los valores por defecto.\n\n## El mecanismo de sesión integrado\n\nPasa un objeto a `AUTH()` en lugar de una función, y Total.js gestiona una sesión con cookie por ti. Descifra la cookie, guarda los datos del usuario en memoria y llama a `onread` solo cuando los datos no están en caché:\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` añade métodos al objeto que le pasas, así que guarda una referencia a él. Inicia la sesión del usuario con `opt.authcookie()` y ciérrala con `opt.logout()`:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nDespués de cambiar un usuario en la base de datos, llama a `opt.refresh(userid)` para descartar los datos en caché, de modo que la siguiente petición los lea de nuevo, o a `opt.update(userid, fn)` para cambiar los datos en caché directamente.\n\n## SESSION(): un almacén de sesiones\n\n`SESSION([name])` devuelve un almacén de sesiones con nombre (el nombre por defecto es `default`). Guarda las sesiones en memoria, escribe sus metadatos en `databases/sessions.txt` y los vuelve a cargar tras un reinicio. Los datos del usuario no se escriben en el archivo: tras un reinicio, o después de liberar los datos, el almacén se los pide al delegado `ondata`:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nCrea la sesión cuando el usuario inicia sesión, y elimínala cuando la cierra:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nPara una API con tokens en lugar de cookies, usa `session.settoken()` y `session.gettoken()`. Los métodos que terminan en `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`) trabajan con el ID del usuario en lugar del ID de sesión, así que puedes actualizar o terminar todas las sesiones de un usuario a la vez.\n\nCada 10 minutos el framework elimina las sesiones caducadas y libera los datos de las sesiones sin usar durante `CONF.allow_sessions_unused` (por defecto `'-20 minutes'`).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Autorisation et sessions","summary":"Authentifie les requêtes avec le délégué AUTH(), limite les routes avec les flags + et -, et conserve les sessions dans des cookies, des tokens ou le store SESSION().","markdown":"---\ntitle: Autorisation et sessions\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorisation et sessions\n\n> Authentifie les requêtes avec le délégué AUTH(), limite les routes avec les flags + et -, et conserve les sessions dans des cookies, des tokens ou le store SESSION().\n\nTotal.js authentifie les requêtes avec un seul délégué. Tu l'enregistres avec `AUTH()`, le framework l'appelle pour chaque requête (et pour chaque connexion WebSocket), et le délégué répond soit « voici l'utilisateur », soit « personne n'est connecté ». Les routes décident ensuite, avec un flag, si elles s'exécutent pour les visiteurs connectés, pour les visiteurs anonymes ou pour les deux.\n\nPlace le délégué dans un fichier du dossier `definitions/`, par exemple `definitions/auth.js`.\n\n## Le délégué AUTH()\n\n`AUTH(function($) { ... })` reçoit un objet `$` avec les données de la requête : `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` et d'autres. Appelle `$.success(user)` quand la requête appartient à un utilisateur, ou `$.invalid()` dans le cas contraire :\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nL'objet que tu passes à `$.success()` devient `controller.user` dans les actions, `$.user` dans les schémas et `client.user` dans les WebSockets. Garde-le léger : c'est le même objet pendant toute la requête.\n\n`$.cancel()` arrête le traitement quand tu as déjà répondu toi-même à la requête, par exemple avec une redirection depuis `$.res`.\n\n## Flags de route : + et -\n\nCommence l'URL par `+` pour les routes qui exigent un utilisateur connecté, et par `-` pour les routes que seuls les visiteurs anonymes peuvent voir. Une route sans flag s'exécute pour les deux :\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nLe préfixe `🔒` fonctionne comme `+`. Dans le tableau de flags, tu peux écrire `'authorize'`, `'authorized'` ou `'logged'` au lieu de `+`, et `'unauthorize'`, `'unauthorized'` ou `'unlogged'` au lieu de `-`. Les routes WebSocket acceptent les mêmes préfixes.\n\nTu peux déclarer la même URL deux fois, une fois avec `+` et une fois avec `-`, et Total.js choisit la route qui correspond au visiteur. Quand une route n'existe que pour l'autre état, le visiteur reçoit `401` ; quand aucune route n'existe, `404`. Un WebSocket qui ne correspond pas est fermé avec `4001`.\n\nLes flags ne prennent effet que si un délégué `AUTH()` est enregistré. Sans délégué, le framework ne les vérifie pas.\n\n## Rôles\n\nUn flag qui commence par `@` est un rôle. Total.js le conserve dans `controller.route.flags` et traite la route comme une route qui exige un utilisateur connecté, mais il ne compare pas les rôles à ta place. Vérifie-les dans l'action, par exemple avec `UNAUTHORIZED()` :\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` cherche les rôles dans `user.permissions` ou `user.roles` (un tableau ou un objet). Elle renvoie `false` quand l'utilisateur possède l'un d'eux, ou quand `sa` ou `su` a une valeur vraie. Sinon, elle appelle `$.invalid(401)` et renvoie `true`.\n\n## Connexion et déconnexion avec des cookies\n\nUn cookie contient un token chiffré. `ENCRYPTREQ()` chiffre une valeur avec le user agent du navigateur (et l'adresse IP en mode strict), si bien qu'un cookie volé ne fonctionne pas dans un autre navigateur :\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` lit un cookie et `controller.cookie(name, value, expires, [options])` en écrit un. Les options sont `domain`, `path` (par défaut `/`), `secure`, `httponly` et `samesite`. `CONF.default_cookies_samesite` (par défaut `'Lax'`) et `CONF.default_cookies_secure` (par défaut `false`) définissent les valeurs par défaut.\n\n## Le mécanisme de session intégré\n\nPasse un objet à `AUTH()` au lieu d'une fonction, et Total.js gère une session par cookie pour toi. Il déchiffre le cookie, garde les données de l'utilisateur en mémoire et n'appelle `onread` que lorsque les données ne sont pas en cache :\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` ajoute des méthodes à l'objet que tu passes, donc gardes-en une référence. Connecte l'utilisateur avec `opt.authcookie()` et déconnecte-le avec `opt.logout()` :\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nAprès avoir modifié un utilisateur dans la base de données, appelle `opt.refresh(userid)` pour supprimer les données en cache, afin que la requête suivante les relise, ou `opt.update(userid, fn)` pour modifier les données en cache sur place.\n\n## SESSION() : un store de sessions\n\n`SESSION([name])` renvoie un store de sessions nommé (le nom par défaut est `default`). Il garde les sessions en mémoire, écrit leurs métadonnées dans `databases/sessions.txt` et les recharge après un redémarrage. Les données de l'utilisateur ne sont pas écrites dans le fichier : après un redémarrage, ou après la libération des données, le store les demande au délégué `ondata` :\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nCrée la session quand l'utilisateur se connecte, et supprime-la quand il se déconnecte :\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nPour une API avec des tokens au lieu de cookies, utilise `session.settoken()` et `session.gettoken()`. Les méthodes qui se terminent par `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`) travaillent avec l'ID de l'utilisateur au lieu de l'ID de session, ce qui te permet de mettre à jour ou de terminer toutes les sessions d'un utilisateur en une seule fois.\n\nToutes les 10 minutes, le framework supprime les sessions expirées et libère les données des sessions inutilisées depuis `CONF.allow_sessions_unused` (par défaut `'-20 minutes'`).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Autorizzazione e sessioni","summary":"Autentica le richieste con il delegato AUTH(), limita le route con i flag + e - e conserva le sessioni in cookie, token o nello store SESSION().","markdown":"---\ntitle: Autorizzazione e sessioni\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorizzazione e sessioni\n\n> Autentica le richieste con il delegato AUTH(), limita le route con i flag + e - e conserva le sessioni in cookie, token o nello store SESSION().\n\nTotal.js autentica le richieste con un solo delegato. Lo registri con `AUTH()`, il framework lo chiama per ogni richiesta (e per ogni connessione WebSocket) e il delegato risponde \"questo è l'utente\" oppure \"nessuno ha effettuato l'accesso\". Le route poi decidono con un flag se vengono eseguite per i visitatori autenticati, per quelli anonimi o per entrambi.\n\nMetti il delegato in un file nella cartella `definitions/`, per esempio `definitions/auth.js`.\n\n## Il delegato AUTH()\n\n`AUTH(function($) { ... })` riceve un oggetto `$` con i dati della richiesta: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` e altro. Chiama `$.success(user)` quando la richiesta appartiene a un utente, oppure `$.invalid()` quando non è così:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nL'oggetto che passi a `$.success()` diventa `controller.user` nelle azioni, `$.user` negli schemi e `client.user` nei WebSocket. Mantienilo piccolo: è lo stesso oggetto per tutta la richiesta.\n\n`$.cancel()` interrompe l'elaborazione quando hai già risposto tu stesso alla richiesta, per esempio con un redirect da `$.res`.\n\n## Flag delle route: + e -\n\nInizia l'URL con `+` per le route che richiedono un utente autenticato e con `-` per le route che possono vedere solo i visitatori anonimi. Una route senza flag viene eseguita per entrambi:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nIl prefisso `🔒` funziona come `+`. Nell'array dei flag puoi scrivere `'authorize'`, `'authorized'` o `'logged'` al posto di `+`, e `'unauthorize'`, `'unauthorized'` o `'unlogged'` al posto di `-`. Le route WebSocket accettano gli stessi prefissi.\n\nPuoi dichiarare lo stesso URL due volte, una con `+` e una con `-`, e Total.js sceglie la route adatta al visitatore. Quando una route esiste solo per l'altro stato, il visitatore riceve `401`; quando non esiste nessuna route, `404`. Un WebSocket che non corrisponde viene chiuso con `4001`.\n\nI flag hanno effetto solo quando è registrato un delegato `AUTH()`. Senza di esso, il framework non li controlla.\n\n## Ruoli\n\nUn flag che inizia con `@` è un ruolo. Total.js lo conserva in `controller.route.flags` e tratta la route come una che richiede un utente autenticato, ma non confronta i ruoli al posto tuo. Controllali nell'azione, per esempio con `UNAUTHORIZED()`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` cerca i ruoli in `user.permissions` o `user.roles` (un array o un oggetto). Restituisce `false` quando l'utente ha uno di essi, oppure ha `sa` o `su` impostato a un valore truthy. Altrimenti chiama `$.invalid(401)` e restituisce `true`.\n\n## Accesso e uscita con i cookie\n\nUn cookie contiene un token cifrato. `ENCRYPTREQ()` cifra un valore insieme allo user agent del browser (e all'indirizzo IP in modalità strict), così un cookie rubato non funziona in un altro browser:\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` legge un cookie e `controller.cookie(name, value, expires, [options])` ne scrive uno. Le opzioni sono `domain`, `path` (predefinito `/`), `secure`, `httponly` e `samesite`. `CONF.default_cookies_samesite` (predefinito `'Lax'`) e `CONF.default_cookies_secure` (predefinito `false`) impostano i valori predefiniti.\n\n## Il meccanismo di sessione integrato\n\nPassa a `AUTH()` un oggetto invece di una funzione e Total.js gestisce per te una sessione basata su cookie. Decifra il cookie, tiene i dati dell'utente in memoria e chiama `onread` solo quando i dati non sono in cache:\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` aggiunge metodi all'oggetto che passi, quindi tienine un riferimento. Fai accedere l'utente con `opt.authcookie()` e fallo uscire con `opt.logout()`:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nDopo aver modificato un utente nel database, chiama `opt.refresh(userid)` per scartare i dati in cache, così la richiesta successiva li legge di nuovo, oppure `opt.update(userid, fn)` per modificare direttamente i dati in cache.\n\n## SESSION(): uno store di sessioni\n\n`SESSION([name])` restituisce uno store di sessioni con nome (il nome predefinito è `default`). Tiene le sessioni in memoria, scrive i loro metadati in `databases/sessions.txt` e li ricarica dopo un riavvio. I dati dell'utente non vengono scritti nel file: dopo un riavvio, o dopo che i dati sono stati rilasciati, lo store li chiede al delegato `ondata`:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nCrea la sessione quando l'utente accede e rimuovila quando l'utente esce:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nPer un'API con token invece dei cookie, usa `session.settoken()` e `session.gettoken()`. I metodi che terminano con `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`) lavorano con l'ID utente invece dell'ID di sessione, così puoi aggiornare o chiudere tutte le sessioni di un utente in una volta.\n\nOgni 10 minuti il framework rimuove le sessioni scadute e rilascia i dati delle sessioni non usate da `CONF.allow_sessions_unused` (predefinito `'-20 minutes'`).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1p4Oh61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/authorization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Autorizácia a relácie","summary":"Prihlasuj požiadavky delegátom AUTH(), obmedzuj trasy flagmi + a - a uchovávaj relácie v cookies, tokenoch alebo v úložisku SESSION().","markdown":"---\ntitle: \"Autorizácia a relácie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorizácia a relácie\n\n> Prihlasuj požiadavky delegátom AUTH(), obmedzuj trasy flagmi + a - a uchovávaj relácie v cookies, tokenoch alebo v úložisku SESSION().\n\nTotal.js prihlasuje požiadavky jedným delegátom. Zaregistruješ ho cez `AUTH()`, framework ho volá pri každej požiadavke (aj pri každom WebSocket spojení) a delegát odpovie buď „toto je používateľ“, alebo „nikto nie je prihlásený“. Trasy potom flagom určia, či sa spustia pre prihlásených návštevníkov, pre anonymných návštevníkov alebo pre oboch.\n\nDelegáta vlož do súboru v priečinku `definitions/`, napríklad `definitions/auth.js`.\n\n## Delegát AUTH()\n\n`AUTH(function($) { ... })` dostane objekt `$` s údajmi požiadavky: `$.cookie(name)`, `$.headers`, `$.query`, `$.ip`, `$.ua`, `$.url`, `$.websocket` a ďalšie. Zavolaj `$.success(user)`, keď požiadavka patrí používateľovi, alebo `$.invalid()`, keď nepatrí:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\n\tvar token = $.cookie('token');\n\tif (!token) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tvar userid = DECRYPTREQ($.req, token, 'auth');\n\tif (!userid) {\n\t\t$.invalid();\n\t\treturn;\n\t}\n\n\tNOSQL('users').one().where('id', userid).callback(function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nObjekt, ktorý odovzdáš do `$.success()`, sa stane `controller.user` v akciách, `$.user` v schémach a `client.user` vo WebSocketoch. Udržuj ho malý: je to ten istý objekt pre celú požiadavku.\n\n`$.cancel()` zastaví spracovanie, keď si už na požiadavku odpovedal sám, napríklad presmerovaním cez `$.res`.\n\n## Flagy trás: + a -\n\nZačni URL znakom `+` pre trasy, ktoré potrebujú prihláseného používateľa, a znakom `-` pre trasy, ktoré vidia len anonymní návštevníci. Trasa bez flagu sa spustí pre oboch:\n\n```js\nexports.install = function() {\n\tROUTE('+GET  /account/', account);   // signed in\n\tROUTE('-GET  /login/', 'login');     // not signed in\n\tROUTE('-POST /login/', login);\n\tROUTE('+GET  /logout/', logout);\n\tROUTE('GET   /', 'index');           // everybody\n};\n```\n\nPrefix `🔒` funguje ako `+`. V poli flagov môžeš namiesto `+` napísať `'authorize'`, `'authorized'` alebo `'logged'` a namiesto `-` hodnoty `'unauthorize'`, `'unauthorized'` alebo `'unlogged'`. WebSocket trasy prijímajú rovnaké prefixy.\n\nTú istú URL môžeš deklarovať dvakrát, raz s `+` a raz s `-`, a Total.js vyberie trasu, ktorá zodpovedá návštevníkovi. Keď trasa existuje len pre opačný stav, návštevník dostane `401`; keď neexistuje žiadna trasa, dostane `404`. WebSocket, ktorý nezodpovedá, sa zatvorí s kódom `4001`.\n\nFlagy fungujú len vtedy, keď je zaregistrovaný delegát `AUTH()`. Bez neho ich framework nekontroluje.\n\n## Roly\n\nFlag, ktorý začína znakom `@`, je rola. Total.js ho uloží do `controller.route.flags` a trasu považuje za takú, ktorá potrebuje prihláseného používateľa, ale roly za teba neporovnáva. Over ich v akcii, napríklad pomocou `UNAUTHORIZED()`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['@admin']);\n};\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n`UNAUTHORIZED($, role1, role2, ...)` hľadá roly v `user.permissions` alebo `user.roles` (pole alebo objekt). Vráti `false`, keď má používateľ niektorú z nich, alebo keď má `sa` či `su` nastavené na pravdivú hodnotu. Inak zavolá `$.invalid(401)` a vráti `true`.\n\n## Prihlásenie a odhlásenie pomocou cookies\n\nCookie obsahuje zašifrovaný token. `ENCRYPTREQ()` zašifruje hodnotu spolu s user agentom prehliadača (a v striktnom režime aj s IP adresou), takže ukradnutá cookie v inom prehliadači nefunguje:\n\n```js\nfunction login() {\n\tvar self = this;\n\tNOSQL('users').one().where('email', self.body.email).callback(function(err, user) {\n\n\t\tif (!user || user.password !== self.body.password.sha256()) {\n\t\t\tself.invalid('error-credentials');\n\t\t\treturn;\n\t\t}\n\n\t\tself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month', { httponly: true });\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tself.cookie('token', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\n`controller.cookie(name)` prečíta cookie a `controller.cookie(name, value, expires, [options])` ju zapíše. Možnosti sú `domain`, `path` (predvolene `/`), `secure`, `httponly` a `samesite`. Predvolené hodnoty nastavujú `CONF.default_cookies_samesite` (predvolene `'Lax'`) a `CONF.default_cookies_secure` (predvolene `false`).\n\n## Vstavaný mechanizmus relácií\n\nOdovzdaj do `AUTH()` namiesto funkcie objekt a Total.js za teba spravuje reláciu v cookie. Dešifruje cookie, drží údaje používateľa v pamäti a `onread` volá len vtedy, keď údaje nie sú v cache:\n\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';   // how long user data stays in memory\nopt.ddos = 10;               // failed attempts per IP before blocking\n\nopt.onread = function(meta, next) {\n\t// meta = { sessionid, userid, ip, ua }\n\tNOSQL('sessions').one().where('id', meta.sessionid).where('userid', meta.userid).callback(function(err, session) {\n\t\tif (!session)\n\t\t\treturn next();\n\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t});\n};\n\nopt.onlogout = function(session) {\n\tNOSQL('sessions').remove().where('id', session.sessionid);\n};\n\nAUTH(opt);\nMAIN.auth = opt;\n```\n\n`AUTH()` pridá do odovzdaného objektu metódy, preto si naň drž referenciu. Používateľa prihlásiš cez `opt.authcookie()` a odhlásiš cez `opt.logout()`:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tvar sessionid = UID();\n\tNOSQL('sessions').insert({ id: sessionid, userid: user.id, dtcreated: NOW });\n\tMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\n\tself.redirect('/account/');\n}\n\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\nKeď zmeníš používateľa v databáze, zavolaj `opt.refresh(userid)`, aby sa údaje v cache zahodili a ďalšia požiadavka ich načítala znova, alebo `opt.update(userid, fn)`, aby si údaje v cache zmenil priamo.\n\n## SESSION(): úložisko relácií\n\n`SESSION([name])` vráti pomenované úložisko relácií (predvolený názov je `default`). Relácie drží v pamäti, ich metadáta zapisuje do `databases/sessions.txt` a po reštarte ich znova načíta. Údaje používateľa sa do súboru nezapisujú: po reštarte alebo po uvoľnení údajov si ich úložisko vyžiada od delegáta `ondata`:\n\n```js\nvar session = SESSION();\n\nsession.ondata = function(meta, next) {\n\t// meta.sessionid, meta.id (user ID), meta.note, meta.settings\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, user) {\n\t\tif (user)\n\t\t\t$.success(user);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\nReláciu vytvor, keď sa používateľ prihlási, a odstráň ju, keď sa odhlási:\n\n```js\nfunction login() {\n\tvar self = this;\n\t// ... check the credentials, then:\n\tsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key', note: self.ua }, function() {\n\t\tself.redirect('/account/');\n\t});\n}\n\nfunction logout() {\n\tvar self = this;\n\tsession.remove(self.sessionid);\n\tself.cookie('sid', '', '-1 day');\n\tself.redirect('/');\n}\n```\n\nPre API s tokenmi namiesto cookies použi `session.settoken()` a `session.gettoken()`. Metódy, ktoré končia na `2` (`get2`, `set2`, `update2`, `remove2`, `release2`, `has2`, `contains2`), pracujú s ID používateľa namiesto ID relácie, takže môžeš naraz aktualizovať alebo ukončiť všetky relácie používateľa.\n\nKaždých 10 minút framework odstráni expirované relácie a uvoľní údaje relácií nepoužitých počas `CONF.allow_sessions_unused` (predvolene `'-20 minutes'`).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JafRjA1ch61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Encryption","summary":"Encrypt values with ENCRYPT() and DECRYPT(), bind them to the browser of a request with ENCRYPTREQ() and DECRYPTREQ(), and set the secret.","markdown":"---\ntitle: Encryption\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Encryption\n\n> Encrypt values with ENCRYPT() and DECRYPT(), bind them to the browser of a request with ENCRYPTREQ() and DECRYPTREQ(), and set the secret.\n\n`ENCRYPT(value, key)` and `DECRYPT(value, key)` encrypt any value with `CONF.secret` and your key. Objects are serialized to JSON, and `DECRYPT()` parses JSON by default; pass `false` as the third argument to get the plain string back.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafRjA1ch61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Verschlüsselung","summary":"Verschlüssele Werte mit ENCRYPT() und DECRYPT(), binde sie mit ENCRYPTREQ() und DECRYPTREQ() an den Browser einer Anfrage und lege das Secret fest.","markdown":"---\ntitle: \"Verschlüsselung\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Verschlüsselung\n\n> Verschlüssele Werte mit ENCRYPT() und DECRYPT(), binde sie mit ENCRYPTREQ() und DECRYPTREQ() an den Browser einer Anfrage und lege das Secret fest.\n\n`ENCRYPT(value, key)` und `DECRYPT(value, key)` verschlüsseln einen beliebigen Wert mit `CONF.secret` und deinem Schlüssel. Objekte werden zu JSON serialisiert, und `DECRYPT()` parst standardmäßig JSON; übergib `false` als drittes Argument, um den reinen String zurückzubekommen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafRjA1ch61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Cifrado","summary":"Cifra valores con ENCRYPT() y DECRYPT(), átalos al navegador de una petición con ENCRYPTREQ() y DECRYPTREQ(), y define el secreto.","markdown":"---\ntitle: Cifrado\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Cifrado\n\n> Cifra valores con ENCRYPT() y DECRYPT(), átalos al navegador de una petición con ENCRYPTREQ() y DECRYPTREQ(), y define el secreto.\n\n`ENCRYPT(value, key)` y `DECRYPT(value, key)` cifran cualquier valor con `CONF.secret` y tu clave. Los objetos se serializan a JSON, y `DECRYPT()` analiza JSON por defecto; pasa `false` como tercer argumento para recuperar la cadena tal cual.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafRjA1ch61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Chiffrement","summary":"Chiffre des valeurs avec ENCRYPT() et DECRYPT(), lie-les au navigateur d'une requête avec ENCRYPTREQ() et DECRYPTREQ(), et définis le secret.","markdown":"---\ntitle: Chiffrement\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Chiffrement\n\n> Chiffre des valeurs avec ENCRYPT() et DECRYPT(), lie-les au navigateur d'une requête avec ENCRYPTREQ() et DECRYPTREQ(), et définis le secret.\n\n`ENCRYPT(value, key)` et `DECRYPT(value, key)` chiffrent n'importe quelle valeur avec `CONF.secret` et ta clé. Les objets sont sérialisés en JSON, et `DECRYPT()` analyse le JSON par défaut ; passe `false` comme troisième argument pour récupérer la chaîne brute.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafRjA1ch61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Cifratura","summary":"Cifra i valori con ENCRYPT() e DECRYPT(), legali al browser di una richiesta con ENCRYPTREQ() e DECRYPTREQ() e imposta il secret.","markdown":"---\ntitle: Cifratura\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Cifratura\n\n> Cifra i valori con ENCRYPT() e DECRYPT(), legali al browser di una richiesta con ENCRYPTREQ() e DECRYPTREQ() e imposta il secret.\n\n`ENCRYPT(value, key)` e `DECRYPT(value, key)` cifrano qualsiasi valore con `CONF.secret` e la tua chiave. Gli oggetti vengono serializzati in JSON e `DECRYPT()` analizza il JSON per impostazione predefinita; passa `false` come terzo argomento per riottenere la stringa semplice.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafRjA1ch61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/encryption/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Šifrovanie","summary":"Šifruj hodnoty pomocou ENCRYPT() a DECRYPT(), viaž ich na prehliadač požiadavky pomocou ENCRYPTREQ() a DECRYPTREQ() a nastav secret.","markdown":"---\ntitle: \"Šifrovanie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/encryption/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Šifrovanie\n\n> Šifruj hodnoty pomocou ENCRYPT() a DECRYPT(), viaž ich na prehliadač požiadavky pomocou ENCRYPTREQ() a DECRYPTREQ() a nastav secret.\n\n`ENCRYPT(value, key)` a `DECRYPT(value, key)` zašifrujú ľubovoľnú hodnotu pomocou `CONF.secret` a tvojho kľúča. Objekty sa serializujú do JSON a `DECRYPT()` predvolene parsuje JSON; ak chceš späť obyčajný reťazec, odovzdaj ako tretí argument `false`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JafjmW2DX60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Middleware","summary":"Run code before routes and files with MIDDLEWARE(), in a route or for many routes at once with USE().","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Run code before routes and files with MIDDLEWARE(), in a route or for many routes at once with USE().\n\n## Defining a middleware\n\n`MIDDLEWARE(name, fn)` registers a function under a name. The function receives one argument, `$`, an instance of [MiddlewareOptions](../../reference/middleware/). Call `$.next()` to continue, or answer the request with `$.res` and do not call it:\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nA middleware must always call `$.next()`, `$.cancel()`, or respond. If it does none of them, the request waits until it times out. `$.next(err)` with an `Error` or an `ErrorBuilder` responds with an error 500. `$.next(false)` and `$.cancel()` stop the chain without running the action.\n\n`NEWMIDDLEWARE()` is the same function under its newer name. Passing `null` as the function removes the middleware and unassigns it from all routes:\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nPut middleware into the `/middleware/` directory (the config key `directory_middleware`). Each file is loaded like a controller, so register the middleware in `exports.install`:\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Using a middleware in a route\n\nAdd the name with `#` (or `&`) to the flags of a route. The middleware runs after the route has been matched and before the action, in the order of the flags:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nHTTP routes also accept the inline form in the URL:\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nAn object in the flags becomes `$.options` in the middleware. In this way, one middleware can be configured for each route:\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nFor routes, `$.controller` is the controller of the request and `$.params` holds the route parameters. See [Routing](../routing/) for the other flags.\n\n## Global middleware\n\n`USE(name, [url], [types], [first])` assigns a middleware to many routes at once. Without `url` and `types`, it runs for **every** request, static files included, before the routing:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nWith `types`, the middleware runs only for one kind of request. `web` means dynamic routes, `file` means static files and file routes, and `websocket` means WebSocket routes (`all` or `*` means every request):\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nWith a `url`, the middleware is added to the routes that already exist and whose URL starts with it. `USE()` waits until the application is loaded, so it sees all the routes from controllers. `first: true` puts the middleware before the others. The third argument of `MIDDLEWARE(name, fn, types, first)` calls `USE(name, '', types, first)` for you:\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nThe order is: middleware of all requests, then middleware of static files (for files), or for routes the middleware of the route, then the middleware of all dynamic routes, then the action.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"JafjmW2DX60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Middleware","summary":"Führe Code vor Routen und Dateien mit MIDDLEWARE() aus, in einer Route oder mit USE() für viele Routen auf einmal.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Führe Code vor Routen und Dateien mit MIDDLEWARE() aus, in einer Route oder mit USE() für viele Routen auf einmal.\n\n## Eine Middleware definieren\n\n`MIDDLEWARE(name, fn)` registriert eine Funktion unter einem Namen. Die Funktion erhält ein Argument, `$`, eine Instanz von [MiddlewareOptions](../../reference/middleware/). Rufe `$.next()` auf, um fortzufahren, oder beantworte den Request mit `$.res` und rufe es nicht auf:\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nEine Middleware muss immer `$.next()` oder `$.cancel()` aufrufen oder antworten. Tut sie nichts davon, wartet der Request, bis er in einen Timeout läuft. `$.next(err)` mit einem `Error` oder einem `ErrorBuilder` antwortet mit einem Fehler 500. `$.next(false)` und `$.cancel()` stoppen die Kette, ohne die Action auszuführen.\n\n`NEWMIDDLEWARE()` ist dieselbe Funktion unter ihrem neueren Namen. Wird `null` als Funktion übergeben, wird die Middleware entfernt und von allen Routen gelöst:\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nLege Middleware in das Verzeichnis `/middleware/` (der Konfigurationsschlüssel `directory_middleware`). Jede Datei wird wie ein Controller geladen, registriere die Middleware also in `exports.install`:\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Eine Middleware in einer Route verwenden\n\nFüge den Namen mit `#` (oder `&`) zu den Flags einer Route hinzu. Die Middleware läuft, nachdem die Route gefunden wurde, und vor der Action, in der Reihenfolge der Flags:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nHTTP-Routen akzeptieren auch die Inline-Form in der URL:\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nEin Objekt in den Flags wird in der Middleware zu `$.options`. So lässt sich eine Middleware für jede Route konfigurieren:\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nBei Routen ist `$.controller` der Controller des Requests, und `$.params` enthält die Parameter der Route. Siehe [Routing](../routing/) für die anderen Flags.\n\n## Globale Middleware\n\n`USE(name, [url], [types], [first])` weist eine Middleware vielen Routen auf einmal zu. Ohne `url` und `types` läuft sie für **jeden** Request, statische Dateien eingeschlossen, vor dem Routing:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nMit `types` läuft die Middleware nur für eine Art von Request. `web` bedeutet dynamische Routen, `file` bedeutet statische Dateien und Datei-Routen, und `websocket` bedeutet WebSocket-Routen (`all` oder `*` bedeutet jeden Request):\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nMit einer `url` wird die Middleware zu den bereits existierenden Routen hinzugefügt, deren URL damit beginnt. `USE()` wartet, bis die Anwendung geladen ist, sodass es alle Routen aus den Controllern sieht. `first: true` setzt die Middleware vor die anderen. Das dritte Argument von `MIDDLEWARE(name, fn, types, first)` ruft `USE(name, '', types, first)` für dich auf:\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nDie Reihenfolge ist: Middleware aller Requests, dann Middleware statischer Dateien (bei Dateien), oder bei Routen die Middleware der Route, dann die Middleware aller dynamischen Routen, dann die Action.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"JafjmW2DX60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Middleware","summary":"Ejecuta código antes de las rutas y los archivos con MIDDLEWARE(), en una ruta o en muchas a la vez con USE().","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Ejecuta código antes de las rutas y los archivos con MIDDLEWARE(), en una ruta o en muchas a la vez con USE().\n\n## Definir un middleware\n\n`MIDDLEWARE(name, fn)` registra una función bajo un nombre. La función recibe un argumento, `$`, una instancia de [MiddlewareOptions](../../reference/middleware/). Llama a `$.next()` para continuar, o responde a la petición con `$.res` y no lo llames:\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nUn middleware siempre debe llamar a `$.next()`, a `$.cancel()` o responder. Si no hace nada de eso, la petición espera hasta que se agota el tiempo. `$.next(err)` con un `Error` o un `ErrorBuilder` responde con un error 500. `$.next(false)` y `$.cancel()` detienen la cadena sin ejecutar la acción.\n\n`NEWMIDDLEWARE()` es la misma función con su nombre más reciente. Pasar `null` como función elimina el middleware y lo desasigna de todas las rutas:\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nPon el middleware en el directorio `/middleware/` (la clave de configuración `directory_middleware`). Cada archivo se carga como un controlador, así que registra el middleware en `exports.install`:\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Usar un middleware en una ruta\n\nAñade el nombre con `#` (o `&`) a los flags de una ruta. El middleware se ejecuta después de que la ruta coincida y antes de la acción, en el orden de los flags:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nLas rutas HTTP también aceptan la forma en línea en la URL:\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nUn objeto en los flags se convierte en `$.options` en el middleware. Así, un mismo middleware se puede configurar para cada ruta:\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nPara las rutas, `$.controller` es el controlador de la petición y `$.params` contiene los parámetros de la ruta. Consulta [Enrutamiento](../routing/) para los demás flags.\n\n## Middleware global\n\n`USE(name, [url], [types], [first])` asigna un middleware a muchas rutas a la vez. Sin `url` ni `types`, se ejecuta para **cada** petición, archivos estáticos incluidos, antes del enrutamiento:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nCon `types`, el middleware se ejecuta solo para un tipo de petición. `web` significa rutas dinámicas, `file` significa archivos estáticos y rutas de archivo, y `websocket` significa rutas WebSocket (`all` o `*` significa cada petición):\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nCon una `url`, el middleware se añade a las rutas que ya existen y cuya URL empieza por ella. `USE()` espera a que la aplicación esté cargada, así que ve todas las rutas de los controladores. `first: true` pone el middleware antes que los demás. El tercer argumento de `MIDDLEWARE(name, fn, types, first)` llama a `USE(name, '', types, first)` por ti:\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nEl orden es: el middleware de todas las peticiones; luego el middleware de los archivos estáticos (para archivos) o, para las rutas, el middleware de la ruta y después el middleware de todas las rutas dinámicas; y por último la acción.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"JafjmW2DX60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Middleware","summary":"Exécute du code avant les routes et les fichiers avec MIDDLEWARE(), dans une route ou pour plusieurs routes à la fois avec USE().","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Exécute du code avant les routes et les fichiers avec MIDDLEWARE(), dans une route ou pour plusieurs routes à la fois avec USE().\n\n## Définir un middleware\n\n`MIDDLEWARE(name, fn)` enregistre une fonction sous un nom. La fonction reçoit un argument, `$`, une instance de [MiddlewareOptions](../../reference/middleware/). Appelle `$.next()` pour continuer, ou réponds à la requête avec `$.res` sans l'appeler :\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nUn middleware doit toujours appeler `$.next()`, `$.cancel()`, ou répondre. S'il ne fait rien de tout cela, la requête attend jusqu'à expiration du délai. `$.next(err)` avec une `Error` ou un `ErrorBuilder` répond avec une erreur 500. `$.next(false)` et `$.cancel()` arrêtent la chaîne sans exécuter l'action.\n\n`NEWMIDDLEWARE()` est la même fonction sous son nom plus récent. Passer `null` comme fonction supprime le middleware et le retire de toutes les routes :\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nPlace les middlewares dans le répertoire `/middleware/` (la clé de configuration `directory_middleware`). Chaque fichier est chargé comme un contrôleur ; enregistre donc le middleware dans `exports.install` :\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Utiliser un middleware dans une route\n\nAjoute le nom avec `#` (ou `&`) aux flags d'une route. Le middleware s'exécute une fois la route trouvée et avant l'action, dans l'ordre des flags :\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nLes routes HTTP acceptent aussi la forme en ligne dans l'URL :\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nUn objet dans les flags devient `$.options` dans le middleware. Ainsi, un même middleware peut être configuré pour chaque route :\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nPour les routes, `$.controller` est le contrôleur de la requête et `$.params` contient les paramètres de la route. Voir [Routage](../routing/) pour les autres flags.\n\n## Middleware global\n\n`USE(name, [url], [types], [first])` assigne un middleware à de nombreuses routes à la fois. Sans `url` ni `types`, il s'exécute pour **chaque** requête, fichiers statiques compris, avant le routage :\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nAvec `types`, le middleware ne s'exécute que pour un type de requête. `web` désigne les routes dynamiques, `file` les fichiers statiques et les routes de fichiers, et `websocket` les routes WebSocket (`all` ou `*` désigne toutes les requêtes) :\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nAvec une `url`, le middleware est ajouté aux routes qui existent déjà et dont l'URL commence par celle-ci. `USE()` attend que l'application soit chargée ; il voit donc toutes les routes des contrôleurs. `first: true` place le middleware avant les autres. Le troisième argument de `MIDDLEWARE(name, fn, types, first)` appelle `USE(name, '', types, first)` pour toi :\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nL'ordre est le suivant : les middlewares de toutes les requêtes, puis les middlewares des fichiers statiques (pour les fichiers), ou pour les routes le middleware de la route, puis les middlewares de toutes les routes dynamiques, puis l'action.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"JafjmW2DX60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Middleware","summary":"Esegui codice prima di route e file con MIDDLEWARE(), in una route o in molte route insieme con USE().","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Esegui codice prima di route e file con MIDDLEWARE(), in una route o in molte route insieme con USE().\n\n## Definire un middleware\n\n`MIDDLEWARE(name, fn)` registra una funzione sotto un nome. La funzione riceve un argomento, `$`, un'istanza di [MiddlewareOptions](../../reference/middleware/). Chiama `$.next()` per proseguire, oppure rispondi alla richiesta con `$.res` e non chiamarlo:\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nUn middleware deve sempre chiamare `$.next()`, `$.cancel()` o rispondere. Se non fa nessuna di queste cose, la richiesta resta in attesa finché non va in timeout. `$.next(err)` con un `Error` o un `ErrorBuilder` risponde con un errore 500. `$.next(false)` e `$.cancel()` fermano la catena senza eseguire l'azione.\n\n`NEWMIDDLEWARE()` è la stessa funzione con il nome più recente. Passare `null` come funzione rimuove il middleware e lo scollega da tutte le route:\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nMetti i middleware nella directory `/middleware/` (la chiave di configurazione `directory_middleware`). Ogni file viene caricato come un controller, quindi registra il middleware in `exports.install`:\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Usare un middleware in una route\n\nAggiungi il nome con `#` (o `&`) ai flag di una route. Il middleware viene eseguito dopo che la route è stata individuata e prima dell'azione, nell'ordine dei flag:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nLe route HTTP accettano anche la forma inline nell'URL:\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nUn oggetto nei flag diventa `$.options` nel middleware. In questo modo, un middleware può essere configurato per ogni route:\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nPer le route, `$.controller` è il controller della richiesta e `$.params` contiene i parametri della route. Vedi [Routing](../routing/) per gli altri flag.\n\n## Middleware globale\n\n`USE(name, [url], [types], [first])` assegna un middleware a molte route contemporaneamente. Senza `url` e `types`, viene eseguito per **ogni** richiesta, file statici compresi, prima del routing:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nCon `types`, il middleware viene eseguito solo per un tipo di richiesta. `web` indica le route dinamiche, `file` indica i file statici e le file route, e `websocket` indica le route WebSocket (`all` o `*` indica ogni richiesta):\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nCon un `url`, il middleware viene aggiunto alle route che esistono già e il cui URL inizia con esso. `USE()` attende che l'applicazione sia caricata, così vede tutte le route dei controller. `first: true` mette il middleware prima degli altri. Il terzo argomento di `MIDDLEWARE(name, fn, types, first)` chiama `USE(name, '', types, first)` al posto tuo:\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nL'ordine è: middleware di tutte le richieste, poi middleware dei file statici (per i file), oppure per le route il middleware della route, poi il middleware di tutte le route dinamiche, poi l'azione.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"JafjmW2DX60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/middleware/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Middleware","summary":"Spúšťaj kód pred trasami a súbormi cez MIDDLEWARE(), v jednej trase alebo vo viacerých naraz cez USE().","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/middleware/\nupdated: 2026-11-16T15:50:00.282Z\n---\n\n# Middleware\n\n> Spúšťaj kód pred trasami a súbormi cez MIDDLEWARE(), v jednej trase alebo vo viacerých naraz cez USE().\n\n## Definícia middleware\n\n`MIDDLEWARE(name, fn)` zaregistruje funkciu pod názvom. Funkcia dostane jeden argument, `$`, inštanciu [MiddlewareOptions](../../reference/middleware/). Zavolaj `$.next()` na pokračovanie, alebo odpovedz na požiadavku cez `$.res` a `$.next()` nevolaj:\n\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\nMiddleware musí vždy zavolať `$.next()`, `$.cancel()` alebo odpovedať. Ak neurobí nič z toho, požiadavka čaká, kým nevyprší časový limit. `$.next(err)` s `Error` alebo `ErrorBuilder` odpovie chybou 500. `$.next(false)` a `$.cancel()` zastavia reťaz bez spustenia akcie.\n\n`NEWMIDDLEWARE()` je tá istá funkcia pod novším názvom. Odovzdanie `null` ako funkcie middleware odstráni a odpojí ho od všetkých trás:\n\n```js\nMIDDLEWARE('apikey', null);\n```\n\nMiddleware daj do adresára `/middleware/` (konfiguračný kľúč `directory_middleware`). Každý súbor sa načíta ako kontrolér, preto middleware zaregistruj v `exports.install`:\n\n```js\n// /middleware/apikey.js\nexports.install = function() {\n\tMIDDLEWARE('apikey', function($) {\n\t\t$.next();\n\t});\n};\n```\n\n## Použitie middleware v trase\n\nPridaj názov s `#` (alebo `&`) do flagov trasy. Middleware sa spustí po tom, čo sa trasa zhodovala, a pred akciou, v poradí flagov:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n\tROUTE('POST /api/orders/', orders, ['#apikey', '#logger']);\n};\n```\n\nHTTP trasy akceptujú aj inline tvar v URL:\n\n```js\nROUTE('GET /api/products/ &apikey', products);\n```\n\nObjekt vo flagoch sa v middleware stane `$.options`. Takto môžeš jeden middleware nakonfigurovať pre každú trasu:\n\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n};\n```\n\nPri trasách je `$.controller` kontrolér požiadavky a `$.params` drží parametre trasy. Ostatné flagy nájdeš v [Smerovanie](../routing/).\n\n## Globálny middleware\n\n`USE(name, [url], [types], [first])` priradí middleware naraz mnohým trasám. Bez `url` a `types` sa spustí pre **každú** požiadavku, vrátane statických súborov, pred smerovaním:\n\n```js\nMIDDLEWARE('poweredby', function($) {\n\t$.res.setHeader('X-Server', 'MyApp');\n\t$.next();\n});\n\nUSE('poweredby');\n```\n\nS `types` sa middleware spustí len pre jeden druh požiadaviek. `web` znamená dynamické trasy, `file` znamená statické súbory a súborové trasy a `websocket` znamená WebSocket trasy (`all` alebo `*` znamená každú požiadavku):\n\n```js\n// Only dynamic routes\nUSE('apikey', ['web']);\n\n// Only routes whose URL starts with /api/\nUSE('apikey', '/api/', ['web']);\n```\n\nS `url` sa middleware pridá k trasám, ktoré už existujú a ktorých URL ním začína. `USE()` čaká, kým sa aplikácia načíta, takže vidí všetky trasy z kontrolérov. `first: true` dá middleware pred ostatné. Tretí argument `MIDDLEWARE(name, fn, types, first)` za teba zavolá `USE(name, '', types, first)`:\n\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nPoradie je: middleware všetkých požiadaviek, potom middleware statických súborov (pre súbory), alebo pri trasách middleware trasy, potom middleware všetkých dynamických trás, potom akcia.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:00.282Z"}
{"id":"Jafjnd2WX61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Static files","summary":"Serve the public directory, build the URLs of static files, map, merge and resize files, answer with file routes and localize static files.","markdown":"---\ntitle: Static files\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Static files\n\n> Serve the public directory, build the URLs of static files, map, merge and resize files, answer with file routes and localize static files.\n\n## The public directory\n\nEvery request whose path ends with a file extension is a static-file request. The framework looks for the file in `/public/` (the config key `directory_public`) and serves it when the extension is allowed in `static_accepts`. Other extensions answer 404. Paths that contain `../` are refused.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nAdd an extension with `ACCEPT()`, or with `static_accepts_custom` in the config file:\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nWhat happens to a file before it is sent:\n\n- `.js`, `.mjs` and `.css` files are minified when `allow_compile` is on (default). Files named like `*.min.js` or `*-min.css` are sent as they are.\n- Text types (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, plain text) are compressed with GZIP when `allow_gzip` is on and the client accepts it.\n- `.html` and `.htm` files are localized when `allow_localize` is on (default).\n- In release mode, the responses have `Cache-Control: public, max-age=11111111`, an `Expires` header one year ahead, `Last-Modified`, and an `ETag` built from `etag_version`. A request with a matching `If-Modified-Since` gets 304. In debug mode, files are sent with `no-cache`.\n\nThe framework keeps the processed files in `/tmp/`. `TOUCH(url)` forgets one cached file, and `TOUCH()` forgets all:\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URLs of static files\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` and the others build URLs from the config keys `static_url_script`, `static_url_style`, `static_url_image`, and so on. They also apply the `/versions` file, so you can change the URL of a file without changing your views:\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` adds a hash of the file content to its name when the application starts. `PATH.public(filename)` gives the absolute path of a file in the public directory.\n\n## Mapping, merging and resizing\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## File routes\n\nA file route answers static-file requests with your own function. Use `ROUTE('FILE ...')` or `FILE()`. The action receives `req` and `res`, not a controller:\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nThe URL can end with `*.ext` (one extension), `*` or `*.*` (any file under the path), or a full file name. When the second argument is a string, the route sends that file (an absolute path) with `res.file()`, or proxies an `http(s)://` URL.\n\nIn a file route, use `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()`, or `res.continue()` to serve the file from `public/` as usual. Middleware in file routes goes in the flags array (`['#name']`). `FILE404(fn)` handles static files that do not exist:\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## Localized static files\n\n`LOCALIZE(url)` sends the files under `url` through the translator, so `@(Text)` markers become texts in the language of the request. Set the language with `LOCALIZE(fn)`:\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Change content before compiling\n\n`MODIFY([filename], fn)` registers a function that changes the content of views, styles, scripts and localized static files before Total.js compiles them. It changes only the copy in memory, never the file on the disk. Return the new content:\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jafjnd2WX61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Statische Dateien","summary":"Liefere das öffentliche Verzeichnis aus, baue die URLs statischer Dateien, ordne Dateien zu, führe sie zusammen und skaliere sie, antworte mit Datei-Routen und lokalisiere statische Dateien.","markdown":"---\ntitle: Statische Dateien\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Statische Dateien\n\n> Liefere das öffentliche Verzeichnis aus, baue die URLs statischer Dateien, ordne Dateien zu, führe sie zusammen und skaliere sie, antworte mit Datei-Routen und lokalisiere statische Dateien.\n\n## Das Verzeichnis public\n\nJeder Request, dessen Pfad auf eine Dateiendung endet, ist ein Request nach einer statischen Datei. Das Framework sucht die Datei in `/public/` (Konfigurationsschlüssel `directory_public`) und liefert sie aus, wenn die Endung in `static_accepts` erlaubt ist. Andere Endungen antworten mit 404. Pfade, die `../` enthalten, werden abgelehnt.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nFüge eine Endung mit `ACCEPT()` hinzu oder mit `static_accepts_custom` in der Konfigurationsdatei:\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nWas mit einer Datei passiert, bevor sie gesendet wird:\n\n- `.js`-, `.mjs`- und `.css`-Dateien werden minifiziert, wenn `allow_compile` aktiv ist (Standard). Dateien mit Namen wie `*.min.js` oder `*-min.css` werden unverändert gesendet.\n- Texttypen (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, reiner Text) werden mit GZIP komprimiert, wenn `allow_gzip` aktiv ist und der Client es akzeptiert.\n- `.html`- und `.htm`-Dateien werden lokalisiert, wenn `allow_localize` aktiv ist (Standard).\n- Im Release-Modus haben die Responses `Cache-Control: public, max-age=11111111`, einen Header `Expires` ein Jahr in der Zukunft, `Last-Modified` und ein `ETag`, das aus `etag_version` gebildet wird. Ein Request mit passendem `If-Modified-Since` erhält 304. Im Debug-Modus werden Dateien mit `no-cache` gesendet.\n\nDas Framework hält die verarbeiteten Dateien in `/tmp/`. `TOUCH(url)` vergisst eine gecachte Datei, und `TOUCH()` vergisst alle:\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URLs statischer Dateien\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` und die anderen bilden URLs aus den Konfigurationsschlüsseln `static_url_script`, `static_url_style`, `static_url_image` und so weiter. Sie wenden auch die Datei `/versions` an, sodass du die URL einer Datei ändern kannst, ohne deine Views zu ändern:\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` fügt beim Start der Anwendung einen Hash des Dateiinhalts an ihren Namen an. `PATH.public(filename)` liefert den absoluten Pfad einer Datei im Verzeichnis public.\n\n## Mapping, Zusammenführen und Skalieren\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## Datei-Routen\n\nEine Datei-Route beantwortet Requests nach statischen Dateien mit deiner eigenen Funktion. Verwende `ROUTE('FILE ...')` oder `FILE()`. Die Action erhält `req` und `res`, keinen Controller:\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nDie URL kann auf `*.ext` (eine Endung), `*` oder `*.*` (jede Datei unter dem Pfad) oder einen vollständigen Dateinamen enden. Ist das zweite Argument ein String, sendet die Route diese Datei (ein absoluter Pfad) mit `res.file()` oder leitet eine URL `http(s)://` per Proxy weiter.\n\nIn einer Datei-Route verwendest du `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()` oder `res.continue()`, um die Datei wie gewohnt aus `public/` auszuliefern. Middleware in Datei-Routen gehört in das Flags-Array (`['#name']`). `FILE404(fn)` behandelt statische Dateien, die nicht existieren:\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## Lokalisierte statische Dateien\n\n`LOCALIZE(url)` schickt die Dateien unter `url` durch den Übersetzer, sodass `@(Text)`-Marker zu Texten in der Sprache des Requests werden. Die Sprache legst du mit `LOCALIZE(fn)` fest:\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Inhalt vor dem Kompilieren ändern\n\n`MODIFY([filename], fn)` registriert eine Funktion, die den Inhalt von Views, Styles, Skripten und lokalisierten statischen Dateien ändert, bevor Total.js sie kompiliert. Sie ändert nur die Kopie im Speicher, nie die Datei auf der Festplatte. Gib den neuen Inhalt zurück:\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jafjnd2WX61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Archivos estáticos","summary":"Sirve el directorio público, construye las URLs de los archivos estáticos, mapea, combina y redimensiona archivos, responde con rutas de archivo y localiza archivos estáticos.","markdown":"---\ntitle: \"Archivos estáticos\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Archivos estáticos\n\n> Sirve el directorio público, construye las URLs de los archivos estáticos, mapea, combina y redimensiona archivos, responde con rutas de archivo y localiza archivos estáticos.\n\n## El directorio público\n\nToda petición cuya ruta termina con una extensión de archivo es una petición de archivo estático. El framework busca el archivo en `/public/` (la clave de configuración `directory_public`) y lo sirve cuando la extensión está permitida en `static_accepts`. Las demás extensiones responden 404. Las rutas que contienen `../` se rechazan.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nAñade una extensión con `ACCEPT()`, o con `static_accepts_custom` en el archivo de configuración:\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nQué ocurre con un archivo antes de enviarlo:\n\n- Los archivos `.js`, `.mjs` y `.css` se minifican cuando `allow_compile` está activado (por defecto). Los archivos con nombres como `*.min.js` o `*-min.css` se envían tal cual.\n- Los tipos de texto (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, texto plano) se comprimen con GZIP cuando `allow_gzip` está activado y el cliente lo acepta.\n- Los archivos `.html` y `.htm` se localizan cuando `allow_localize` está activado (por defecto).\n- En modo release, las respuestas llevan `Cache-Control: public, max-age=11111111`, una cabecera `Expires` un año en el futuro, `Last-Modified` y un `ETag` construido a partir de `etag_version`. Una petición con un `If-Modified-Since` coincidente recibe 304. En modo debug, los archivos se envían con `no-cache`.\n\nEl framework guarda los archivos procesados en `/tmp/`. `TOUCH(url)` olvida un archivo en caché, y `TOUCH()` los olvida todos:\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URLs de archivos estáticos\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` y los demás construyen URLs a partir de las claves de configuración `static_url_script`, `static_url_style`, `static_url_image`, etc. También aplican el archivo `/versions`, así que puedes cambiar la URL de un archivo sin cambiar tus vistas:\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` añade un hash del contenido del archivo a su nombre cuando la aplicación arranca. `PATH.public(filename)` da la ruta absoluta de un archivo del directorio público.\n\n## Mapear, combinar y redimensionar\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## Rutas de archivo\n\nUna ruta de archivo responde a peticiones de archivos estáticos con tu propia función. Usa `ROUTE('FILE ...')` o `FILE()`. La acción recibe `req` y `res`, no un controlador:\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nLa URL puede terminar en `*.ext` (una extensión), `*` o `*.*` (cualquier archivo bajo la ruta), o un nombre de archivo completo. Cuando el segundo argumento es una cadena, la ruta envía ese archivo (una ruta absoluta) con `res.file()`, o hace de proxy de una URL `http(s)://`.\n\nEn una ruta de archivo, usa `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()` o `res.continue()` para servir el archivo desde `public/` como siempre. Los middleware de las rutas de archivo van en el array de flags (`['#name']`). `FILE404(fn)` gestiona los archivos estáticos que no existen:\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## Archivos estáticos localizados\n\n`LOCALIZE(url)` pasa los archivos bajo `url` por el traductor, de modo que los marcadores `@(Text)` se convierten en textos en el idioma de la petición. Define el idioma con `LOCALIZE(fn)`:\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Cambiar el contenido antes de compilar\n\n`MODIFY([filename], fn)` registra una función que cambia el contenido de vistas, estilos, scripts y archivos estáticos localizados antes de que Total.js los compile. Solo cambia la copia en memoria, nunca el archivo en disco. Devuelve el nuevo contenido:\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jafjnd2WX61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Fichiers statiques","summary":"Sers le répertoire public, construis les URL des fichiers statiques, mappe, fusionne et redimensionne des fichiers, réponds avec des routes de fichiers et localise les fichiers statiques.","markdown":"---\ntitle: Fichiers statiques\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Fichiers statiques\n\n> Sers le répertoire public, construis les URL des fichiers statiques, mappe, fusionne et redimensionne des fichiers, réponds avec des routes de fichiers et localise les fichiers statiques.\n\n## Le répertoire public\n\nToute requête dont le chemin se termine par une extension de fichier est une requête de fichier statique. Le framework cherche le fichier dans `/public/` (la clé de configuration `directory_public`) et le sert quand l'extension est autorisée dans `static_accepts`. Les autres extensions répondent 404. Les chemins qui contiennent `../` sont refusés.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nAjoute une extension avec `ACCEPT()`, ou avec `static_accepts_custom` dans le fichier de configuration :\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nCe qui arrive à un fichier avant son envoi :\n\n- Les fichiers `.js`, `.mjs` et `.css` sont minifiés quand `allow_compile` est activé (par défaut). Les fichiers nommés comme `*.min.js` ou `*-min.css` sont envoyés tels quels.\n- Les types texte (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, texte brut) sont compressés avec GZIP quand `allow_gzip` est activé et que le client l'accepte.\n- Les fichiers `.html` et `.htm` sont localisés quand `allow_localize` est activé (par défaut).\n- En mode release, les réponses ont `Cache-Control: public, max-age=11111111`, un en-tête `Expires` un an plus tard, `Last-Modified` et un `ETag` construit à partir de `etag_version`. Une requête avec un `If-Modified-Since` correspondant reçoit 304. En mode debug, les fichiers sont envoyés avec `no-cache`.\n\nLe framework conserve les fichiers traités dans `/tmp/`. `TOUCH(url)` oublie un fichier en cache, et `TOUCH()` les oublie tous :\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URL des fichiers statiques\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` et les autres construisent des URL à partir des clés de configuration `static_url_script`, `static_url_style`, `static_url_image`, etc. Elles appliquent aussi le fichier `/versions`, ce qui te permet de changer l'URL d'un fichier sans modifier tes vues :\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` ajoute un hash du contenu du fichier à son nom au démarrage de l'application. `PATH.public(filename)` donne le chemin absolu d'un fichier du répertoire public.\n\n## Mappage, fusion et redimensionnement\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## Routes de fichiers\n\nUne route de fichier répond aux requêtes de fichiers statiques avec ta propre fonction. Utilise `ROUTE('FILE ...')` ou `FILE()`. L'action reçoit `req` et `res`, pas un contrôleur :\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nL'URL peut se terminer par `*.ext` (une extension), `*` ou `*.*` (n'importe quel fichier sous le chemin), ou par un nom de fichier complet. Quand le deuxième argument est une chaîne, la route envoie ce fichier (un chemin absolu) avec `res.file()`, ou sert de proxy vers une URL `http(s)://`.\n\nDans une route de fichier, utilise `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()` ou `res.continue()` pour servir le fichier depuis `public/` comme d'habitude. Le middleware des routes de fichiers se place dans le tableau de flags (`['#name']`). `FILE404(fn)` gère les fichiers statiques qui n'existent pas :\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## Fichiers statiques localisés\n\n`LOCALIZE(url)` fait passer les fichiers situés sous `url` par le traducteur, si bien que les marqueurs `@(Text)` deviennent des textes dans la langue de la requête. Définis la langue avec `LOCALIZE(fn)` :\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Modifier le contenu avant la compilation\n\n`MODIFY([filename], fn)` enregistre une fonction qui modifie le contenu des vues, des styles, des scripts et des fichiers statiques localisés avant que Total.js ne les compile. Elle ne modifie que la copie en mémoire, jamais le fichier sur le disque. Renvoie le nouveau contenu :\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jafjnd2WX61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"File statici","summary":"Servi la directory pubblica, costruisci gli URL dei file statici, mappa, unisci e ridimensiona i file, rispondi con le file route e localizza i file statici.","markdown":"---\ntitle: File statici\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# File statici\n\n> Servi la directory pubblica, costruisci gli URL dei file statici, mappa, unisci e ridimensiona i file, rispondi con le file route e localizza i file statici.\n\n## La directory public\n\nOgni richiesta il cui percorso termina con un'estensione di file è una richiesta di file statico. Il framework cerca il file in `/public/` (la chiave di configurazione `directory_public`) e lo serve quando l'estensione è consentita in `static_accepts`. Le altre estensioni rispondono 404. I percorsi che contengono `../` vengono rifiutati.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nAggiungi un'estensione con `ACCEPT()`, oppure con `static_accepts_custom` nel file di configurazione:\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nCosa succede a un file prima che venga inviato:\n\n- I file `.js`, `.mjs` e `.css` vengono minificati quando `allow_compile` è attivo (predefinito). I file con nomi come `*.min.js` o `*-min.css` vengono inviati così come sono.\n- I tipi di testo (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, testo semplice) vengono compressi con GZIP quando `allow_gzip` è attivo e il client lo accetta.\n- I file `.html` e `.htm` vengono localizzati quando `allow_localize` è attivo (predefinito).\n- In modalità release, le risposte hanno `Cache-Control: public, max-age=11111111`, un header `Expires` un anno avanti, `Last-Modified` e un `ETag` costruito da `etag_version`. Una richiesta con un `If-Modified-Since` corrispondente riceve 304. In modalità debug, i file vengono inviati con `no-cache`.\n\nIl framework conserva i file elaborati in `/tmp/`. `TOUCH(url)` dimentica un file in cache e `TOUCH()` li dimentica tutti:\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URL dei file statici\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` e gli altri costruiscono gli URL dalle chiavi di configurazione `static_url_script`, `static_url_style`, `static_url_image` e così via. Applicano anche il file `/versions`, così puoi cambiare l'URL di un file senza modificare le tue viste:\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` aggiunge al nome del file un hash del suo contenuto all'avvio dell'applicazione. `PATH.public(filename)` fornisce il percorso assoluto di un file nella directory public.\n\n## Mappatura, unione e ridimensionamento\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## Route di file\n\nUna route di file risponde alle richieste di file statici con una tua funzione. Usa `ROUTE('FILE ...')` o `FILE()`. L'azione riceve `req` e `res`, non un controller:\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nL'URL può terminare con `*.ext` (un'estensione), `*` o `*.*` (qualsiasi file sotto il percorso), oppure con un nome di file completo. Quando il secondo argomento è una stringa, la route invia quel file (un percorso assoluto) con `res.file()`, oppure fa da proxy verso un URL `http(s)://`.\n\nIn una route di file, usa `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()` oppure `res.continue()` per servire il file da `public/` come di consueto. I middleware nelle route di file vanno nell'array dei flag (`['#name']`). `FILE404(fn)` gestisce i file statici che non esistono:\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## File statici localizzati\n\n`LOCALIZE(url)` fa passare i file sotto `url` attraverso il traduttore, così i marcatori `@(Text)` diventano testi nella lingua della richiesta. Imposta la lingua con `LOCALIZE(fn)`:\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Modificare il contenuto prima della compilazione\n\n`MODIFY([filename], fn)` registra una funzione che modifica il contenuto di viste, stili, script e file statici localizzati prima che Total.js li compili. Modifica solo la copia in memoria, mai il file su disco. Restituisci il nuovo contenuto:\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jafjnd2WX61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/static-files/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Statické súbory","summary":"Poskytuj verejný adresár, vytváraj URL statických súborov, mapuj, zlučuj a meň veľkosť súborov, odpovedaj cez súborové trasy a lokalizuj statické súbory.","markdown":"---\ntitle: \"Statické súbory\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/static-files/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Statické súbory\n\n> Poskytuj verejný adresár, vytváraj URL statických súborov, mapuj, zlučuj a meň veľkosť súborov, odpovedaj cez súborové trasy a lokalizuj statické súbory.\n\n## Verejný priečinok\n\nKaždá požiadavka, ktorej cesta končí príponou súboru, je požiadavka na statický súbor. Framework hľadá súbor v `/public/` (kľúč konfigurácie `directory_public`) a obslúži ho, keď je prípona povolená v `static_accepts`. Ostatné prípony odpovedajú 404. Cesty, ktoré obsahujú `../`, sa odmietnu.\n\n```text\n/public/css/default.css  -->  GET /css/default.css\n/public/img/logo.png     -->  GET /img/logo.png\n```\n\nPríponu pridáš pomocou `ACCEPT()` alebo cez `static_accepts_custom` v konfiguračnom súbore:\n\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n```text\nstatic_accepts_custom : glb, usdz\n```\n\nČo sa so súborom stane pred odoslaním:\n\n- Súbory `.js`, `.mjs` a `.css` sa minifikujú, keď je zapnuté `allow_compile` (predvolene). Súbory s názvom ako `*.min.js` alebo `*-min.css` sa posielajú tak, ako sú.\n- Textové typy (HTML, CSS, JavaScript, JSON, XML, SVG, Markdown, obyčajný text) sa komprimujú pomocou GZIP, keď je zapnuté `allow_gzip` a klient to akceptuje.\n- Súbory `.html` a `.htm` sa lokalizujú, keď je zapnuté `allow_localize` (predvolene).\n- V režime release majú odpovede `Cache-Control: public, max-age=11111111`, hlavičku `Expires` o rok dopredu, `Last-Modified` a `ETag` zostavený z `etag_version`. Požiadavka so zhodným `If-Modified-Since` dostane 304. V režime debug sa súbory posielajú s `no-cache`.\n\nSpracované súbory framework drží v `/tmp/`. `TOUCH(url)` zabudne jeden súbor v cache a `TOUCH()` zabudne všetky:\n\n```js\nTOUCH('/css/default.css');\n```\n\n## URL statických súborov\n\n`F.public_js()`, `F.public_css()`, `F.public_image()` a ďalšie zostavujú URL z kľúčov konfigurácie `static_url_script`, `static_url_style`, `static_url_image` atď. Uplatňujú aj súbor `/versions`, takže URL súboru môžeš zmeniť bez zmeny svojich view:\n\n```js\nF.public_js('app.js');      // /js/app.js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n```text\n// /versions\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n```\n\n`auto` pridá pri štarte aplikácie k názvu súboru hash jeho obsahu. `PATH.public(filename)` vráti absolútnu cestu k súboru vo verejnom priečinku.\n\n## Mapovanie, spájanie a zmena veľkosti\n\n```js\n// A URL served from another file or directory\nMAP('/favicon.ico', '~/assets/favicon.ico');\n\n// Several files served as one\nMERGE('/js/bundle.js', '/js/a.js', '/js/b.js');\n\n// /img/small/*.jpg is made from /public/img/*.jpg\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n## Súborové trasy\n\nSúborová trasa odpovedá na požiadavky na statické súbory tvojou vlastnou funkciou. Použi `ROUTE('FILE ...')` alebo `FILE()`. Akcia dostane `req` a `res`, nie kontrolér:\n\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', pdf, ['#apikey']);\n\tROUTE('FILE /thumbnails/*.jpg', thumbnail);\n\tROUTE('FILE /favicon.ico', PATH.public('img/favicon.ico'));\n};\n\nfunction pdf(req, res) {\n\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)), 'document.pdf');\n}\n\nfunction thumbnail(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t});\n}\n```\n\nURL môže končiť na `*.ext` (jedna prípona), `*` alebo `*.*` (ľubovoľný súbor pod cestou) alebo na celý názov súboru. Keď je druhý argument reťazec, trasa pošle tento súbor (absolútna cesta) pomocou `res.file()` alebo urobí proxy na URL `http(s)://`.\n\nV súborovej trase použi `res.file()`, `res.image()`, `res.filefs()`, `res.imagefs()`, `res.stream()` alebo `res.continue()`, ak chceš súbor obslúžiť z `public/` ako obvykle. Middleware v súborových trasách patrí do poľa flagov (`['#name']`). `FILE404(fn)` obsluhuje statické súbory, ktoré neexistujú:\n\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'png') {\n\t\tres.file(PATH.public('img/empty.png'));\n\t\treturn true;\n\t}\n});\n```\n\n## Lokalizované statické súbory\n\n`LOCALIZE(url)` pošle súbory pod `url` cez prekladač, takže značky `@(Text)` sa zmenia na texty v jazyku požiadavky. Jazyk nastavíš pomocou `LOCALIZE(fn)`:\n\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n## Zmena obsahu pred kompiláciou\n\n`MODIFY([filename], fn)` zaregistruje funkciu, ktorá mení obsah view, štýlov, skriptov a lokalizovaných statických súborov predtým, ako ich Total.js skompiluje. Mení iba kópiu v pamäti, nikdy súbor na disku. Vráť nový obsah:\n\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('{year}', NOW.getFullYear() + '');\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"WebSockets","summary":"Declare WebSocket routes, handle clients and messages in the WebSocket controller, and connect to WebSocket servers with WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSockets\n\n> Declare WebSocket routes, handle clients and messages in the WebSocket controller, and connect to WebSocket servers with WEBSOCKETCLIENT().\n\nA WebSocket route keeps a connection open between the browser and the server. In Total.js you declare it with `ROUTE()` and the `SOCKET` method. The action of the route does not answer a request: it runs **once**, when the first client connects, and its `this` is a **WebSocket controller** shared by every client of that route.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nThe full list of properties and methods is in the reference of [WebSockets](../../reference/websockets/).\n\n## Declaring a route\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` registers the route. `WS` and `WSS` are accepted as aliases of `SOCKET`. A `+` before the method allows only signed-in users and a `-` only anonymous users, as in other routes:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nDynamic parts of the URL arrive as arguments of the action and in `this.params`. The `length` argument (or a number in the flags) is the maximum size of one message in **kB**. The default comes from `CONF.default_websocket_maxlength` (`2` kB). A bigger frame closes the connection with code `1009`.\n\n## Flags\n\n| Flag | Meaning |\n| --- | --- |\n| `json` | Messages are JSON (the default). Incoming messages are parsed, outgoing objects are serialized. |\n| `text` or `plain` | Messages are strings. |\n| `binary` | Messages are binary; `message` receives a `Buffer`. |\n| `raw` | Turns off `json` and `binary`; messages are handled as text. |\n| `buffer` | The `message` event always receives the raw `Buffer`. |\n| `authorize`, `logged` | Only signed-in users (the same as `+`). |\n| `unauthorize`, `unlogged` | Only anonymous users (the same as `-`). |\n| `@role` | Marks a role; the route also becomes `authorize`. |\n| `http://…`, `https://…` | Allowed origins. The `Origin` header must contain one of them. |\n| `#name` or `&name` | Middleware run before the connection is accepted. |\n| `id:name` | An identifier of the route. |\n| `debug`, `release`, `http`, `https` | Limit the route to a mode or a protocol. |\n| any other word | A required sub-protocol: the client must send it in `Sec-WebSocket-Protocol`. |\n| a number | The maximum message size in kB. |\n| an object | Options passed to the middleware. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nThis route accepts only clients from `https://www.example.com` that ask for the `chat` sub-protocol, and messages up to 128 kB.\n\n## How connections are grouped\n\nEvery route has one controller per URL. The first client creates it and runs the action; later clients on the same URL join the existing controller, and the action is not called again. That is why the action registers events instead of answering.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nWithout more code the controller stays in memory after the last client leaves. Call `this.autodestroy()` to destroy it 5 seconds after the last client disconnects; the next client creates a new one and the action runs again:\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Receiving and sending\n\nWith the default `json` flag, `message` receives a parsed object; invalid JSON is ignored. `client.send(obj)` sends to one client and `this.send(obj)` sends to all clients of the controller. The second argument of `this.send()` filters the receivers:\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` returns the first client for which `fn` returns `true`, and `this.clients()` returns all clients as an array. `this.online` is the number of connected clients and `this.connections` maps client ids to clients.\n\n## The client of a connection\n\nEvery connected client has `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` and `protocol`. `user` is the value accepted by your `AUTH()` delegate:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nA client that fails authorization is closed with code `4001`, a URL without a route with `4004`, and invalid URL parameters with `4000`.\n\n`client.close([message], [code])` closes one client and `this.close([message], [code])` closes all of them. The default code is `1000`.\n\n## Ping and stale connections\n\nThe framework pings every connected client every `CONF.default_interval_websocket_ping` milliseconds (default `20000`). The answer sets `client.latency`. A client that did not answer, or whose latency is higher than `CONF.default_websocket_maxlatency` (default `2000` ms), is closed at the next round. Set `default_websocket_maxlatency` to `0` to turn the pinger off.\n\n## WebSocket API\n\nA route can process `API` routes over the socket. Declare the API with `@name` and use the same name in the socket route:\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nA `SOCKET` route with `@name` and no action calls `this.api('@name')` and `this.autodestroy()` for you. The client sends `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` and gets the same object back with `success: true` and `data`, or `error: true` and the errors.\n\n## Connecting from the server\n\n`WEBSOCKETCLIENT()` creates a WebSocket client, for example to connect one Total.js app to another:\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` is `json` by default; use `text`, `binary` or `buffer` for other data. The client reconnects 3 seconds after the connection is lost (`options.reconnect`); `client.close()` stops reconnecting and `client.destroy()` frees the client. `client.api(schema, data, callback)` calls the WebSocket API of the server:\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Configuration\n\n| Key | Default | Meaning |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Enables WebSocket routes. |\n| `allow_websocket_compression` | `true` | Allows `permessage-deflate` compression. |\n| `default_websocket_maxlength` | `2` | Maximum message size in kB. |\n| `default_websocket_maxlatency` | `2000` | Maximum ping latency in ms; `0` disables the pinger. |\n| `default_interval_websocket_ping` | `20000` | Interval of the ping in ms. |\n| `default_websocket_encodedecode` | `false` | Encodes messages with `encodeURIComponent()` and decodes them. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"WebSockets","summary":"Deklariere WebSocket-Routen, verarbeite Clients und Nachrichten im WebSocket-Controller und verbinde dich mit WEBSOCKETCLIENT() zu WebSocket-Servern.","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSockets\n\n> Deklariere WebSocket-Routen, verarbeite Clients und Nachrichten im WebSocket-Controller und verbinde dich mit WEBSOCKETCLIENT() zu WebSocket-Servern.\n\nEine WebSocket-Route hält eine Verbindung zwischen Browser und Server offen. In Total.js deklarierst du sie mit `ROUTE()` und der Methode `SOCKET`. Die Action der Route beantwortet keinen Request: Sie läuft **einmal**, wenn sich der erste Client verbindet, und ihr `this` ist ein **WebSocket-Controller**, den alle Clients dieser Route teilen.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nDie vollständige Liste der Eigenschaften und Methoden steht in der Referenz zu [WebSockets](../../reference/websockets/).\n\n## Eine Route deklarieren\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` registriert die Route. `WS` und `WSS` werden als Aliase von `SOCKET` akzeptiert. Ein `+` vor der Methode erlaubt nur angemeldete Benutzer und ein `-` nur anonyme Benutzer, wie bei anderen Routen:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nDynamische Teile der URL kommen als Argumente der Action und in `this.params` an. Das Argument `length` (oder eine Zahl in den Flags) ist die maximale Größe einer Nachricht in **kB**. Der Standardwert kommt aus `CONF.default_websocket_maxlength` (`2` kB). Ein größerer Frame schließt die Verbindung mit dem Code `1009`.\n\n## Flags\n\n| Flag | Bedeutung |\n| --- | --- |\n| `json` | Nachrichten sind JSON (Standard). Eingehende Nachrichten werden geparst, ausgehende Objekte serialisiert. |\n| `text` oder `plain` | Nachrichten sind Strings. |\n| `binary` | Nachrichten sind binär; `message` erhält einen `Buffer`. |\n| `raw` | Schaltet `json` und `binary` ab; Nachrichten werden als Text behandelt. |\n| `buffer` | Das Event `message` erhält immer den rohen `Buffer`. |\n| `authorize`, `logged` | Nur angemeldete Benutzer (wie `+`). |\n| `unauthorize`, `unlogged` | Nur anonyme Benutzer (wie `-`). |\n| `@role` | Kennzeichnet eine Rolle; die Route wird außerdem `authorize`. |\n| `http://…`, `https://…` | Erlaubte Origins. Der Header `Origin` muss einen davon enthalten. |\n| `#name` oder `&name` | Middleware, die ausgeführt wird, bevor die Verbindung akzeptiert wird. |\n| `id:name` | Ein Bezeichner der Route. |\n| `debug`, `release`, `http`, `https` | Beschränken die Route auf einen Modus oder ein Protokoll. |\n| jedes andere Wort | Ein erforderliches Subprotokoll: Der Client muss es in `Sec-WebSocket-Protocol` senden. |\n| eine Zahl | Die maximale Nachrichtengröße in kB. |\n| ein Objekt | Optionen, die an die Middleware übergeben werden. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nDiese Route akzeptiert nur Clients von `https://www.example.com`, die das Subprotokoll `chat` anfordern, und Nachrichten bis 128 kB.\n\n## Wie Verbindungen gruppiert werden\n\nJede Route hat einen Controller pro URL. Der erste Client erzeugt ihn und führt die Action aus; spätere Clients auf derselben URL treten dem bestehenden Controller bei, und die Action wird nicht erneut aufgerufen. Deshalb registriert die Action Events, statt zu antworten.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nOhne weiteren Code bleibt der Controller im Speicher, nachdem der letzte Client gegangen ist. Rufe `this.autodestroy()` auf, um ihn 5 Sekunden nach dem Trennen des letzten Clients zu zerstören; der nächste Client erzeugt einen neuen, und die Action läuft erneut:\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Empfangen und Senden\n\nMit dem Standard-Flag `json` erhält `message` ein geparstes Objekt; ungültiges JSON wird ignoriert. `client.send(obj)` sendet an einen Client und `this.send(obj)` an alle Clients des Controllers. Das zweite Argument von `this.send()` filtert die Empfänger:\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` gibt den ersten Client zurück, für den `fn` `true` zurückgibt, und `this.clients()` gibt alle Clients als Array zurück. `this.online` ist die Anzahl der verbundenen Clients und `this.connections` ordnet Client-IDs den Clients zu.\n\n## Der Client einer Verbindung\n\nJeder verbundene Client hat `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` und `protocol`. `user` ist der Wert, den dein `AUTH()`-Delegate akzeptiert hat:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nEin Client, der die Autorisierung nicht besteht, wird mit dem Code `4001` geschlossen, eine URL ohne Route mit `4004` und ungültige URL-Parameter mit `4000`.\n\n`client.close([message], [code])` schließt einen Client und `this.close([message], [code])` schließt alle. Der Standardcode ist `1000`.\n\n## Ping und veraltete Verbindungen\n\nDas Framework pingt jeden verbundenen Client alle `CONF.default_interval_websocket_ping` Millisekunden (Standard `20000`). Die Antwort setzt `client.latency`. Ein Client, der nicht geantwortet hat oder dessen Latenz höher als `CONF.default_websocket_maxlatency` (Standard `2000` ms) ist, wird in der nächsten Runde geschlossen. Setze `default_websocket_maxlatency` auf `0`, um den Pinger abzuschalten.\n\n## WebSocket-API\n\nEine Route kann `API`-Routen über den Socket verarbeiten. Deklariere die API mit `@name` und verwende denselben Namen in der Socket-Route:\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nEine `SOCKET`-Route mit `@name` und ohne Action ruft `this.api('@name')` und `this.autodestroy()` für dich auf. Der Client sendet `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` und erhält dasselbe Objekt zurück, mit `success: true` und `data` oder mit `error: true` und den Fehlern.\n\n## Verbindung vom Server aus\n\n`WEBSOCKETCLIENT()` erzeugt einen WebSocket-Client, zum Beispiel um eine Total.js-App mit einer anderen zu verbinden:\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` ist standardmäßig `json`; verwende `text`, `binary` oder `buffer` für andere Daten. Der Client verbindet sich 3 Sekunden nach dem Verlust der Verbindung neu (`options.reconnect`); `client.close()` beendet das Neuverbinden und `client.destroy()` gibt den Client frei. `client.api(schema, data, callback)` ruft die WebSocket-API des Servers auf:\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Konfiguration\n\n| Schlüssel | Standard | Bedeutung |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Aktiviert WebSocket-Routen. |\n| `allow_websocket_compression` | `true` | Erlaubt die Kompression `permessage-deflate`. |\n| `default_websocket_maxlength` | `2` | Maximale Nachrichtengröße in kB. |\n| `default_websocket_maxlatency` | `2000` | Maximale Ping-Latenz in ms; `0` deaktiviert den Pinger. |\n| `default_interval_websocket_ping` | `20000` | Intervall des Pings in ms. |\n| `default_websocket_encodedecode` | `false` | Kodiert Nachrichten mit `encodeURIComponent()` und dekodiert sie. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"WebSockets","summary":"Declara rutas WebSocket, gestiona clientes y mensajes en el controlador WebSocket y conéctate a servidores WebSocket con WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSockets\n\n> Declara rutas WebSocket, gestiona clientes y mensajes en el controlador WebSocket y conéctate a servidores WebSocket con WEBSOCKETCLIENT().\n\nUna ruta WebSocket mantiene una conexión abierta entre el navegador y el servidor. En Total.js la declaras con `ROUTE()` y el método `SOCKET`. La acción de la ruta no responde a una petición: se ejecuta **una vez**, cuando se conecta el primer cliente, y su `this` es un **controlador WebSocket** compartido por todos los clientes de esa ruta.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nLa lista completa de propiedades y métodos está en la referencia de [WebSockets](../../reference/websockets/).\n\n## Declarar una ruta\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` registra la ruta. `WS` y `WSS` se aceptan como alias de `SOCKET`. Un `+` antes del método permite solo usuarios con sesión iniciada y un `-` solo usuarios anónimos, igual que en otras rutas:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nLas partes dinámicas de la URL llegan como argumentos de la acción y en `this.params`. El argumento `length` (o un número en los flags) es el tamaño máximo de un mensaje en **kB**. El valor por defecto viene de `CONF.default_websocket_maxlength` (`2` kB). Un frame más grande cierra la conexión con el código `1009`.\n\n## Flags\n\n| Flag | Significado |\n| --- | --- |\n| `json` | Los mensajes son JSON (por defecto). Los mensajes entrantes se parsean y los objetos salientes se serializan. |\n| `text` o `plain` | Los mensajes son cadenas. |\n| `binary` | Los mensajes son binarios; `message` recibe un `Buffer`. |\n| `raw` | Desactiva `json` y `binary`; los mensajes se tratan como texto. |\n| `buffer` | El evento `message` siempre recibe el `Buffer` sin procesar. |\n| `authorize`, `logged` | Solo usuarios con sesión iniciada (igual que `+`). |\n| `unauthorize`, `unlogged` | Solo usuarios anónimos (igual que `-`). |\n| `@role` | Marca un rol; la ruta también pasa a ser `authorize`. |\n| `http://…`, `https://…` | Orígenes permitidos. La cabecera `Origin` debe contener uno de ellos. |\n| `#name` o `&name` | Middleware que se ejecuta antes de aceptar la conexión. |\n| `id:name` | Un identificador de la ruta. |\n| `debug`, `release`, `http`, `https` | Limitan la ruta a un modo o a un protocolo. |\n| cualquier otra palabra | Un sub-protocolo obligatorio: el cliente debe enviarlo en `Sec-WebSocket-Protocol`. |\n| un número | El tamaño máximo del mensaje en kB. |\n| un objeto | Opciones que se pasan al middleware. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nEsta ruta acepta solo clientes de `https://www.example.com` que piden el sub-protocolo `chat`, y mensajes de hasta 128 kB.\n\n## Cómo se agrupan las conexiones\n\nCada ruta tiene un controlador por URL. El primer cliente lo crea y ejecuta la acción; los clientes posteriores en la misma URL se unen al controlador existente, y la acción no se vuelve a llamar. Por eso la acción registra eventos en lugar de responder.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nSin más código, el controlador se queda en memoria después de que se vaya el último cliente. Llama a `this.autodestroy()` para destruirlo 5 segundos después de que se desconecte el último cliente; el siguiente cliente crea uno nuevo y la acción se vuelve a ejecutar:\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Recibir y enviar\n\nCon el flag `json` por defecto, `message` recibe un objeto parseado; el JSON no válido se ignora. `client.send(obj)` envía a un cliente y `this.send(obj)` envía a todos los clientes del controlador. El segundo argumento de `this.send()` filtra los destinatarios:\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` devuelve el primer cliente para el que `fn` devuelve `true`, y `this.clients()` devuelve todos los clientes como un array. `this.online` es el número de clientes conectados y `this.connections` asocia los ids de cliente con los clientes.\n\n## El cliente de una conexión\n\nCada cliente conectado tiene `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` y `protocol`. `user` es el valor aceptado por tu delegado `AUTH()`:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nUn cliente que falla la autorización se cierra con el código `4001`, una URL sin ruta con `4004`, y unos parámetros de URL no válidos con `4000`.\n\n`client.close([message], [code])` cierra un cliente y `this.close([message], [code])` los cierra todos. El código por defecto es `1000`.\n\n## Ping y conexiones inactivas\n\nEl framework hace ping a cada cliente conectado cada `CONF.default_interval_websocket_ping` milisegundos (por defecto `20000`). La respuesta asigna `client.latency`. Un cliente que no respondió, o cuya latencia es mayor que `CONF.default_websocket_maxlatency` (por defecto `2000` ms), se cierra en la siguiente ronda. Asigna `0` a `default_websocket_maxlatency` para desactivar el ping.\n\n## WebSocket API\n\nUna ruta puede procesar rutas `API` a través del socket. Declara la API con `@name` y usa el mismo nombre en la ruta del socket:\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nUna ruta `SOCKET` con `@name` y sin acción llama por ti a `this.api('@name')` y a `this.autodestroy()`. El cliente envía `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` y recibe el mismo objeto de vuelta con `success: true` y `data`, o con `error: true` y los errores.\n\n## Conectar desde el servidor\n\n`WEBSOCKETCLIENT()` crea un cliente WebSocket, por ejemplo para conectar una aplicación Total.js con otra:\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` es `json` por defecto; usa `text`, `binary` o `buffer` para otros datos. El cliente se reconecta 3 segundos después de perder la conexión (`options.reconnect`); `client.close()` detiene la reconexión y `client.destroy()` libera el cliente. `client.api(schema, data, callback)` llama a la WebSocket API del servidor:\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Configuración\n\n| Clave | Por defecto | Significado |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Activa las rutas WebSocket. |\n| `allow_websocket_compression` | `true` | Permite la compresión `permessage-deflate`. |\n| `default_websocket_maxlength` | `2` | Tamaño máximo del mensaje en kB. |\n| `default_websocket_maxlatency` | `2000` | Latencia máxima del ping en ms; `0` desactiva el ping. |\n| `default_interval_websocket_ping` | `20000` | Intervalo del ping en ms. |\n| `default_websocket_encodedecode` | `false` | Codifica los mensajes con `encodeURIComponent()` y los decodifica. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"WebSockets","summary":"Déclare des routes WebSocket, gère les clients et les messages dans le contrôleur WebSocket, et connecte-toi à des serveurs WebSocket avec WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSockets\n\n> Déclare des routes WebSocket, gère les clients et les messages dans le contrôleur WebSocket, et connecte-toi à des serveurs WebSocket avec WEBSOCKETCLIENT().\n\nUne route WebSocket maintient une connexion ouverte entre le navigateur et le serveur. Dans Total.js, tu la déclares avec `ROUTE()` et la méthode `SOCKET`. L'action de la route ne répond pas à une requête : elle s'exécute **une seule fois**, lorsque le premier client se connecte, et son `this` est un **contrôleur WebSocket** partagé par tous les clients de cette route.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nLa liste complète des propriétés et des méthodes se trouve dans la référence [WebSockets](../../reference/websockets/).\n\n## Déclarer une route\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` enregistre la route. `WS` et `WSS` sont acceptés comme alias de `SOCKET`. Un `+` devant la méthode n'autorise que les utilisateurs connectés et un `-` uniquement les utilisateurs anonymes, comme pour les autres routes :\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nLes parties dynamiques de l'URL arrivent comme arguments de l'action et dans `this.params`. L'argument `length` (ou un nombre dans les flags) est la taille maximale d'un message en **ko**. La valeur par défaut provient de `CONF.default_websocket_maxlength` (`2` ko). Une trame plus grande ferme la connexion avec le code `1009`.\n\n## Flags\n\n| Flag | Signification |\n| --- | --- |\n| `json` | Les messages sont en JSON (par défaut). Les messages entrants sont analysés, les objets sortants sont sérialisés. |\n| `text` ou `plain` | Les messages sont des chaînes. |\n| `binary` | Les messages sont binaires ; `message` reçoit un `Buffer`. |\n| `raw` | Désactive `json` et `binary` ; les messages sont traités comme du texte. |\n| `buffer` | L'événement `message` reçoit toujours le `Buffer` brut. |\n| `authorize`, `logged` | Utilisateurs connectés uniquement (identique à `+`). |\n| `unauthorize`, `unlogged` | Utilisateurs anonymes uniquement (identique à `-`). |\n| `@role` | Marque un rôle ; la route devient aussi `authorize`. |\n| `http://…`, `https://…` | Origines autorisées. L'en-tête `Origin` doit contenir l'une d'elles. |\n| `#name` ou `&name` | Middleware exécuté avant l'acceptation de la connexion. |\n| `id:name` | Un identifiant de la route. |\n| `debug`, `release`, `http`, `https` | Limitent la route à un mode ou à un protocole. |\n| tout autre mot | Un sous-protocole obligatoire : le client doit l'envoyer dans `Sec-WebSocket-Protocol`. |\n| un nombre | La taille maximale d'un message en ko. |\n| un objet | Options passées au middleware. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nCette route n'accepte que les clients provenant de `https://www.example.com` qui demandent le sous-protocole `chat`, et des messages d'au plus 128 ko.\n\n## Regroupement des connexions\n\nChaque route a un contrôleur par URL. Le premier client le crée et exécute l'action ; les clients suivants sur la même URL rejoignent le contrôleur existant, et l'action n'est pas rappelée. C'est pourquoi l'action enregistre des événements au lieu de répondre.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nSans code supplémentaire, le contrôleur reste en mémoire après le départ du dernier client. Appelle `this.autodestroy()` pour le détruire 5 secondes après la déconnexion du dernier client ; le client suivant en crée un nouveau et l'action s'exécute de nouveau :\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Recevoir et envoyer\n\nAvec le flag `json` par défaut, `message` reçoit un objet analysé ; un JSON invalide est ignoré. `client.send(obj)` envoie à un seul client et `this.send(obj)` envoie à tous les clients du contrôleur. Le deuxième argument de `this.send()` filtre les destinataires :\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` retourne le premier client pour lequel `fn` retourne `true`, et `this.clients()` retourne tous les clients sous forme de tableau. `this.online` est le nombre de clients connectés et `this.connections` associe les id des clients aux clients.\n\n## Le client d'une connexion\n\nChaque client connecté possède `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` et `protocol`. `user` est la valeur acceptée par ton délégué `AUTH()` :\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nUn client qui échoue à l'autorisation est fermé avec le code `4001`, une URL sans route avec `4004`, et des paramètres d'URL invalides avec `4000`.\n\n`client.close([message], [code])` ferme un client et `this.close([message], [code])` les ferme tous. Le code par défaut est `1000`.\n\n## Ping et connexions inactives\n\nLe framework envoie un ping à chaque client connecté toutes les `CONF.default_interval_websocket_ping` millisecondes (par défaut `20000`). La réponse définit `client.latency`. Un client qui n'a pas répondu, ou dont la latence dépasse `CONF.default_websocket_maxlatency` (par défaut `2000` ms), est fermé au tour suivant. Définis `default_websocket_maxlatency` à `0` pour désactiver le ping.\n\n## API WebSocket\n\nUne route peut traiter des routes `API` via le socket. Déclare l'API avec `@name` et utilise le même nom dans la route du socket :\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nUne route `SOCKET` avec `@name` et sans action appelle `this.api('@name')` et `this.autodestroy()` à ta place. Le client envoie `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` et reçoit en retour le même objet avec `success: true` et `data`, ou `error: true` et les erreurs.\n\n## Se connecter depuis le serveur\n\n`WEBSOCKETCLIENT()` crée un client WebSocket, par exemple pour connecter une application Total.js à une autre :\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` vaut `json` par défaut ; utilise `text`, `binary` ou `buffer` pour d'autres données. Le client se reconnecte 3 secondes après la perte de la connexion (`options.reconnect`) ; `client.close()` arrête la reconnexion et `client.destroy()` libère le client. `client.api(schema, data, callback)` appelle l'API WebSocket du serveur :\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Configuration\n\n| Clé | Par défaut | Signification |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Active les routes WebSocket. |\n| `allow_websocket_compression` | `true` | Autorise la compression `permessage-deflate`. |\n| `default_websocket_maxlength` | `2` | Taille maximale d'un message en ko. |\n| `default_websocket_maxlatency` | `2000` | Latence maximale du ping en ms ; `0` désactive le ping. |\n| `default_interval_websocket_ping` | `20000` | Intervalle du ping en ms. |\n| `default_websocket_encodedecode` | `false` | Encode les messages avec `encodeURIComponent()` et les décode. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"WebSocket","summary":"Dichiara route WebSocket, gestisci client e messaggi nel controller WebSocket e connettiti a server WebSocket con WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSocket\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSocket\n\n> Dichiara route WebSocket, gestisci client e messaggi nel controller WebSocket e connettiti a server WebSocket con WEBSOCKETCLIENT().\n\nUna route WebSocket mantiene aperta una connessione tra il browser e il server. In Total.js la dichiari con `ROUTE()` e il metodo `SOCKET`. L'azione della route non risponde a una richiesta: viene eseguita **una sola volta**, quando si connette il primo client, e il suo `this` è un **controller WebSocket** condiviso da tutti i client di quella route.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nL'elenco completo di proprietà e metodi si trova nel riferimento di [WebSocket](../../reference/websockets/).\n\n## Dichiarare una route\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` registra la route. `WS` e `WSS` sono accettati come alias di `SOCKET`. Un `+` prima del metodo ammette solo utenti autenticati e un `-` solo utenti anonimi, come nelle altre route:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nLe parti dinamiche dell'URL arrivano come argomenti dell'azione e in `this.params`. L'argomento `length` (o un numero nei flag) è la dimensione massima di un messaggio in **kB**. Il valore predefinito proviene da `CONF.default_websocket_maxlength` (`2` kB). Un frame più grande chiude la connessione con il codice `1009`.\n\n## Flag\n\n| Flag | Significato |\n| --- | --- |\n| `json` | I messaggi sono JSON (il valore predefinito). I messaggi in arrivo vengono analizzati, gli oggetti in uscita vengono serializzati. |\n| `text` o `plain` | I messaggi sono stringhe. |\n| `binary` | I messaggi sono binari; `message` riceve un `Buffer`. |\n| `raw` | Disattiva `json` e `binary`; i messaggi vengono gestiti come testo. |\n| `buffer` | L'evento `message` riceve sempre il `Buffer` grezzo. |\n| `authorize`, `logged` | Solo utenti autenticati (come `+`). |\n| `unauthorize`, `unlogged` | Solo utenti anonimi (come `-`). |\n| `@role` | Indica un ruolo; la route diventa anche `authorize`. |\n| `http://…`, `https://…` | Origini consentite. L'intestazione `Origin` deve contenerne una. |\n| `#name` o `&name` | Middleware eseguito prima che la connessione venga accettata. |\n| `id:name` | Un identificatore della route. |\n| `debug`, `release`, `http`, `https` | Limitano la route a una modalità o a un protocollo. |\n| qualsiasi altra parola | Un sotto-protocollo obbligatorio: il client deve inviarlo in `Sec-WebSocket-Protocol`. |\n| un numero | La dimensione massima del messaggio in kB. |\n| un oggetto | Opzioni passate al middleware. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nQuesta route accetta solo client da `https://www.example.com` che richiedono il sotto-protocollo `chat`, e messaggi fino a 128 kB.\n\n## Come vengono raggruppate le connessioni\n\nOgni route ha un controller per URL. Il primo client lo crea ed esegue l'azione; i client successivi sullo stesso URL si uniscono al controller esistente, e l'azione non viene richiamata. Per questo l'azione registra eventi invece di rispondere.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nSenza altro codice il controller resta in memoria dopo che l'ultimo client se ne va. Chiama `this.autodestroy()` per distruggerlo 5 secondi dopo la disconnessione dell'ultimo client; il client successivo ne crea uno nuovo e l'azione viene eseguita di nuovo:\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Ricevere e inviare\n\nCon il flag predefinito `json`, `message` riceve un oggetto già analizzato; il JSON non valido viene ignorato. `client.send(obj)` invia a un client e `this.send(obj)` invia a tutti i client del controller. Il secondo argomento di `this.send()` filtra i destinatari:\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` restituisce il primo client per cui `fn` restituisce `true`, e `this.clients()` restituisce tutti i client come array. `this.online` è il numero di client connessi e `this.connections` associa gli id dei client ai client.\n\n## Il client di una connessione\n\nOgni client connesso ha `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` e `protocol`. `user` è il valore accettato dal tuo delegato `AUTH()`:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nUn client che non supera l'autorizzazione viene chiuso con il codice `4001`, un URL senza route con `4004`, e parametri dell'URL non validi con `4000`.\n\n`client.close([message], [code])` chiude un client e `this.close([message], [code])` li chiude tutti. Il codice predefinito è `1000`.\n\n## Ping e connessioni inattive\n\nIl framework invia un ping a ogni client connesso ogni `CONF.default_interval_websocket_ping` millisecondi (predefinito `20000`). La risposta imposta `client.latency`. Un client che non ha risposto, o la cui latenza è superiore a `CONF.default_websocket_maxlatency` (predefinito `2000` ms), viene chiuso al giro successivo. Imposta `default_websocket_maxlatency` a `0` per disattivare il ping.\n\n## WebSocket API\n\nUna route può elaborare route `API` attraverso il socket. Dichiara l'API con `@name` e usa lo stesso nome nella route del socket:\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nUna route `SOCKET` con `@name` e senza azione chiama per te `this.api('@name')` e `this.autodestroy()`. Il client invia `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` e riceve indietro lo stesso oggetto con `success: true` e `data`, oppure `error: true` e gli errori.\n\n## Connettersi dal server\n\n`WEBSOCKETCLIENT()` crea un client WebSocket, per esempio per connettere un'app Total.js a un'altra:\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` è `json` per impostazione predefinita; usa `text`, `binary` o `buffer` per altri dati. Il client si riconnette 3 secondi dopo la perdita della connessione (`options.reconnect`); `client.close()` interrompe la riconnessione e `client.destroy()` libera il client. `client.api(schema, data, callback)` chiama la WebSocket API del server:\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Configurazione\n\n| Chiave | Predefinito | Significato |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Abilita le route WebSocket. |\n| `allow_websocket_compression` | `true` | Consente la compressione `permessage-deflate`. |\n| `default_websocket_maxlength` | `2` | Dimensione massima del messaggio in kB. |\n| `default_websocket_maxlatency` | `2000` | Latenza massima del ping in ms; `0` disattiva il ping. |\n| `default_interval_websocket_ping` | `20000` | Intervallo del ping in ms. |\n| `default_websocket_encodedecode` | `false` | Codifica i messaggi con `encodeURIComponent()` e li decodifica. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWc61c361f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/websockets/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"WebSockety","summary":"Deklaruj WebSocket routy, spracúvaj klientov a správy vo WebSocket kontroléri a pripájaj sa k WebSocket serverom pomocou WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockety\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/websockets/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# WebSockety\n\n> Deklaruj WebSocket routy, spracúvaj klientov a správy vo WebSocket kontroléri a pripájaj sa k WebSocket serverom pomocou WEBSOCKETCLIENT().\n\nWebSocket routa udržiava otvorené spojenie medzi prehliadačom a serverom. V Total.js ju deklaruješ pomocou `ROUTE()` a metódy `SOCKET`. Akcia routy neodpovedá na požiadavku: spustí sa **raz**, keď sa pripojí prvý klient, a jej `this` je **WebSocket kontrolér** zdieľaný všetkými klientmi danej routy.\n\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\n\tvar self = this;\n\n\tself.on('open', function(client) {\n\t\tclient.send({ type: 'welcome', id: client.id });\n\t});\n\n\tself.on('message', function(client, message) {\n\t\t// Send the message to everybody\n\t\tself.send({ type: 'message', from: client.id, body: message.body });\n\t});\n\n\tself.on('close', function(client) {\n\t\tself.send({ type: 'leave', id: client.id });\n\t});\n}\n```\n\nÚplný zoznam vlastností a metód nájdeš v referencii [WebSockety](../../reference/websockets/).\n\n## Deklarácia routy\n\n`ROUTE('SOCKET /path/', action, [flags], [length])` zaregistruje routu. `WS` a `WSS` sa akceptujú ako aliasy pre `SOCKET`. `+` pred metódou povolí iba prihlásených používateľov a `-` iba anonymných, rovnako ako pri iných routách:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /notifications/', notifications);\n\tROUTE('SOCKET /live/{room}/', live, ['json'], 64);\n};\n\nfunction live(room) {\n\t// room === this.params.room\n}\n```\n\nDynamické časti URL prichádzajú ako argumenty akcie a v `this.params`. Argument `length` (alebo číslo vo flagoch) je maximálna veľkosť jednej správy v **kB**. Predvolená hodnota pochádza z `CONF.default_websocket_maxlength` (`2` kB). Väčší rámec zatvorí spojenie s kódom `1009`.\n\n## Flagy\n\n| Flag | Význam |\n| --- | --- |\n| `json` | Správy sú JSON (predvolené). Prichádzajúce správy sa parsujú, odchádzajúce objekty sa serializujú. |\n| `text` alebo `plain` | Správy sú reťazce. |\n| `binary` | Správy sú binárne; `message` dostane `Buffer`. |\n| `raw` | Vypne `json` a `binary`; správy sa spracúvajú ako text. |\n| `buffer` | Udalosť `message` vždy dostane nespracovaný `Buffer`. |\n| `authorize`, `logged` | Iba prihlásení používatelia (to isté ako `+`). |\n| `unauthorize`, `unlogged` | Iba anonymní používatelia (to isté ako `-`). |\n| `@role` | Označí rolu; routa sa zároveň stane `authorize`. |\n| `http://…`, `https://…` | Povolené pôvody (origins). Hlavička `Origin` musí obsahovať jeden z nich. |\n| `#name` alebo `&name` | Middleware spustený pred prijatím spojenia. |\n| `id:name` | Identifikátor routy. |\n| `debug`, `release`, `http`, `https` | Obmedzia routu na režim alebo protokol. |\n| akékoľvek iné slovo | Povinný subprotokol: klient ho musí poslať v `Sec-WebSocket-Protocol`. |\n| číslo | Maximálna veľkosť správy v kB. |\n| objekt | Možnosti odovzdané middlewaru. |\n\n```js\nROUTE('SOCKET /api/', api, ['json', 'https://www.example.com', 'chat'], 128);\n```\n\nTáto routa prijíma iba klientov z `https://www.example.com`, ktorí žiadajú subprotokol `chat`, a správy do 128 kB.\n\n## Ako sa spojenia zoskupujú\n\nKaždá routa má jeden kontrolér na URL. Prvý klient ho vytvorí a spustí akciu; ďalší klienti na tej istej URL sa pripoja k existujúcemu kontroléru a akcia sa znova nevolá. Preto akcia registruje udalosti namiesto toho, aby odpovedala.\n\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n\tself.on('close', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\nBez ďalšieho kódu zostane kontrolér v pamäti aj po odchode posledného klienta. Zavolaj `this.autodestroy()`, aby sa zničil 5 sekúnd po odpojení posledného klienta; ďalší klient vytvorí nový a akcia sa spustí znova:\n\n```js\nfunction room() {\n\tvar self = this;\n\tself.autodestroy(function() {\n\t\tconsole.log('Room closed:', self.url);\n\t});\n}\n```\n\n## Prijímanie a odosielanie\n\nS predvoleným flagom `json` dostane `message` sparsovaný objekt; neplatný JSON sa ignoruje. `client.send(obj)` posiela jednému klientovi a `this.send(obj)` posiela všetkým klientom kontroléra. Druhý argument `this.send()` filtruje príjemcov:\n\n```js\nfunction chat() {\n\tvar self = this;\n\tself.on('message', function(client, message) {\n\n\t\t// Everybody except the sender\n\t\tself.send(message, function(c) {\n\t\t\treturn c !== client;\n\t\t});\n\n\t\t// Only users of one company\n\t\tself.send(message, function(c, msg, params) {\n\t\t\treturn c.user && c.user.companyid === params.companyid;\n\t\t}, { companyid: client.user.companyid });\n\t});\n}\n```\n\n`this.find(fn)` vráti prvého klienta, pre ktorého `fn` vráti `true`, a `this.clients()` vráti všetkých klientov ako pole. `this.online` je počet pripojených klientov a `this.connections` mapuje id klientov na klientov.\n\n## Klient spojenia\n\nKaždý pripojený klient má `id`, `ip`, `query`, `headers`, `url`, `ua`, `user`, `session`, `language`, `mobile` a `protocol`. `user` je hodnota, ktorú prijal tvoj delegát `AUTH()`:\n\n```js\n// definitions/auth.js\nAUTH(function($) {\n\t// $.websocket is true for WebSocket connections\n\tvar token = $.query.token || $.cookie('token');\n\tif (token === 'secret')\n\t\t$.success({ id: 1, name: 'Peter' });\n\telse\n\t\t$.invalid();\n});\n\n// controllers/default.js\nexports.install = function() {\n\tROUTE('+SOCKET /private/', privatechannel);\n};\n\nfunction privatechannel() {\n\tthis.on('open', function(client) {\n\t\tclient.send({ hello: client.user.name });\n\t});\n}\n```\n\nKlient, ktorý neprejde autorizáciou, sa zatvorí s kódom `4001`, URL bez routy s `4004` a neplatné parametre URL s `4000`.\n\n`client.close([message], [code])` zatvorí jedného klienta a `this.close([message], [code])` zatvorí všetkých. Predvolený kód je `1000`.\n\n## Ping a neaktívne spojenia\n\nFramework pinguje každého pripojeného klienta každých `CONF.default_interval_websocket_ping` milisekúnd (predvolene `20000`). Odpoveď nastaví `client.latency`. Klient, ktorý neodpovedal alebo ktorého latencia je vyššia ako `CONF.default_websocket_maxlatency` (predvolene `2000` ms), sa v ďalšom kole zatvorí. Nastav `default_websocket_maxlatency` na `0`, ak chceš ping vypnúť.\n\n## WebSocket API\n\nRouta môže cez socket spracúvať routy `API`. Deklaruj API pomocou `@name` a ten istý názov použi v socket route:\n\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list   *Messages --> list');\n\tROUTE('API @chat +messages_create *Messages --> create');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\nRouta `SOCKET` s `@name` a bez akcie za teba zavolá `this.api('@name')` a `this.autodestroy()`. Klient pošle `{ TYPE: 'api', callbackid: '1', data: { schema: 'messages_list', data: {} } }` a dostane späť ten istý objekt so `success: true` a `data`, alebo s `error: true` a chybami.\n\n## Pripojenie zo servera\n\n`WEBSOCKETCLIENT()` vytvorí WebSocket klienta, napríklad na pripojenie jednej Total.js aplikácie k inej:\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\n\tclient.options.reconnect = 5000;\n\tclient.headers['x-token'] = 'secret';\n\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\n\tclient.on('close', function(code, message) {\n\t\tconsole.log('Closed', code, message);\n\t});\n\n\tclient.connect('ws://127.0.0.1:8000/chat/');\n});\n```\n\n`client.options.type` je predvolene `json`; pre iné dáta použi `text`, `binary` alebo `buffer`. Klient sa znova pripojí 3 sekundy po strate spojenia (`options.reconnect`); `client.close()` zastaví opätovné pripájanie a `client.destroy()` klienta uvoľní. `client.api(schema, data, callback)` volá WebSocket API servera:\n\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n## Konfigurácia\n\n| Kľúč | Predvolené | Význam |\n| --- | --- | --- |\n| `allow_websocket` | `true` | Zapne WebSocket routy. |\n| `allow_websocket_compression` | `true` | Povolí kompresiu `permessage-deflate`. |\n| `default_websocket_maxlength` | `2` | Maximálna veľkosť správy v kB. |\n| `default_websocket_maxlatency` | `2000` | Maximálna latencia pingu v ms; `0` ping vypne. |\n| `default_interval_websocket_ping` | `20000` | Interval pingu v ms. |\n| `default_websocket_encodedecode` | `false` | Kóduje správy pomocou `encodeURIComponent()` a dekóduje ich. |\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"NoSQL database","summary":"The embedded file database of Total.js 4: NOSQL() for JSON documents and TABLE() for rows with a schema, both stored in the databases/ folder and queried with the same builder.","markdown":"---\ntitle: NoSQL database\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL database\n\n> The embedded file database of Total.js 4: NOSQL() for JSON documents and TABLE() for rows with a schema, both stored in the databases/ folder and queried with the same builder.\n\nTotal.js 4 has an embedded file database. `NOSQL(name)` stores JSON documents, `TABLE(name)` stores rows with a fixed set of columns. Both need no server and no installation: the data lives in plain text files in the `databases/` folder of the app, and both use the same query builder.\n\n## Files and storage\n\n| Call | File |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (one JSON document per line) |\n| `TABLE('users')` | `databases/users.table` (a header with the columns, then one row per line, values separated by `\\|`) |\n\nNext to the data file the engine can create `users.nosql.bk` with backups of changed documents (see `builder.backup()`). The folder comes from the `directory_databases` config key (`/databases/` by default) and is created when it is needed.\n\nA name that starts with `~` is an absolute path: `NOSQL('~/www/data/logs.nosql')`. Such an instance is not cached, so every call creates a new one. Other instances are created once and then reused.\n\nOperations are queued and run one after another, so you can call them from anywhere without locking. Every call returns at once; the work starts in the next tick, which gives you time to add conditions to the builder.\n\n## Inserting documents\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nWith `true` as the second argument the document is inserted only when no document matches the conditions you add to the returned builder. The response is `0` when it already exists:\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Reading\n\n`find()` returns an array, `read()` one document, `count()` an object `{ count: Number }` and `list()` a page of results:\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` reads the file from the end, so with several matches it returns the newest one. `find2()` also reads from the end and returns the newest documents first.\n\n## Conditions\n\nAll conditions are joined with AND. Field names can use dots for nested objects (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` adds a raw JavaScript condition. The code sees `doc` and `arg`:\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Sorting, fields and pages\n\n`sort('name')` sorts ascending, `sort('created_desc')` descending, `sort('country,name_desc')` by several fields. `fields('id,name')` returns only these fields, `fields('-password')` removes a field, and `fields('name as title')` renames one.\n\n`take()` and `skip()` limit the result. `paginate(page, limit, [maxlimit])` takes a page number that starts at `1`, which fits values from the query string. `list()` returns everything a grid needs:\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Updating\n\n`update()` (aliases `modify()` and `mod()`) changes only the fields you pass; other fields of the document stay. A prefix in the key performs an operation with the stored value:\n\n| Key | Operation |\n| --- | --- |\n| `name` | Set the value |\n| `+count`, `-count`, `*count`, `/count` | Add, subtract, multiply, divide |\n| `!active` | Toggle a boolean (the value is ignored) |\n| `>max`, `<min` | Keep the higher / the lower value |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nWith `true` as the second argument (upsert) the data is inserted as a new document when nothing matched. `builder.insert(fn)` changes that document before it is written:\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Removing and maintenance\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nRemoved and updated documents leave unused lines in the file. `clean()` rewrites the file without them. `clear()` removes all documents, `drop()` deletes the data file with its backups and log.\n\n## Use in schemas\n\n`callback($)` connects the builder to an operation. An error goes to `$.invalid()`, and the call returns a promise with the result, so it works with `await`. A second argument is an error used when nothing was found:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` returns a promise that rejects on an error, for code outside operations.\n\n## Tables\n\nA table has a fixed schema: columns with a name and a type. Declare it in the config as `table_<name>`, or call `alter()`:\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nTypes are `string`, `string(length)`, `number`, `boolean` (or `bool`), `date` and `object`. Columns can be separated with `|`, `,` or `;`. Only declared columns are stored. When every column has a size (a `string` with a length, `number`, `boolean`, `date`), rows have a fixed width and updates are written in place. Changing the schema with `alter()` rewrites existing rows; `newname=oldname:type` copies values from an old column.\n\n## Performance options\n\n`textdb_inmemory` in the config keeps databases smaller than the given number of megabytes in memory for reading. `textdb_worker : true` runs the engine in a worker thread while the web server is running.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"NoSQL-Datenbank","summary":"Die eingebettete Dateidatenbank von Total.js 4: NOSQL() für JSON-Dokumente und TABLE() für Zeilen mit einem Schema, beide im Ordner databases/ gespeichert und mit demselben Builder abgefragt.","markdown":"---\ntitle: NoSQL-Datenbank\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL-Datenbank\n\n> Die eingebettete Dateidatenbank von Total.js 4: NOSQL() für JSON-Dokumente und TABLE() für Zeilen mit einem Schema, beide im Ordner databases/ gespeichert und mit demselben Builder abgefragt.\n\nTotal.js 4 hat eine eingebettete Dateidatenbank. `NOSQL(name)` speichert JSON-Dokumente, `TABLE(name)` speichert Zeilen mit einer festen Menge an Spalten. Beide brauchen keinen Server und keine Installation: Die Daten liegen in einfachen Textdateien im Ordner `databases/` der App, und beide verwenden denselben Query-Builder.\n\n## Dateien und Speicherung\n\n| Aufruf | Datei |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (ein JSON-Dokument pro Zeile) |\n| `TABLE('users')` | `databases/users.table` (ein Header mit den Spalten, dann eine Zeile pro Datensatz, Werte getrennt durch `\\|`) |\n\nNeben der Datendatei kann die Engine `users.nosql.bk` mit Backups geänderter Dokumente anlegen (siehe `builder.backup()`). Der Ordner kommt aus dem Konfigurationsschlüssel `directory_databases` (standardmäßig `/databases/`) und wird angelegt, wenn er gebraucht wird.\n\nEin Name, der mit `~` beginnt, ist ein absoluter Pfad: `NOSQL('~/www/data/logs.nosql')`. Eine solche Instanz wird nicht gecacht, jeder Aufruf erzeugt also eine neue. Andere Instanzen werden einmal erzeugt und dann wiederverwendet.\n\nOperationen werden in eine Warteschlange gestellt und nacheinander ausgeführt, du kannst sie also von überall ohne Sperren aufrufen. Jeder Aufruf kehrt sofort zurück; die Arbeit beginnt im nächsten Tick, was dir Zeit gibt, dem Builder Bedingungen hinzuzufügen.\n\n## Dokumente einfügen\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nMit `true` als zweitem Argument wird das Dokument nur eingefügt, wenn kein Dokument auf die Bedingungen passt, die du dem zurückgegebenen Builder hinzufügst. Die Response ist `0`, wenn es bereits existiert:\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Lesen\n\n`find()` gibt ein Array zurück, `read()` ein Dokument, `count()` ein Objekt `{ count: Number }` und `list()` eine Seite mit Ergebnissen:\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` liest die Datei vom Ende her, bei mehreren Treffern gibt es also den neuesten zurück. `find2()` liest ebenfalls vom Ende her und gibt die neuesten Dokumente zuerst zurück.\n\n## Bedingungen\n\nAlle Bedingungen werden mit AND verknüpft. Feldnamen können Punkte für verschachtelte Objekte verwenden (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` fügt eine rohe JavaScript-Bedingung hinzu. Der Code sieht `doc` und `arg`:\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Sortierung, Felder und Seiten\n\n`sort('name')` sortiert aufsteigend, `sort('created_desc')` absteigend, `sort('country,name_desc')` nach mehreren Feldern. `fields('id,name')` gibt nur diese Felder zurück, `fields('-password')` entfernt ein Feld, und `fields('name as title')` benennt eines um.\n\n`take()` und `skip()` begrenzen das Ergebnis. `paginate(page, limit, [maxlimit])` nimmt eine Seitennummer, die bei `1` beginnt, was zu Werten aus dem Query-String passt. `list()` gibt alles zurück, was ein Grid braucht:\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Aktualisieren\n\n`update()` (Aliase `modify()` und `mod()`) ändert nur die Felder, die du übergibst; andere Felder des Dokuments bleiben. Ein Präfix im Schlüssel führt eine Operation mit dem gespeicherten Wert aus:\n\n| Schlüssel | Operation |\n| --- | --- |\n| `name` | Den Wert setzen |\n| `+count`, `-count`, `*count`, `/count` | Addieren, subtrahieren, multiplizieren, dividieren |\n| `!active` | Einen Boolean umschalten (der Wert wird ignoriert) |\n| `>max`, `<min` | Den höheren / den niedrigeren Wert behalten |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nMit `true` als zweitem Argument (Upsert) werden die Daten als neues Dokument eingefügt, wenn nichts gepasst hat. `builder.insert(fn)` ändert dieses Dokument, bevor es geschrieben wird:\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Entfernen und Wartung\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nEntfernte und aktualisierte Dokumente hinterlassen ungenutzte Zeilen in der Datei. `clean()` schreibt die Datei ohne sie neu. `clear()` entfernt alle Dokumente, `drop()` löscht die Datendatei mit ihren Backups und ihrem Log.\n\n## Verwendung in Schemas\n\n`callback($)` verbindet den Builder mit einer Operation. Ein Fehler geht an `$.invalid()`, und der Aufruf gibt eine Promise mit dem Ergebnis zurück, er funktioniert also mit `await`. Ein zweites Argument ist ein Fehler, der verwendet wird, wenn nichts gefunden wurde:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` gibt eine Promise zurück, die bei einem Fehler abgelehnt wird, für Code außerhalb von Operationen.\n\n## Tabellen\n\nEine Tabelle hat ein festes Schema: Spalten mit einem Namen und einem Typ. Deklariere es in der Konfiguration als `table_<name>` oder rufe `alter()` auf:\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nDie Typen sind `string`, `string(length)`, `number`, `boolean` (oder `bool`), `date` und `object`. Spalten können mit `|`, `,` oder `;` getrennt werden. Nur deklarierte Spalten werden gespeichert. Wenn jede Spalte eine Größe hat (ein `string` mit Länge, `number`, `boolean`, `date`), haben Zeilen eine feste Breite und Aktualisierungen werden an Ort und Stelle geschrieben. Eine Änderung des Schemas mit `alter()` schreibt bestehende Zeilen neu; `newname=oldname:type` kopiert Werte aus einer alten Spalte.\n\n## Performance-Optionen\n\n`textdb_inmemory` in der Konfiguration hält Datenbanken, die kleiner als die angegebene Anzahl Megabyte sind, zum Lesen im Speicher. `textdb_worker : true` führt die Engine in einem Worker-Thread aus, solange der Webserver läuft.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Base de datos NoSQL","summary":"La base de datos en archivos integrada en Total.js 4: NOSQL() para documentos JSON y TABLE() para filas con esquema, ambas guardadas en la carpeta databases/ y consultadas con el mismo builder.","markdown":"---\ntitle: Base de datos NoSQL\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Base de datos NoSQL\n\n> La base de datos en archivos integrada en Total.js 4: NOSQL() para documentos JSON y TABLE() para filas con esquema, ambas guardadas en la carpeta databases/ y consultadas con el mismo builder.\n\nTotal.js 4 tiene una base de datos en archivos integrada. `NOSQL(name)` guarda documentos JSON y `TABLE(name)` guarda filas con un conjunto fijo de columnas. Ninguna necesita servidor ni instalación: los datos están en archivos de texto plano en la carpeta `databases/` de la aplicación, y ambas usan el mismo query builder.\n\n## Archivos y almacenamiento\n\n| Llamada | Archivo |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (un documento JSON por línea) |\n| `TABLE('users')` | `databases/users.table` (una cabecera con las columnas y luego una fila por línea, con los valores separados por `\\|`) |\n\nJunto al archivo de datos, el motor puede crear `users.nosql.bk` con copias de seguridad de los documentos modificados (consulta `builder.backup()`). La carpeta viene de la clave de configuración `directory_databases` (`/databases/` por defecto) y se crea cuando hace falta.\n\nUn nombre que empieza por `~` es una ruta absoluta: `NOSQL('~/www/data/logs.nosql')`. Esa instancia no se guarda en caché, así que cada llamada crea una nueva. Las demás instancias se crean una vez y luego se reutilizan.\n\nLas operaciones se encolan y se ejecutan una tras otra, así que puedes llamarlas desde cualquier sitio sin bloqueos. Cada llamada retorna al instante; el trabajo empieza en el siguiente tick, lo que te da tiempo para añadir condiciones al builder.\n\n## Insertar documentos\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nCon `true` como segundo argumento, el documento se inserta solo cuando ningún documento cumple las condiciones que añades al builder devuelto. La respuesta es `0` cuando ya existe:\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Lectura\n\n`find()` devuelve un array, `read()` un documento, `count()` un objeto `{ count: Number }` y `list()` una página de resultados:\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` lee el archivo desde el final, así que con varias coincidencias devuelve la más reciente. `find2()` también lee desde el final y devuelve primero los documentos más recientes.\n\n## Condiciones\n\nTodas las condiciones se unen con AND. Los nombres de campo pueden usar puntos para objetos anidados (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` añade una condición en JavaScript puro. El código ve `doc` y `arg`:\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Orden, campos y páginas\n\n`sort('name')` ordena de forma ascendente, `sort('created_desc')` de forma descendente y `sort('country,name_desc')` por varios campos. `fields('id,name')` devuelve solo esos campos, `fields('-password')` quita un campo y `fields('name as title')` renombra uno.\n\n`take()` y `skip()` limitan el resultado. `paginate(page, limit, [maxlimit])` recibe un número de página que empieza en `1`, lo que encaja con los valores del query string. `list()` devuelve todo lo que necesita un grid:\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Actualizar\n\n`update()` (alias `modify()` y `mod()`) cambia solo los campos que pasas; los demás campos del documento se mantienen. Un prefijo en la clave realiza una operación con el valor guardado:\n\n| Clave | Operación |\n| --- | --- |\n| `name` | Asigna el valor |\n| `+count`, `-count`, `*count`, `/count` | Suma, resta, multiplica, divide |\n| `!active` | Invierte un booleano (el valor se ignora) |\n| `>max`, `<min` | Conserva el valor mayor / el menor |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nCon `true` como segundo argumento (upsert), los datos se insertan como un documento nuevo cuando no hubo coincidencias. `builder.insert(fn)` modifica ese documento antes de escribirlo:\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Eliminación y mantenimiento\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nLos documentos eliminados y actualizados dejan líneas sin usar en el archivo. `clean()` reescribe el archivo sin ellas. `clear()` elimina todos los documentos y `drop()` borra el archivo de datos con sus copias de seguridad y su log.\n\n## Uso en esquemas\n\n`callback($)` conecta el builder con una operación. Un error va a `$.invalid()`, y la llamada devuelve una promesa con el resultado, así que funciona con `await`. Un segundo argumento es un error que se usa cuando no se encontró nada:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` devuelve una promesa que se rechaza ante un error, para código fuera de las operaciones.\n\n## Tablas\n\nUna tabla tiene un esquema fijo: columnas con un nombre y un tipo. Declárala en la configuración como `table_<name>`, o llama a `alter()`:\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nLos tipos son `string`, `string(length)`, `number`, `boolean` (o `bool`), `date` y `object`. Las columnas pueden separarse con `|`, `,` o `;`. Solo se guardan las columnas declaradas. Cuando todas las columnas tienen tamaño (un `string` con longitud, `number`, `boolean`, `date`), las filas tienen ancho fijo y las actualizaciones se escriben en su sitio. Cambiar el esquema con `alter()` reescribe las filas existentes; `newname=oldname:type` copia los valores de una columna antigua.\n\n## Opciones de rendimiento\n\n`textdb_inmemory` en la configuración mantiene en memoria, para lectura, las bases de datos menores que el número de megabytes indicado. `textdb_worker : true` ejecuta el motor en un hilo worker mientras el servidor web está en marcha.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Base de données NoSQL","summary":"La base de données embarquée sur fichiers de Total.js 4 : NOSQL() pour les documents JSON et TABLE() pour les lignes avec un schéma, toutes deux stockées dans le dossier databases/ et interrogées avec le même builder.","markdown":"---\ntitle: \"Base de données NoSQL\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Base de données NoSQL\n\n> La base de données embarquée sur fichiers de Total.js 4 : NOSQL() pour les documents JSON et TABLE() pour les lignes avec un schéma, toutes deux stockées dans le dossier databases/ et interrogées avec le même builder.\n\nTotal.js 4 dispose d'une base de données embarquée sur fichiers. `NOSQL(name)` stocke des documents JSON, `TABLE(name)` stocke des lignes avec un ensemble fixe de colonnes. Aucune des deux n'a besoin de serveur ni d'installation : les données résident dans de simples fichiers texte du dossier `databases/` de l'application, et les deux utilisent le même query builder.\n\n## Fichiers et stockage\n\n| Appel | Fichier |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (un document JSON par ligne) |\n| `TABLE('users')` | `databases/users.table` (un en-tête avec les colonnes, puis une ligne par enregistrement, valeurs séparées par `\\|`) |\n\nÀ côté du fichier de données, le moteur peut créer `users.nosql.bk` avec les sauvegardes des documents modifiés (voir `builder.backup()`). Le dossier provient de la clé de configuration `directory_databases` (`/databases/` par défaut) et il est créé lorsqu'il est nécessaire.\n\nUn nom qui commence par `~` est un chemin absolu : `NOSQL('~/www/data/logs.nosql')`. Une telle instance n'est pas mise en cache, chaque appel en crée donc une nouvelle. Les autres instances sont créées une seule fois, puis réutilisées.\n\nLes opérations sont mises en file d'attente et exécutées l'une après l'autre : tu peux donc les appeler depuis n'importe où sans verrouillage. Chaque appel retourne immédiatement ; le travail commence au tick suivant, ce qui te laisse le temps d'ajouter des conditions au builder.\n\n## Insertion de documents\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nAvec `true` comme deuxième argument, le document n'est inséré que si aucun document ne correspond aux conditions que tu ajoutes au builder retourné. La réponse vaut `0` lorsqu'il existe déjà :\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Lecture\n\n`find()` retourne un tableau, `read()` un seul document, `count()` un objet `{ count: Number }` et `list()` une page de résultats :\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` lit le fichier à partir de la fin : s'il y a plusieurs correspondances, il retourne donc la plus récente. `find2()` lit également à partir de la fin et retourne d'abord les documents les plus récents.\n\n## Conditions\n\nToutes les conditions sont combinées avec AND. Les noms de champs peuvent utiliser des points pour les objets imbriqués (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` ajoute une condition JavaScript brute. Le code voit `doc` et `arg` :\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Tri, champs et pages\n\n`sort('name')` trie par ordre croissant, `sort('created_desc')` par ordre décroissant, `sort('country,name_desc')` selon plusieurs champs. `fields('id,name')` ne retourne que ces champs, `fields('-password')` retire un champ et `fields('name as title')` en renomme un.\n\n`take()` et `skip()` limitent le résultat. `paginate(page, limit, [maxlimit])` prend un numéro de page qui commence à `1`, ce qui convient aux valeurs de la query string. `list()` retourne tout ce dont une grille a besoin :\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Mise à jour\n\n`update()` (alias `modify()` et `mod()`) ne modifie que les champs que tu passes ; les autres champs du document restent inchangés. Un préfixe dans la clé effectue une opération avec la valeur stockée :\n\n| Clé | Opération |\n| --- | --- |\n| `name` | Définir la valeur |\n| `+count`, `-count`, `*count`, `/count` | Additionner, soustraire, multiplier, diviser |\n| `!active` | Inverser un booléen (la valeur est ignorée) |\n| `>max`, `<min` | Conserver la valeur la plus élevée / la plus basse |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nAvec `true` comme deuxième argument (upsert), les données sont insérées comme nouveau document lorsque rien ne correspond. `builder.insert(fn)` modifie ce document avant son écriture :\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Suppression et maintenance\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nLes documents supprimés et mis à jour laissent des lignes inutilisées dans le fichier. `clean()` réécrit le fichier sans elles. `clear()` supprime tous les documents, `drop()` supprime le fichier de données avec ses sauvegardes et son journal.\n\n## Utilisation dans les schémas\n\n`callback($)` relie le builder à une opération. Une erreur est transmise à `$.invalid()`, et l'appel retourne une promesse avec le résultat : il fonctionne donc avec `await`. Un deuxième argument est une erreur utilisée lorsque rien n'a été trouvé :\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` retourne une promesse qui est rejetée en cas d'erreur, pour le code en dehors des opérations.\n\n## Tables\n\nUne table a un schéma fixe : des colonnes avec un nom et un type. Déclare-le dans la configuration sous la forme `table_<name>`, ou appelle `alter()` :\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nLes types sont `string`, `string(length)`, `number`, `boolean` (ou `bool`), `date` et `object`. Les colonnes peuvent être séparées par `|`, `,` ou `;`. Seules les colonnes déclarées sont stockées. Lorsque chaque colonne a une taille (une `string` avec une longueur, `number`, `boolean`, `date`), les lignes ont une largeur fixe et les mises à jour sont écrites sur place. Modifier le schéma avec `alter()` réécrit les lignes existantes ; `newname=oldname:type` copie les valeurs d'une ancienne colonne.\n\n## Options de performance\n\n`textdb_inmemory` dans la configuration conserve en mémoire, pour la lecture, les bases de données plus petites que le nombre de mégaoctets indiqué. `textdb_worker : true` exécute le moteur dans un worker thread pendant que le serveur web tourne.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Database NoSQL","summary":"Il database su file integrato in Total.js 4: NOSQL() per documenti JSON e TABLE() per righe con uno schema, entrambi salvati nella cartella databases/ e interrogati con lo stesso builder.","markdown":"---\ntitle: Database NoSQL\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Database NoSQL\n\n> Il database su file integrato in Total.js 4: NOSQL() per documenti JSON e TABLE() per righe con uno schema, entrambi salvati nella cartella databases/ e interrogati con lo stesso builder.\n\nTotal.js 4 ha un database su file integrato. `NOSQL(name)` salva documenti JSON, `TABLE(name)` salva righe con un insieme fisso di colonne. Nessuno dei due richiede un server o un'installazione: i dati si trovano in semplici file di testo nella cartella `databases/` dell'app, ed entrambi usano lo stesso query builder.\n\n## File e archiviazione\n\n| Chiamata | File |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (un documento JSON per riga) |\n| `TABLE('users')` | `databases/users.table` (un'intestazione con le colonne, poi una riga per ogni record, valori separati da `\\|`) |\n\nAccanto al file dei dati il motore può creare `users.nosql.bk` con i backup dei documenti modificati (vedi `builder.backup()`). La cartella proviene dalla chiave di configurazione `directory_databases` (`/databases/` per impostazione predefinita) e viene creata quando serve.\n\nUn nome che inizia con `~` è un percorso assoluto: `NOSQL('~/www/data/logs.nosql')`. Un'istanza di questo tipo non viene messa in cache, quindi ogni chiamata ne crea una nuova. Le altre istanze vengono create una volta e poi riutilizzate.\n\nLe operazioni vengono messe in coda ed eseguite una dopo l'altra, quindi puoi chiamarle da qualsiasi punto senza lock. Ogni chiamata ritorna subito; il lavoro inizia al tick successivo, il che ti dà il tempo di aggiungere condizioni al builder.\n\n## Inserire documenti\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nCon `true` come secondo argomento il documento viene inserito solo quando nessun documento corrisponde alle condizioni che aggiungi al builder restituito. La risposta è `0` quando esiste già:\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Leggere\n\n`find()` restituisce un array, `read()` un documento, `count()` un oggetto `{ count: Number }` e `list()` una pagina di risultati:\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` legge il file dalla fine, quindi con più corrispondenze restituisce quella più recente. Anche `find2()` legge dalla fine e restituisce per primi i documenti più recenti.\n\n## Condizioni\n\nTutte le condizioni vengono unite con AND. I nomi dei campi possono usare i punti per gli oggetti annidati (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` aggiunge una condizione JavaScript grezza. Il codice vede `doc` e `arg`:\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Ordinamento, campi e pagine\n\n`sort('name')` ordina in modo crescente, `sort('created_desc')` decrescente, `sort('country,name_desc')` per più campi. `fields('id,name')` restituisce solo questi campi, `fields('-password')` rimuove un campo, e `fields('name as title')` ne rinomina uno.\n\n`take()` e `skip()` limitano il risultato. `paginate(page, limit, [maxlimit])` accetta un numero di pagina che parte da `1`, adatto ai valori della query string. `list()` restituisce tutto ciò che serve a una griglia:\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Aggiornare\n\n`update()` (alias `modify()` e `mod()`) modifica solo i campi che passi; gli altri campi del documento restano. Un prefisso nella chiave esegue un'operazione con il valore memorizzato:\n\n| Chiave | Operazione |\n| --- | --- |\n| `name` | Imposta il valore |\n| `+count`, `-count`, `*count`, `/count` | Somma, sottrae, moltiplica, divide |\n| `!active` | Inverte un booleano (il valore viene ignorato) |\n| `>max`, `<min` | Mantiene il valore più alto / più basso |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nCon `true` come secondo argomento (upsert) i dati vengono inseriti come nuovo documento quando non c'è stata alcuna corrispondenza. `builder.insert(fn)` modifica quel documento prima che venga scritto:\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Rimozione e manutenzione\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nI documenti rimossi e aggiornati lasciano righe inutilizzate nel file. `clean()` riscrive il file senza di esse. `clear()` rimuove tutti i documenti, `drop()` elimina il file dei dati con i suoi backup e il log.\n\n## Uso negli schemi\n\n`callback($)` collega il builder a un'operazione. Un errore va a `$.invalid()`, e la chiamata restituisce una promessa con il risultato, quindi funziona con `await`. Un secondo argomento è un errore usato quando non è stato trovato nulla:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` restituisce una promessa che viene rifiutata in caso di errore, per il codice al di fuori delle operazioni.\n\n## Tabelle\n\nUna tabella ha uno schema fisso: colonne con un nome e un tipo. Dichiaralo nella configurazione come `table_<name>`, oppure chiama `alter()`:\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nI tipi sono `string`, `string(length)`, `number`, `boolean` (o `bool`), `date` e `object`. Le colonne possono essere separate con `|`, `,` o `;`. Vengono memorizzate solo le colonne dichiarate. Quando ogni colonna ha una dimensione (una `string` con una lunghezza, `number`, `boolean`, `date`), le righe hanno una larghezza fissa e gli aggiornamenti vengono scritti sul posto. Modificare lo schema con `alter()` riscrive le righe esistenti; `newname=oldname:type` copia i valori da una vecchia colonna.\n\n## Opzioni di prestazione\n\n`textdb_inmemory` nella configurazione tiene in memoria per la lettura i database più piccoli del numero di megabyte indicato. `textdb_worker : true` esegue il motore in un worker thread mentre il server web è in esecuzione.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvZ2Yh61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/nosql/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"NoSQL databáza","summary":"Vstavaná súborová databáza Total.js 4: NOSQL() pre JSON dokumenty a TABLE() pre riadky so schémou, obe uložené v priečinku databases/ a dopytované rovnakým builderom.","markdown":"---\ntitle: \"NoSQL databáza\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL databáza\n\n> Vstavaná súborová databáza Total.js 4: NOSQL() pre JSON dokumenty a TABLE() pre riadky so schémou, obe uložené v priečinku databases/ a dopytované rovnakým builderom.\n\nTotal.js 4 má vstavanú súborovú databázu. `NOSQL(name)` ukladá JSON dokumenty, `TABLE(name)` ukladá riadky s pevnou sadou stĺpcov. Ani jedna nepotrebuje server ani inštaláciu: dáta sú v obyčajných textových súboroch v priečinku `databases/` aplikácie a obe používajú rovnaký query builder.\n\n## Súbory a úložisko\n\n| Volanie | Súbor |\n| --- | --- |\n| `NOSQL('users')` | `databases/users.nosql` (jeden JSON dokument na riadok) |\n| `TABLE('users')` | `databases/users.table` (hlavička so stĺpcami, potom jeden riadok na záznam, hodnoty oddelené `\\|`) |\n\nVedľa dátového súboru môže engine vytvoriť `users.nosql.bk` so zálohami zmenených dokumentov (pozri `builder.backup()`). Priečinok pochádza z konfiguračného kľúča `directory_databases` (predvolene `/databases/`) a vytvorí sa, keď je potrebný.\n\nNázov, ktorý začína `~`, je absolútna cesta: `NOSQL('~/www/data/logs.nosql')`. Takáto inštancia sa neukladá do cache, takže každé volanie vytvorí novú. Ostatné inštancie sa vytvoria raz a potom sa opakovane používajú.\n\nOperácie sa radia do fronty a spúšťajú jedna po druhej, takže ich môžeš volať odkiaľkoľvek bez zamykania. Každé volanie sa vráti okamžite; práca začne v ďalšom ticku, čo ti dáva čas pridať do buildera podmienky.\n\n## Vkladanie dokumentov\n\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', email: 'peter@example.com', age: 32, created: NOW }).callback(function(err, count) {\n\t// count: 1\n});\n```\n\nS `true` ako druhým argumentom sa dokument vloží, iba keď podmienkam, ktoré pridáš do vráteného buildera, nevyhovuje žiadny dokument. Odpoveď je `0`, keď už existuje:\n\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('The email is already registered');\n});\n```\n\n## Čítanie\n\n`find()` vráti pole, `read()` jeden dokument, `count()` objekt `{ count: Number }` a `list()` stránku výsledkov:\n\n```js\nNOSQL('users').find().where('age', '>', 18).sort('name').fields('id,name,email').take(20).callback(function(err, items, meta) {\n\t// meta: { count, counter, scanned, duration }\n});\n\nNOSQL('users').read().id('3ab5k001pt51d').callback(function(err, user) {\n\t// user is the document or nothing\n});\n\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\t// response.count\n});\n```\n\n`read()` číta súbor od konca, takže pri viacerých zhodách vráti najnovší. Aj `find2()` číta od konca a vracia najnovšie dokumenty ako prvé.\n\n## Podmienky\n\nVšetky podmienky sa spájajú pomocou AND. Názvy polí môžu pre vnorené objekty používať bodky (`address.city`).\n\n```js\nvar builder = NOSQL('products').find();\nbuilder.where('price', '>=', 10);       // =, ==, !=, <>, >, <, >=, <=\nbuilder.where('category', 'books');     // two arguments: equality\nbuilder.in('tags', ['new', 'sale']);    // the field (or one of its items) is in the array\nbuilder.notin('status', ['deleted']);\nbuilder.between('price', 10, 100);\nbuilder.search('name', 'total');        // case-insensitive substring\nbuilder.search('code', 'AB', 'beg');    // 'beg' = starts with, 'end' = ends with\nbuilder.contains('photos');             // not empty\nbuilder.empty('note');                  // empty, null or an empty array\nbuilder.year('created', 2022);\nbuilder.month('created', '>=', 6);\nbuilder.or(function() {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n});\nbuilder.callback(console.log);\n```\n\n`rule(code, [arg])` pridá surovú JavaScript podmienku. Kód vidí `doc` a `arg`:\n\n```js\nNOSQL('users').find().rule('doc.age > arg.min && doc.roles.includes(\\'admin\\')', { min: 18 }).callback(console.log);\n```\n\n## Triedenie, polia a stránky\n\n`sort('name')` triedi vzostupne, `sort('created_desc')` zostupne, `sort('country,name_desc')` podľa viacerých polí. `fields('id,name')` vráti iba tieto polia, `fields('-password')` pole odstráni a `fields('name as title')` jedno premenuje.\n\n`take()` a `skip()` obmedzia výsledok. `paginate(page, limit, [maxlimit])` prijíma číslo stránky začínajúce od `1`, čo zodpovedá hodnotám z query stringu. `list()` vráti všetko, čo potrebuje tabuľka (grid):\n\n```js\nNOSQL('users').list().where('active', true).sort('name').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response: { page, pages, limit, count, items }\n});\n```\n\n## Aktualizácia\n\n`update()` (aliasy `modify()` a `mod()`) zmení iba polia, ktoré odovzdáš; ostatné polia dokumentu zostanú. Prefix v kľúči vykoná operáciu s uloženou hodnotou:\n\n| Kľúč | Operácia |\n| --- | --- |\n| `name` | Nastaví hodnotu |\n| `+count`, `-count`, `*count`, `/count` | Pripočíta, odpočíta, vynásobí, vydelí |\n| `!active` | Prepne boolovskú hodnotu (hodnota sa ignoruje) |\n| `>max`, `<min` | Ponechá vyššiu / nižšiu hodnotu |\n\n```js\nNOSQL('products').update({ name: 'Book', '+views': 1, updated: NOW }).id(id).callback(function(err, count) {\n\t// count: number of changed documents\n});\n```\n\nS `true` ako druhým argumentom (upsert) sa dáta vložia ako nový dokument, keď nič nevyhovelo. `builder.insert(fn)` tento dokument pred zápisom upraví:\n\n```js\nNOSQL('stats').update({ id: key, '+count': 1 }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n## Odstraňovanie a údržba\n\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\nOdstránené a aktualizované dokumenty nechávajú v súbore nepoužívané riadky. `clean()` prepíše súbor bez nich. `clear()` odstráni všetky dokumenty, `drop()` vymaže dátový súbor spolu so zálohami a logom.\n\n## Použitie v schémach\n\n`callback($)` prepojí builder s operáciou. Chyba ide do `$.invalid()` a volanie vráti promise s výsledkom, takže funguje s `await`. Druhý argument je chyba, ktorá sa použije, keď sa nič nenašlo:\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.setRead(async function($) {\n\t\tvar user = await NOSQL('users').read().id($.id).fields('-password').callback($, 'error-users-404');\n\t\t$.callback(user);\n\t});\n\n\tschema.setQuery(async function($) {\n\t\tvar response = await NOSQL('users').list().autofill($, null, 'password', 'name', 50).callback($);\n\t\t$.callback(response);\n\t});\n\n});\n```\n\n`promise()` vráti promise, ktorý sa pri chybe zamietne, pre kód mimo operácií.\n\n## Tabuľky\n\nTabuľka má pevnú schému: stĺpce s názvom a typom. Deklaruj ju v konfigurácii ako `table_<name>` alebo zavolaj `alter()`:\n\n```\ntable_users     : id:string(20)|name:string(50)|age:number|active:boolean|created:date\n```\n\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\nTABLE('users').insert({ id: UID(), name: 'Anna', age: 28, active: true, created: NOW });\nTABLE('users').find().where('active', true).callback(console.log);\n```\n\nTypy sú `string`, `string(length)`, `number`, `boolean` (alebo `bool`), `date` a `object`. Stĺpce môžeš oddeliť pomocou `|`, `,` alebo `;`. Ukladajú sa iba deklarované stĺpce. Keď má každý stĺpec veľkosť (`string` s dĺžkou, `number`, `boolean`, `date`), riadky majú pevnú šírku a aktualizácie sa zapisujú na mieste. Zmena schémy pomocou `alter()` prepíše existujúce riadky; `newname=oldname:type` skopíruje hodnoty zo starého stĺpca.\n\n## Možnosti výkonu\n\n`textdb_inmemory` v konfigurácii drží databázy menšie ako zadaný počet megabajtov v pamäti na čítanie. `textdb_worker : true` spustí engine vo worker vlákne, kým beží webový server.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Localization","summary":"Translate views, static files, errors and e-mails with resource files and a language for each request.","markdown":"---\ntitle: Localization\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localization\n\n> Translate views, static files, errors and e-mails with resource files and a language for each request.\n\nTotal.js translates text with **resource files**. A resource file is a plain text file with `key : value` lines in the `resources/` directory. The name of the file is the name of a language: `resources/sk.resource` holds the Slovak texts, `resources/de.resource` the German ones. `resources/default.resource` is the fallback for every language.\n\nYou mark text in views with `@(Text)`, choose the language of each request in a delegate, and the framework does the rest: it translates views, static HTML files, error messages and e-mail subjects. The exact reference is in [Localization](../../reference/localization/).\n\n## Resource files\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nRules of the format:\n\n- One key and one value per line, separated by ` : `. Keep a space after the colon: the parser skips the first character after `:`.\n- Lines that start with `//` or `#` are comments; empty lines are ignored.\n- The value is one line. Leading and trailing spaces are removed.\n- Keys made of `T` and a base-36 hash of the text are translations of `@(Text)`. You do not write them by hand: the `total4 translate` command creates them (see below).\n\n`RESOURCE()` reads a value by its key:\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nWhen a key is missing in `sk.resource`, the value from `default.resource` is used. When it is missing there too, the result is an empty string.\n\nA resource with one name can come from several places. The framework joins them in this order, and a later line with the same key wins:\n\n1. files registered with `F.register('/path/to/sk.resource')` (useful for packages and modules),\n2. `tmp/sk.resource`, written by `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nParsed resources are cached in `F.resources`. The cache is cleared every 20 minutes (`default_interval_clear_resources`), so changed files are read again without a restart.\n\n## Choosing the language of a request\n\nThe language is a string: the name of the resource file without the extension. You set it with `LOCALIZE()` and a function; the function becomes `DEF.onLocale`:\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nThe function is called once per request and must return the language. The framework calls it:\n\n- for static files, with `true` as the third argument,\n- for routes, after authorization, so `req.user` is already known when you use `AUTH()`,\n- for WebSocket connections, with `req` only.\n\nThe returned value is stored in `req.$language`. From there it goes to `controller.language`, `client.language` in WebSockets and `$.language` in schemas, operations and middleware.\n\nWith the built-in session authorization of `AUTH()`, use the `locale` option to take the language from the user:\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Translating views\n\nWrite the text of the default language inside `@(...)`:\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` is replaced with the translation from the resource of `controller.language`. The key is `T` plus a hash of the text. When there is no translation, the original text stays.\n- `@(#key)` reads `key` from the resource directly.\n- `@{resource([name], key)}` prints a resource value, HTML-encoded. In views, `language` holds the current language.\n- When `@(...)` is inside quotes, quotes in the translation are escaped, so it is safe in attributes and in inline scripts.\n- `@{notranslate}` (or `@{nolocalize}`) anywhere in a view turns translation off for that view.\n\nTranslation happens when the view is compiled, so a view is compiled once for each language. In release mode the compiled views are cached; in debug mode they are compiled again on every render.\n\nWhen no file exists for the language (for example `fr.resource` is missing), `@(Text)` keeps the original text.\n\nYou can change the language for one response before you render the view:\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## Static files\n\nWith `allow_localize: true` (the default), `.html` and `.htm` files from `public/` are translated like views: `@(Text)` is replaced and the result is cached per language in release mode.\n\n`LOCALIZE(url, [flags], [minify])` translates other files too:\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Translating in code\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nDates use resources for the names of months and days. `new Date().format('dddd d. MMMM yyyy', 'sk')` reads `January`…`December` and `Sunday`…`Saturday` as keys from `sk.resource`.\n\n## Error messages\n\nErrors of schemas and operations are translated with the language of the request:\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- A short name without spaces, colons or commas (`error-email`) is a resource key.\n- `@(Text)` is translated like in views: `$.invalid('@(The e-mail is taken)')`.\n- Any other text is sent as it is.\n\nWithout a translation the message is `The field \"name\" is invalid`. Use `schema.setResource()` and `schema.setPrefix()` to read errors from a fixed resource or with a key prefix, and `ErrorBuilder.resource()` for your own `ErrorBuilder`.\n\n## E-mails\n\n`MAIL()` and `HTMLMAIL()` take a language. The subject is translated, and the view of `MAIL()` is rendered in that language:\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` uses the language of the controller.\n\n## Loading translations at runtime\n\n`LOADRESOURCE()` writes a resource into `tmp/` and clears its cache. You can pass an object, an array or a URL:\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## The translate tool\n\nThe `total4` command creates and maintains resource files. Run it in the root of the application:\n\n| Command | What it does |\n| --- | --- |\n| `total4 translate` | Finds every `@(Text)` in `.html`, `.js` and sitemap files, and keys of `$.invalid('key')`, and writes `translate.resource` |\n| `total4 translate \"Text\"` | Prints the key of one text |\n| `total4 translate <file>` | Creates `translate.resource` from a text file, one text per line |\n| `total4 translatecsv` | Writes the texts into `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Creates a resource from the first two columns of a CSV |\n| `total4 diff <source> <target>` | Writes `<target>-diff.txt` with keys to add to and to remove from the target |\n| `total4 merge <source> <target>` | Writes `<target>-merged.txt`: the target with values taken from the source |\n| `total4 clean <source>` | Writes `<source>-cleaned.txt` with aligned keys |\n\nA typical workflow: run `total4 translate`, copy `translate.resource` to `resources/sk.resource`, translate the values, and after the next change run `total4 diff translate.resource resources/sk.resource` to find new texts.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Lokalisierung","summary":"Übersetze Views, statische Dateien, Fehler und E-Mails mit Ressourcendateien und einer Sprache für jede Anfrage.","markdown":"---\ntitle: Lokalisierung\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Lokalisierung\n\n> Übersetze Views, statische Dateien, Fehler und E-Mails mit Ressourcendateien und einer Sprache für jede Anfrage.\n\nTotal.js übersetzt Texte mit **Ressourcendateien**. Eine Ressourcendatei ist eine einfache Textdatei mit `key : value`-Zeilen im Verzeichnis `resources/`. Der Name der Datei ist der Name einer Sprache: `resources/sk.resource` enthält die slowakischen Texte, `resources/de.resource` die deutschen. `resources/default.resource` ist der Fallback für jede Sprache.\n\nDu markierst Text in Views mit `@(Text)`, wählst die Sprache jeder Anfrage in einem Delegate, und das Framework erledigt den Rest: Es übersetzt Views, statische HTML-Dateien, Fehlermeldungen und E-Mail-Betreffs. Die genaue Referenz findest du unter [Lokalisierung](../../reference/localization/).\n\n## Ressourcendateien\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nRegeln des Formats:\n\n- Ein Schlüssel und ein Wert pro Zeile, getrennt durch ` : `. Lass ein Leerzeichen nach dem Doppelpunkt: Der Parser überspringt das erste Zeichen nach `:`.\n- Zeilen, die mit `//` oder `#` beginnen, sind Kommentare; leere Zeilen werden ignoriert.\n- Der Wert ist eine Zeile. Leerzeichen am Anfang und am Ende werden entfernt.\n- Schlüssel aus `T` und einem Base-36-Hash des Textes sind Übersetzungen von `@(Text)`. Du schreibst sie nicht von Hand: Der Befehl `total4 translate` erstellt sie (siehe unten).\n\n`RESOURCE()` liest einen Wert anhand seines Schlüssels:\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nFehlt ein Schlüssel in `sk.resource`, wird der Wert aus `default.resource` verwendet. Fehlt er auch dort, ist das Ergebnis ein leerer String.\n\nEine Ressource mit einem Namen kann aus mehreren Quellen stammen. Das Framework fügt sie in dieser Reihenfolge zusammen, und eine spätere Zeile mit demselben Schlüssel gewinnt:\n\n1. mit `F.register('/path/to/sk.resource')` registrierte Dateien (nützlich für Pakete und Module),\n2. `tmp/sk.resource`, geschrieben von `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nGeparste Ressourcen werden in `F.resources` gecacht. Der Cache wird alle 20 Minuten geleert (`default_interval_clear_resources`), sodass geänderte Dateien ohne Neustart erneut gelesen werden.\n\n## Die Sprache einer Anfrage wählen\n\nDie Sprache ist ein String: der Name der Ressourcendatei ohne Endung. Du setzt sie mit `LOCALIZE()` und einer Funktion; die Funktion wird zu `DEF.onLocale`:\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nDie Funktion wird einmal pro Anfrage aufgerufen und muss die Sprache zurückgeben. Das Framework ruft sie auf:\n\n- für statische Dateien, mit `true` als drittem Argument,\n- für Routen, nach der Autorisierung, sodass `req.user` bereits bekannt ist, wenn du `AUTH()` verwendest,\n- für WebSocket-Verbindungen, nur mit `req`.\n\nDer zurückgegebene Wert wird in `req.$language` gespeichert. Von dort gelangt er nach `controller.language`, nach `client.language` in WebSockets und nach `$.language` in Schemas, Operationen und Middleware.\n\nMit der eingebauten Session-Autorisierung von `AUTH()` verwendest du die Option `locale`, um die Sprache vom Benutzer zu übernehmen:\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Views übersetzen\n\nSchreib den Text der Standardsprache in `@(...)`:\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` wird durch die Übersetzung aus der Ressource von `controller.language` ersetzt. Der Schlüssel ist `T` plus ein Hash des Textes. Gibt es keine Übersetzung, bleibt der Originaltext.\n- `@(#key)` liest `key` direkt aus der Ressource.\n- `@{resource([name], key)}` gibt einen Ressourcenwert HTML-kodiert aus. In Views enthält `language` die aktuelle Sprache.\n- Steht `@(...)` in Anführungszeichen, werden Anführungszeichen in der Übersetzung maskiert, sodass es in Attributen und Inline-Skripten sicher ist.\n- `@{notranslate}` (oder `@{nolocalize}`) an beliebiger Stelle in einer View schaltet die Übersetzung für diese View ab.\n\nDie Übersetzung erfolgt beim Kompilieren der View, daher wird eine View für jede Sprache einmal kompiliert. Im Release-Modus werden die kompilierten Views gecacht; im Debug-Modus werden sie bei jedem Rendern neu kompiliert.\n\nExistiert für die Sprache keine Datei (zum Beispiel fehlt `fr.resource`), behält `@(Text)` den Originaltext.\n\nDu kannst die Sprache für eine einzelne Antwort ändern, bevor du die View renderst:\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## Statische Dateien\n\nMit `allow_localize: true` (Standard) werden `.html`- und `.htm`-Dateien aus `public/` wie Views übersetzt: `@(Text)` wird ersetzt, und das Ergebnis wird im Release-Modus pro Sprache gecacht.\n\n`LOCALIZE(url, [flags], [minify])` übersetzt auch andere Dateien:\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Im Code übersetzen\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nDatumsangaben verwenden Ressourcen für die Namen von Monaten und Tagen. `new Date().format('dddd d. MMMM yyyy', 'sk')` liest `January`…`December` und `Sunday`…`Saturday` als Schlüssel aus `sk.resource`.\n\n## Fehlermeldungen\n\nFehler von Schemas und Operationen werden mit der Sprache der Anfrage übersetzt:\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- Ein kurzer Name ohne Leerzeichen, Doppelpunkte oder Kommas (`error-email`) ist ein Ressourcenschlüssel.\n- `@(Text)` wird wie in Views übersetzt: `$.invalid('@(The e-mail is taken)')`.\n- Jeder andere Text wird unverändert gesendet.\n\nOhne Übersetzung lautet die Meldung `The field \"name\" is invalid`. Verwende `schema.setResource()` und `schema.setPrefix()`, um Fehler aus einer festen Ressource oder mit einem Schlüsselpräfix zu lesen, und `ErrorBuilder.resource()` für deinen eigenen `ErrorBuilder`.\n\n## E-Mails\n\n`MAIL()` und `HTMLMAIL()` nehmen eine Sprache entgegen. Der Betreff wird übersetzt, und die View von `MAIL()` wird in dieser Sprache gerendert:\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` verwendet die Sprache des Controllers.\n\n## Übersetzungen zur Laufzeit laden\n\n`LOADRESOURCE()` schreibt eine Ressource nach `tmp/` und leert ihren Cache. Du kannst ein Objekt, ein Array oder eine URL übergeben:\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## Das Übersetzungswerkzeug\n\nDer Befehl `total4` erstellt und pflegt Ressourcendateien. Führ ihn im Stammverzeichnis der Anwendung aus:\n\n| Befehl | Was er tut |\n| --- | --- |\n| `total4 translate` | Findet jedes `@(Text)` in `.html`-, `.js`- und Sitemap-Dateien sowie Schlüssel von `$.invalid('key')` und schreibt `translate.resource` |\n| `total4 translate \"Text\"` | Gibt den Schlüssel eines Textes aus |\n| `total4 translate <file>` | Erstellt `translate.resource` aus einer Textdatei, ein Text pro Zeile |\n| `total4 translatecsv` | Schreibt die Texte in `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Erstellt eine Ressource aus den ersten beiden Spalten einer CSV-Datei |\n| `total4 diff <source> <target>` | Schreibt `<target>-diff.txt` mit Schlüsseln, die zum Ziel hinzugefügt bzw. daraus entfernt werden müssen |\n| `total4 merge <source> <target>` | Schreibt `<target>-merged.txt`: das Ziel mit Werten aus der Quelle |\n| `total4 clean <source>` | Schreibt `<source>-cleaned.txt` mit ausgerichteten Schlüsseln |\n\nEin typischer Ablauf: Führ `total4 translate` aus, kopiere `translate.resource` nach `resources/sk.resource`, übersetze die Werte und führ nach der nächsten Änderung `total4 diff translate.resource resources/sk.resource` aus, um neue Texte zu finden.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Localización","summary":"Traduce vistas, archivos estáticos, errores y correos electrónicos con archivos de recursos y un idioma para cada petición.","markdown":"---\ntitle: \"Localización\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localización\n\n> Traduce vistas, archivos estáticos, errores y correos electrónicos con archivos de recursos y un idioma para cada petición.\n\nTotal.js traduce texto con **archivos de recursos**. Un archivo de recursos es un archivo de texto plano con líneas `key : value` en el directorio `resources/`. El nombre del archivo es el nombre de un idioma: `resources/sk.resource` contiene los textos en eslovaco, `resources/de.resource` los textos en alemán. `resources/default.resource` es el respaldo para todos los idiomas.\n\nMarcas el texto en las vistas con `@(Text)`, eliges el idioma de cada petición en un delegado y el framework hace el resto: traduce vistas, archivos HTML estáticos, mensajes de error y asuntos de correo electrónico. La referencia exacta está en [Localización](../../reference/localization/).\n\n## Archivos de recursos\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nReglas del formato:\n\n- Una clave y un valor por línea, separados por ` : `. Deja un espacio después de los dos puntos: el parser omite el primer carácter después de `:`.\n- Las líneas que empiezan con `//` o `#` son comentarios; las líneas vacías se ignoran.\n- El valor ocupa una sola línea. Se eliminan los espacios iniciales y finales.\n- Las claves formadas por `T` y un hash en base 36 del texto son traducciones de `@(Text)`. No las escribes a mano: las crea el comando `total4 translate` (ver más abajo).\n\n`RESOURCE()` lee un valor por su clave:\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nCuando falta una clave en `sk.resource`, se usa el valor de `default.resource`. Cuando también falta allí, el resultado es una cadena vacía.\n\nUn recurso con un mismo nombre puede venir de varios lugares. El framework los une en este orden, y una línea posterior con la misma clave gana:\n\n1. archivos registrados con `F.register('/path/to/sk.resource')` (útil para paquetes y módulos),\n2. `tmp/sk.resource`, escrito por `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nLos recursos analizados se guardan en caché en `F.resources`. La caché se vacía cada 20 minutos (`default_interval_clear_resources`), así que los archivos modificados se vuelven a leer sin reiniciar.\n\n## Elegir el idioma de una petición\n\nEl idioma es una cadena: el nombre del archivo de recursos sin la extensión. Lo defines con `LOCALIZE()` y una función; la función se convierte en `DEF.onLocale`:\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nLa función se llama una vez por petición y debe devolver el idioma. El framework la llama:\n\n- para archivos estáticos, con `true` como tercer argumento,\n- para rutas, después de la autorización, así que `req.user` ya se conoce cuando usas `AUTH()`,\n- para conexiones WebSocket, solo con `req`.\n\nEl valor devuelto se guarda en `req.$language`. Desde ahí pasa a `controller.language`, a `client.language` en WebSockets y a `$.language` en esquemas, operaciones y middleware.\n\nCon la autorización de sesión integrada de `AUTH()`, usa la opción `locale` para tomar el idioma del usuario:\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Traducir vistas\n\nEscribe el texto del idioma predeterminado dentro de `@(...)`:\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` se reemplaza por la traducción del recurso de `controller.language`. La clave es `T` más un hash del texto. Cuando no hay traducción, se mantiene el texto original.\n- `@(#key)` lee `key` directamente del recurso.\n- `@{resource([name], key)}` imprime un valor del recurso, codificado en HTML. En las vistas, `language` contiene el idioma actual.\n- Cuando `@(...)` está entre comillas, las comillas de la traducción se escapan, así que es seguro en atributos y en scripts en línea.\n- `@{notranslate}` (o `@{nolocalize}`) en cualquier parte de una vista desactiva la traducción para esa vista.\n\nLa traducción ocurre cuando se compila la vista, así que una vista se compila una vez por cada idioma. En modo release las vistas compiladas se guardan en caché; en modo debug se vuelven a compilar en cada renderizado.\n\nCuando no existe ningún archivo para el idioma (por ejemplo, falta `fr.resource`), `@(Text)` mantiene el texto original.\n\nPuedes cambiar el idioma de una respuesta antes de renderizar la vista:\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## Archivos estáticos\n\nCon `allow_localize: true` (el valor predeterminado), los archivos `.html` y `.htm` de `public/` se traducen como las vistas: `@(Text)` se reemplaza y el resultado se guarda en caché por idioma en modo release.\n\n`LOCALIZE(url, [flags], [minify])` también traduce otros archivos:\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Traducir en el código\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nLas fechas usan recursos para los nombres de meses y días. `new Date().format('dddd d. MMMM yyyy', 'sk')` lee `January`…`December` y `Sunday`…`Saturday` como claves de `sk.resource`.\n\n## Mensajes de error\n\nLos errores de esquemas y operaciones se traducen con el idioma de la petición:\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- Un nombre corto sin espacios, dos puntos ni comas (`error-email`) es una clave de recurso.\n- `@(Text)` se traduce como en las vistas: `$.invalid('@(The e-mail is taken)')`.\n- Cualquier otro texto se envía tal cual.\n\nSin traducción, el mensaje es `The field \"name\" is invalid`. Usa `schema.setResource()` y `schema.setPrefix()` para leer los errores de un recurso fijo o con un prefijo de clave, y `ErrorBuilder.resource()` para tu propio `ErrorBuilder`.\n\n## Correos electrónicos\n\n`MAIL()` y `HTMLMAIL()` aceptan un idioma. El asunto se traduce y la vista de `MAIL()` se renderiza en ese idioma:\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` usa el idioma del controlador.\n\n## Cargar traducciones en tiempo de ejecución\n\n`LOADRESOURCE()` escribe un recurso en `tmp/` y vacía su caché. Puedes pasar un objeto, un array o una URL:\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## La herramienta de traducción\n\nEl comando `total4` crea y mantiene archivos de recursos. Ejecútalo en la raíz de la aplicación:\n\n| Comando | Qué hace |\n| --- | --- |\n| `total4 translate` | Busca cada `@(Text)` en archivos `.html`, `.js` y de sitemap, y las claves de `$.invalid('key')`, y escribe `translate.resource` |\n| `total4 translate \"Text\"` | Imprime la clave de un texto |\n| `total4 translate <file>` | Crea `translate.resource` a partir de un archivo de texto, un texto por línea |\n| `total4 translatecsv` | Escribe los textos en `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Crea un recurso a partir de las dos primeras columnas de un CSV |\n| `total4 diff <source> <target>` | Escribe `<target>-diff.txt` con las claves que hay que añadir al destino y quitar de él |\n| `total4 merge <source> <target>` | Escribe `<target>-merged.txt`: el destino con valores tomados del origen |\n| `total4 clean <source>` | Escribe `<source>-cleaned.txt` con las claves alineadas |\n\nUn flujo de trabajo típico: ejecuta `total4 translate`, copia `translate.resource` a `resources/sk.resource`, traduce los valores y, tras el siguiente cambio, ejecuta `total4 diff translate.resource resources/sk.resource` para encontrar los textos nuevos.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Localisation","summary":"Traduis les vues, les fichiers statiques, les erreurs et les e-mails avec des fichiers de ressources et une langue pour chaque requête.","markdown":"---\ntitle: Localisation\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localisation\n\n> Traduis les vues, les fichiers statiques, les erreurs et les e-mails avec des fichiers de ressources et une langue pour chaque requête.\n\nTotal.js traduit le texte avec des **fichiers de ressources**. Un fichier de ressources est un simple fichier texte contenant des lignes `key : value` dans le répertoire `resources/`. Le nom du fichier est le nom d'une langue : `resources/sk.resource` contient les textes slovaques, `resources/de.resource` les textes allemands. `resources/default.resource` sert de repli pour toutes les langues.\n\nTu marques le texte dans les vues avec `@(Text)`, tu choisis la langue de chaque requête dans un délégué, et le framework fait le reste : il traduit les vues, les fichiers HTML statiques, les messages d'erreur et les sujets des e-mails. La référence exacte se trouve dans [Localisation](../../reference/localization/).\n\n## Fichiers de ressources\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nRègles du format :\n\n- Une clé et une valeur par ligne, séparées par ` : `. Laisse un espace après les deux-points : l'analyseur ignore le premier caractère après `:`.\n- Les lignes qui commencent par `//` ou `#` sont des commentaires ; les lignes vides sont ignorées.\n- La valeur tient sur une ligne. Les espaces de début et de fin sont supprimés.\n- Les clés composées de `T` et d'un hachage en base 36 du texte sont des traductions de `@(Text)`. Tu ne les écris pas à la main : la commande `total4 translate` les crée (voir ci-dessous).\n\n`RESOURCE()` lit une valeur par sa clé :\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nQuand une clé manque dans `sk.resource`, la valeur de `default.resource` est utilisée. Quand elle y manque aussi, le résultat est une chaîne vide.\n\nUne ressource d'un même nom peut provenir de plusieurs endroits. Le framework les joint dans cet ordre, et une ligne ultérieure avec la même clé l'emporte :\n\n1. les fichiers enregistrés avec `F.register('/path/to/sk.resource')` (utile pour les paquets et les modules),\n2. `tmp/sk.resource`, écrit par `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nLes ressources analysées sont mises en cache dans `F.resources`. Le cache est vidé toutes les 20 minutes (`default_interval_clear_resources`), les fichiers modifiés sont donc relus sans redémarrage.\n\n## Choisir la langue d'une requête\n\nLa langue est une chaîne : le nom du fichier de ressources sans l'extension. Tu la définis avec `LOCALIZE()` et une fonction ; la fonction devient `DEF.onLocale` :\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nLa fonction est appelée une fois par requête et doit renvoyer la langue. Le framework l'appelle :\n\n- pour les fichiers statiques, avec `true` comme troisième argument,\n- pour les routes, après l'autorisation, donc `req.user` est déjà connu lorsque tu utilises `AUTH()`,\n- pour les connexions WebSocket, avec `req` uniquement.\n\nLa valeur renvoyée est stockée dans `req.$language`. De là, elle passe dans `controller.language`, `client.language` pour les WebSockets et `$.language` dans les schémas, les opérations et les middlewares.\n\nAvec l'autorisation par session intégrée de `AUTH()`, utilise l'option `locale` pour prendre la langue de l'utilisateur :\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Traduire les vues\n\nÉcris le texte de la langue par défaut dans `@(...)` :\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` est remplacé par la traduction issue de la ressource de `controller.language`. La clé est `T` suivi d'un hachage du texte. Sans traduction, le texte d'origine reste.\n- `@(#key)` lit `key` directement dans la ressource.\n- `@{resource([name], key)}` affiche une valeur de ressource, encodée en HTML. Dans les vues, `language` contient la langue courante.\n- Quand `@(...)` se trouve entre guillemets, les guillemets de la traduction sont échappés, c'est donc sûr dans les attributs et les scripts en ligne.\n- `@{notranslate}` (ou `@{nolocalize}`) n'importe où dans une vue désactive la traduction pour cette vue.\n\nLa traduction a lieu à la compilation de la vue, une vue est donc compilée une fois par langue. En mode release, les vues compilées sont mises en cache ; en mode debug, elles sont recompilées à chaque rendu.\n\nQuand aucun fichier n'existe pour la langue (par exemple `fr.resource` est absent), `@(Text)` garde le texte d'origine.\n\nTu peux changer la langue pour une réponse avant de rendre la vue :\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## Fichiers statiques\n\nAvec `allow_localize: true` (la valeur par défaut), les fichiers `.html` et `.htm` de `public/` sont traduits comme les vues : `@(Text)` est remplacé et le résultat est mis en cache par langue en mode release.\n\n`LOCALIZE(url, [flags], [minify])` traduit aussi d'autres fichiers :\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Traduire dans le code\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nLes dates utilisent les ressources pour les noms des mois et des jours. `new Date().format('dddd d. MMMM yyyy', 'sk')` lit `January`…`December` et `Sunday`…`Saturday` comme clés dans `sk.resource`.\n\n## Messages d'erreur\n\nLes erreurs des schémas et des opérations sont traduites dans la langue de la requête :\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- Un nom court sans espaces, deux-points ni virgules (`error-email`) est une clé de ressource.\n- `@(Text)` est traduit comme dans les vues : `$.invalid('@(The e-mail is taken)')`.\n- Tout autre texte est envoyé tel quel.\n\nSans traduction, le message est `The field \"name\" is invalid`. Utilise `schema.setResource()` et `schema.setPrefix()` pour lire les erreurs depuis une ressource fixe ou avec un préfixe de clé, et `ErrorBuilder.resource()` pour ton propre `ErrorBuilder`.\n\n## E-mails\n\n`MAIL()` et `HTMLMAIL()` acceptent une langue. Le sujet est traduit, et la vue de `MAIL()` est rendue dans cette langue :\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` utilise la langue du contrôleur.\n\n## Charger des traductions à l'exécution\n\n`LOADRESOURCE()` écrit une ressource dans `tmp/` et vide son cache. Tu peux passer un objet, un tableau ou une URL :\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## L'outil de traduction\n\nLa commande `total4` crée et maintient les fichiers de ressources. Exécute-la à la racine de l'application :\n\n| Commande | Ce qu'elle fait |\n| --- | --- |\n| `total4 translate` | Trouve chaque `@(Text)` dans les fichiers `.html`, `.js` et sitemap, ainsi que les clés de `$.invalid('key')`, et écrit `translate.resource` |\n| `total4 translate \"Text\"` | Affiche la clé d'un texte |\n| `total4 translate <file>` | Crée `translate.resource` à partir d'un fichier texte, un texte par ligne |\n| `total4 translatecsv` | Écrit les textes dans `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Crée une ressource à partir des deux premières colonnes d'un CSV |\n| `total4 diff <source> <target>` | Écrit `<target>-diff.txt` avec les clés à ajouter à la cible et à en retirer |\n| `total4 merge <source> <target>` | Écrit `<target>-merged.txt` : la cible avec les valeurs reprises de la source |\n| `total4 clean <source>` | Écrit `<source>-cleaned.txt` avec des clés alignées |\n\nUn flux de travail typique : exécute `total4 translate`, copie `translate.resource` vers `resources/sk.resource`, traduis les valeurs, et après la modification suivante exécute `total4 diff translate.resource resources/sk.resource` pour trouver les nouveaux textes.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Localizzazione","summary":"Traduci viste, file statici, errori ed e-mail con i file di risorse e una lingua per ogni richiesta.","markdown":"---\ntitle: Localizzazione\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localizzazione\n\n> Traduci viste, file statici, errori ed e-mail con i file di risorse e una lingua per ogni richiesta.\n\nTotal.js traduce il testo con i **file di risorse**. Un file di risorse è un semplice file di testo con righe `key : value` nella directory `resources/`. Il nome del file è il nome di una lingua: `resources/sk.resource` contiene i testi in slovacco, `resources/de.resource` quelli in tedesco. `resources/default.resource` è il fallback per ogni lingua.\n\nContrassegni il testo nelle viste con `@(Text)`, scegli la lingua di ogni richiesta in un delegato e il framework fa il resto: traduce viste, file HTML statici, messaggi di errore e oggetti delle e-mail. Il riferimento esatto è in [Localizzazione](../../reference/localization/).\n\n## File di risorse\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nRegole del formato:\n\n- Una chiave e un valore per riga, separati da ` : `. Lascia uno spazio dopo i due punti: il parser salta il primo carattere dopo `:`.\n- Le righe che iniziano con `//` o `#` sono commenti; le righe vuote vengono ignorate.\n- Il valore occupa una riga. Gli spazi iniziali e finali vengono rimossi.\n- Le chiavi composte da `T` e da un hash in base 36 del testo sono traduzioni di `@(Text)`. Non le scrivi a mano: le crea il comando `total4 translate` (vedi sotto).\n\n`RESOURCE()` legge un valore tramite la sua chiave:\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nQuando una chiave manca in `sk.resource`, viene usato il valore di `default.resource`. Quando manca anche lì, il risultato è una stringa vuota.\n\nUna risorsa con un certo nome può provenire da più posti. Il framework li unisce in questo ordine, e una riga successiva con la stessa chiave prevale:\n\n1. file registrati con `F.register('/path/to/sk.resource')` (utile per pacchetti e moduli),\n2. `tmp/sk.resource`, scritto da `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nLe risorse analizzate vengono messe in cache in `F.resources`. La cache viene svuotata ogni 20 minuti (`default_interval_clear_resources`), quindi i file modificati vengono riletti senza un riavvio.\n\n## Scegliere la lingua di una richiesta\n\nLa lingua è una stringa: il nome del file di risorse senza estensione. La imposti con `LOCALIZE()` e una funzione; la funzione diventa `DEF.onLocale`:\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nLa funzione viene chiamata una volta per richiesta e deve restituire la lingua. Il framework la chiama:\n\n- per i file statici, con `true` come terzo argomento,\n- per le route, dopo l'autorizzazione, quindi `req.user` è già noto quando usi `AUTH()`,\n- per le connessioni WebSocket, solo con `req`.\n\nIl valore restituito viene salvato in `req.$language`. Da lì passa a `controller.language`, a `client.language` nei WebSocket e a `$.language` in schemi, operazioni e middleware.\n\nCon l'autorizzazione di sessione integrata di `AUTH()`, usa l'opzione `locale` per prendere la lingua dall'utente:\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Tradurre le viste\n\nScrivi il testo della lingua predefinita dentro `@(...)`:\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` viene sostituito con la traduzione dalla risorsa di `controller.language`. La chiave è `T` più un hash del testo. Quando non c'è traduzione, resta il testo originale.\n- `@(#key)` legge `key` direttamente dalla risorsa.\n- `@{resource([name], key)}` stampa un valore di risorsa, codificato in HTML. Nelle viste, `language` contiene la lingua corrente.\n- Quando `@(...)` si trova tra virgolette, le virgolette nella traduzione vengono escapate, quindi è sicuro negli attributi e negli script inline.\n- `@{notranslate}` (o `@{nolocalize}`) in qualsiasi punto di una vista disattiva la traduzione per quella vista.\n\nLa traduzione avviene quando la vista viene compilata, quindi una vista viene compilata una volta per ogni lingua. In modalità release le viste compilate vengono messe in cache; in modalità debug vengono ricompilate a ogni render.\n\nQuando non esiste un file per la lingua (per esempio manca `fr.resource`), `@(Text)` mantiene il testo originale.\n\nPuoi cambiare la lingua per una singola risposta prima di fare il render della vista:\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## File statici\n\nCon `allow_localize: true` (il valore predefinito), i file `.html` e `.htm` di `public/` vengono tradotti come le viste: `@(Text)` viene sostituito e il risultato viene messo in cache per lingua in modalità release.\n\n`LOCALIZE(url, [flags], [minify])` traduce anche altri file:\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Tradurre nel codice\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nLe date usano le risorse per i nomi dei mesi e dei giorni. `new Date().format('dddd d. MMMM yyyy', 'sk')` legge `January`…`December` e `Sunday`…`Saturday` come chiavi da `sk.resource`.\n\n## Messaggi di errore\n\nGli errori di schemi e operazioni vengono tradotti con la lingua della richiesta:\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- Un nome breve senza spazi, due punti o virgole (`error-email`) è una chiave di risorsa.\n- `@(Text)` viene tradotto come nelle viste: `$.invalid('@(The e-mail is taken)')`.\n- Qualsiasi altro testo viene inviato così com'è.\n\nSenza traduzione il messaggio è `The field \"name\" is invalid`. Usa `schema.setResource()` e `schema.setPrefix()` per leggere gli errori da una risorsa fissa o con un prefisso di chiave, e `ErrorBuilder.resource()` per il tuo `ErrorBuilder`.\n\n## E-mail\n\n`MAIL()` e `HTMLMAIL()` accettano una lingua. L'oggetto viene tradotto e la vista di `MAIL()` viene renderizzata in quella lingua:\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` usa la lingua del controller.\n\n## Caricare traduzioni a runtime\n\n`LOADRESOURCE()` scrive una risorsa in `tmp/` e ne svuota la cache. Puoi passare un oggetto, un array o un URL:\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## Lo strumento di traduzione\n\nIl comando `total4` crea e mantiene i file di risorse. Eseguilo nella radice dell'applicazione:\n\n| Comando | Cosa fa |\n| --- | --- |\n| `total4 translate` | Trova ogni `@(Text)` nei file `.html`, `.js` e della sitemap, e le chiavi di `$.invalid('key')`, e scrive `translate.resource` |\n| `total4 translate \"Text\"` | Stampa la chiave di un testo |\n| `total4 translate <file>` | Crea `translate.resource` da un file di testo, un testo per riga |\n| `total4 translatecsv` | Scrive i testi in `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Crea una risorsa dalle prime due colonne di un CSV |\n| `total4 diff <source> <target>` | Scrive `<target>-diff.txt` con le chiavi da aggiungere e da rimuovere nel file di destinazione |\n| `total4 merge <source> <target>` | Scrive `<target>-merged.txt`: il file di destinazione con i valori presi dal file sorgente |\n| `total4 clean <source>` | Scrive `<source>-cleaned.txt` con le chiavi allineate |\n\nUn flusso di lavoro tipico: esegui `total4 translate`, copia `translate.resource` in `resources/sk.resource`, traduci i valori e, dopo la modifica successiva, esegui `total4 diff translate.resource resources/sk.resource` per trovare i nuovi testi.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSP60j61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/localization/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Lokalizácia","summary":"Prekladaj view, statické súbory, chyby a e-maily pomocou súborov zdrojov a jazyka pre každú požiadavku.","markdown":"---\ntitle: \"Lokalizácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Lokalizácia\n\n> Prekladaj view, statické súbory, chyby a e-maily pomocou súborov zdrojov a jazyka pre každú požiadavku.\n\nTotal.js prekladá text pomocou **súborov zdrojov**. Súbor zdroja je obyčajný textový súbor s riadkami `key : value` v adresári `resources/`. Názov súboru je názov jazyka: `resources/sk.resource` obsahuje slovenské texty, `resources/de.resource` nemecké. `resources/default.resource` je záloha pre každý jazyk.\n\nText vo view označíš cez `@(Text)`, jazyk každej požiadavky vyberieš v delegátovi a zvyšok urobí framework: preloží view, statické HTML súbory, chybové hlásenia a predmety e-mailov. Presnú referenciu nájdeš v [Lokalizácia](../../reference/localization/).\n\n## Súbory zdrojov\n\n```text\n// resources/sk.resource\n# Comments start with // or #\n\ntitle                : Moja stránka\nwelcome              : Vitajte\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\nPravidlá formátu:\n\n- Jeden kľúč a jedna hodnota na riadok, oddelené ` : `. Za dvojbodkou nechaj medzeru: parser preskočí prvý znak za `:`.\n- Riadky, ktoré začínajú `//` alebo `#`, sú komentáre; prázdne riadky sa ignorujú.\n- Hodnota je jeden riadok. Úvodné a koncové medzery sa odstránia.\n- Kľúče zložené z `T` a hashu textu v sústave 36 sú preklady `@(Text)`. Nepíšeš ich ručne: vytvára ich príkaz `total4 translate` (pozri nižšie).\n\n`RESOURCE()` prečíta hodnotu podľa kľúča:\n\n```js\nvar title = RESOURCE('sk', 'title');  // \"Moja stránka\"\nvar name = RESOURCE('title');          // reads resources/default.resource\n```\n\nKeď kľúč v `sk.resource` chýba, použije sa hodnota z `default.resource`. Keď chýba aj tam, výsledkom je prázdny reťazec.\n\nZdroj s jedným názvom môže pochádzať z viacerých miest. Framework ich spája v tomto poradí a neskorší riadok s rovnakým kľúčom vyhráva:\n\n1. súbory zaregistrované cez `F.register('/path/to/sk.resource')` (užitočné pre balíky a moduly),\n2. `tmp/sk.resource`, ktorý zapisuje `LOADRESOURCE()`,\n3. `resources/sk.resource`.\n\nSpracované zdroje sa ukladajú do cache v `F.resources`. Cache sa maže každých 20 minút (`default_interval_clear_resources`), takže zmenené súbory sa načítajú znova bez reštartu.\n\n## Výber jazyka požiadavky\n\nJazyk je reťazec: názov súboru zdroja bez prípony. Nastavíš ho cez `LOCALIZE()` a funkciu; funkcia sa stane `DEF.onLocale`:\n\n```js\n// definitions/localization.js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || req.cookie('language') || (req.headers['accept-language'] || '').substring(0, 2);\n\tswitch (lang) {\n\t\tcase 'sk':\n\t\tcase 'de':\n\t\t\treturn lang;\n\t}\n\treturn 'en';\n});\n```\n\nFunkcia sa volá raz pre každú požiadavku a musí vrátiť jazyk. Framework ju volá:\n\n- pre statické súbory, s `true` ako tretím argumentom,\n- pre routy, po autorizácii, takže `req.user` je už známy, keď používaš `AUTH()`,\n- pre WebSocket spojenia, iba s `req`.\n\nVrátená hodnota sa uloží do `req.$language`. Odtiaľ ide do `controller.language`, `client.language` vo WebSocketoch a `$.language` v schémach, operáciách a middleware.\n\nSo vstavanou session autorizáciou `AUTH()` použi voľbu `locale`, aby sa jazyk prevzal od používateľa:\n\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n## Preklad view\n\nText predvoleného jazyka napíš do `@(...)`:\n\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n<p>@{resource(language, 'title')}</p>\n<p>Language: @{language}</p>\n```\n\n- `@(Text)` sa nahradí prekladom zo zdroja jazyka `controller.language`. Kľúč je `T` plus hash textu. Keď preklad neexistuje, zostane pôvodný text.\n- `@(#key)` prečíta `key` priamo zo zdroja.\n- `@{resource([name], key)}` vypíše hodnotu zdroja, zakódovanú pre HTML. Vo view obsahuje `language` aktuálny jazyk.\n- Keď je `@(...)` v úvodzovkách, úvodzovky v preklade sa escapujú, takže je to bezpečné v atribútoch aj v inline skriptoch.\n- `@{notranslate}` (alebo `@{nolocalize}`) kdekoľvek vo view vypne preklad pre toto view.\n\nPreklad prebieha pri kompilácii view, takže view sa skompiluje raz pre každý jazyk. V release režime sa skompilované view ukladajú do cache; v debug režime sa kompilujú znova pri každom vykreslení.\n\nKeď pre jazyk neexistuje súbor (napríklad chýba `fr.resource`), `@(Text)` ponechá pôvodný text.\n\nJazyk môžeš pre jednu odpoveď zmeniť pred vykreslením view:\n\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n## Statické súbory\n\nS `allow_localize: true` (predvolené) sa súbory `.html` a `.htm` z `public/` prekladajú ako view: `@(Text)` sa nahradí a výsledok sa v release režime uloží do cache pre každý jazyk.\n\n`LOCALIZE(url, [flags], [minify])` prekladá aj iné súbory:\n\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n## Preklad v kóde\n\n```js\nTRANSLATE('sk', 'Add to cart');          // the translation of @(Add to cart), or the text\nTRANSLATE('sk', '#welcome');              // the same as RESOURCE('sk', 'welcome')\nTRANSLATOR('sk', '<b>@(Products)</b>');  // replaces every @(...) in a string\n```\n\nDátumy používajú zdroje pre názvy mesiacov a dní. `new Date().format('dddd d. MMMM yyyy', 'sk')` číta `January`…`December` a `Sunday`…`Saturday` ako kľúče zo `sk.resource`.\n\n## Chybové hlásenia\n\nChyby schém a operácií sa prekladajú do jazyka požiadavky:\n\n```js\n// resources/en.resource\n// error-email            : Please enter a valid e-mail address\n\nNEWSCHEMA('Contact', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addWorkflow('send', function($) {\n\t\tif (!$.model.email.endsWith('.com')) {\n\t\t\t$.invalid('error-email');\n\t\t\treturn;\n\t\t}\n\t\t$.success();\n\t});\n});\n```\n\n- Krátky názov bez medzier, dvojbodiek a čiarok (`error-email`) je kľúč zdroja.\n- `@(Text)` sa prekladá ako vo view: `$.invalid('@(The e-mail is taken)')`.\n- Akýkoľvek iný text sa pošle tak, ako je.\n\nBez prekladu je hlásenie `The field \"name\" is invalid`. Použi `schema.setResource()` a `schema.setPrefix()`, aby sa chyby čítali z pevného zdroja alebo s prefixom kľúča, a `ErrorBuilder.resource()` pre vlastný `ErrorBuilder`.\n\n## E-maily\n\n`MAIL()` a `HTMLMAIL()` prijímajú jazyk. Predmet sa preloží a view pre `MAIL()` sa vykreslí v tomto jazyku:\n\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n`controller.mail()` používa jazyk kontroléra.\n\n## Načítanie prekladov za behu\n\n`LOADRESOURCE()` zapíše zdroj do `tmp/` a vymaže jeho cache. Môžeš odovzdať objekt, pole alebo URL:\n\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');  // { sk: {...}, de: {...} }\n```\n\n## Nástroj na preklad\n\nPríkaz `total4` vytvára a udržiava súbory zdrojov. Spusti ho v koreni aplikácie:\n\n| Príkaz | Čo robí |\n| --- | --- |\n| `total4 translate` | Nájde každý `@(Text)` v súboroch `.html`, `.js` a sitemap a kľúče `$.invalid('key')` a zapíše `translate.resource` |\n| `total4 translate \"Text\"` | Vypíše kľúč jedného textu |\n| `total4 translate <file>` | Vytvorí `translate.resource` z textového súboru, jeden text na riadok |\n| `total4 translatecsv` | Zapíše texty do `translate.csv` (`Hash;Text;Translation`) |\n| `total4 csv <file.csv>` | Vytvorí zdroj z prvých dvoch stĺpcov CSV |\n| `total4 diff <source> <target>` | Zapíše `<target>-diff.txt` s kľúčmi, ktoré treba do cieľa pridať a z cieľa odstrániť |\n| `total4 merge <source> <target>` | Zapíše `<target>-merged.txt`: cieľ s hodnotami prevzatými zo zdrojového súboru |\n| `total4 clean <source>` | Zapíše `<source>-cleaned.txt` so zarovnanými kľúčmi |\n\nTypický postup: spusti `total4 translate`, skopíruj `translate.resource` do `resources/sk.resource`, prelož hodnoty a po ďalšej zmene spusti `total4 diff translate.resource resources/sk.resource`, aby si našiel nové texty.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabmGT3ii61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"HTTP requests","summary":"Call other HTTP services with RESTBuilder, REQUEST() and DOWNLOAD().","markdown":"---\ntitle: HTTP requests\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTTP requests\n\n> Call other HTTP services with RESTBuilder, REQUEST() and DOWNLOAD().\n\nTotal.js has three tools for calling other HTTP services from your application:\n\n- **`RESTBuilder`** builds a request step by step, sends it and parses the answer (JSON, XML or URL-encoded). Use it for REST APIs.\n- **`REQUEST(options, [callback])`** is the low-level HTTP client that `RESTBuilder` uses. It returns the raw body, or a stream.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** saves a response straight into a file.\n\nAll three are global: you can use them in controllers, schemas, definitions and modules without `require()`.\n\n## RESTBuilder\n\nA static method creates the builder for the HTTP method you need. The data you pass to `POST`, `PUT`, `PATCH` and `DELETE` is sent as JSON; the data of `GET` becomes the query string.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nThe callback receives three arguments:\n\n| Argument | What it contains |\n| --- | --- |\n| `err` | An error, or `null` |\n| `response` | The parsed body: an object for JSON, XML and URL-encoded answers, otherwise an empty object |\n| `output` | Details: `value`, `response` (the raw body), `status`, `headers`, `hostname`, `origin`, `cache` and the method `cookie(name)` |\n\nA status code `400` or higher is **not** an error by default: check `output.status`, or call `strict()` to get the status code as `err`. When the service answers with a Total.js error array (`[{ name, error }]`), `err` is an `ErrorBuilder` with those errors.\n\n### Promises\n\n`promise()` sends the request and returns a promise of the parsed body. Pass `$` (the options of a schema operation) and the error goes to `$.invalid()` instead of rejecting the promise.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\n`callback()` without a function also returns a promise.\n\n### Building the request\n\nEvery method returns the builder, so you can chain them. Nothing is sent until you call `callback()`, `exec()`, `promise()` or `stream()`.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Area | Methods |\n| --- | --- |\n| Address and method | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| Headers | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Body | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookies | `cookie()`, `cookies()`, `cook()` |\n| Connection | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Response | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Sending | `callback()`, `exec()`, `promise()`, `stream()` |\n\nThe default timeout is 10 seconds. The builder sends `User-Agent: Total.js/v...` and accepts JSON, text and XML.\n\n### Uploading files\n\n`file()` adds a file and switches the request to `multipart/form-data` (a `GET` becomes a `POST`). The content can be a path, a `Buffer` or a URL that the framework downloads and forwards. `set()` adds plain form fields.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Shaping the response\n\n- `schema(name)` validates the response with a schema and returns the model. A status code `400` or higher is an error here.\n- `map('id:number,name:string')` keeps only the listed fields and converts them; `id:number:itemid` also renames `id` to `itemid`.\n- `convert('price:number,date:date')` converts fields of the response with `CONVERT()`.\n- `cache('5 minutes')` caches a successful (`200`) response in `F.cache`.\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Calling Total.js API endpoints\n\n`RESTBuilder.API(url, operation, [data])` sends a `POST` with the JSON `{ schema: operation, data: data }`, the format of Total.js API routes:\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Global changes\n\n`RESTBuilder.upgrade(fn)` runs `fn(builder)` for every builder before it sends the request, for example to add a header to all requests. `RESTBuilder.addTransform(name, fn, [isDefault])` registers a function that changes every parsed response.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` sends one HTTP request. The body you send must be a string or a `Buffer`; the response body is a string for text and `application/*` types, otherwise a `Buffer`. Without a callback it returns a promise.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nWith `custom: true` you get `response.stream` (the incoming message) instead of the body. The framework follows `301` and `302` redirects and copies their cookies to the next request; `noredirect: true` turns that off.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` writes the response into a file. A relative URL (`/sitemap.xml`) is requested from your own running application.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` sends every request through a proxy server, except requests to `localhost`, `127.0.0.1` and `0.0.0.0`. `proxy(url)` and the `proxy` option set a proxy for one request. The value can contain credentials: `http://user:password@proxy.example.com:8080`.\n\nThe configuration key `default_restbuilder_timeout` (default `10000`) is the timeout of `REQUEST()` calls without their own `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmGT3ii61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"HTTP-Requests","summary":"Rufe andere HTTP-Dienste mit RESTBuilder, REQUEST() und DOWNLOAD() auf.","markdown":"---\ntitle: HTTP-Requests\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTTP-Requests\n\n> Rufe andere HTTP-Dienste mit RESTBuilder, REQUEST() und DOWNLOAD() auf.\n\nTotal.js hat drei Werkzeuge, um aus deiner Anwendung andere HTTP-Dienste aufzurufen:\n\n- **`RESTBuilder`** baut einen Request Schritt für Schritt auf, sendet ihn und parst die Antwort (JSON, XML oder URL-kodiert). Verwende ihn für REST-APIs.\n- **`REQUEST(options, [callback])`** ist der Low-Level-HTTP-Client, den `RESTBuilder` verwendet. Er gibt den rohen Body oder einen Stream zurück.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** speichert eine Response direkt in eine Datei.\n\nAlle drei sind global: Du kannst sie in Controllern, Schemas, Definitionen und Modulen ohne `require()` verwenden.\n\n## RESTBuilder\n\nEine statische Methode erstellt den Builder für die HTTP-Methode, die du brauchst. Die Daten, die du an `POST`, `PUT`, `PATCH` und `DELETE` übergibst, werden als JSON gesendet; die Daten von `GET` werden zum Query-String.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nDer Callback erhält drei Argumente:\n\n| Argument | Was es enthält |\n| --- | --- |\n| `err` | Ein Fehler oder `null` |\n| `response` | Der geparste Body: ein Objekt bei JSON-, XML- und URL-kodierten Antworten, sonst ein leeres Objekt |\n| `output` | Details: `value`, `response` (der rohe Body), `status`, `headers`, `hostname`, `origin`, `cache` und die Methode `cookie(name)` |\n\nEin Statuscode ab `400` ist standardmäßig **kein** Fehler: Prüfe `output.status` oder rufe `strict()` auf, um den Statuscode als `err` zu bekommen. Antwortet der Dienst mit einem Total.js-Fehler-Array (`[{ name, error }]`), ist `err` ein `ErrorBuilder` mit diesen Fehlern.\n\n### Promises\n\n`promise()` sendet den Request und gibt eine Promise des geparsten Bodys zurück. Übergib `$` (die Optionen einer Schema-Operation), und der Fehler geht an `$.invalid()`, statt die Promise abzulehnen.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\n`callback()` ohne Funktion gibt ebenfalls eine Promise zurück.\n\n### Den Request aufbauen\n\nJede Methode gibt den Builder zurück, sodass du sie verketten kannst. Nichts wird gesendet, bis du `callback()`, `exec()`, `promise()` oder `stream()` aufrufst.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Bereich | Methoden |\n| --- | --- |\n| Adresse und Methode | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| Header | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Body | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookies | `cookie()`, `cookies()`, `cook()` |\n| Verbindung | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Response | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Senden | `callback()`, `exec()`, `promise()`, `stream()` |\n\nDer Standard-Timeout beträgt 10 Sekunden. Der Builder sendet `User-Agent: Total.js/v...` und akzeptiert JSON, Text und XML.\n\n### Dateien hochladen\n\n`file()` fügt eine Datei hinzu und stellt den Request auf `multipart/form-data` um (ein `GET` wird zu einem `POST`). Der Inhalt kann ein Pfad, ein `Buffer` oder eine URL sein, die das Framework herunterlädt und weiterleitet. `set()` fügt einfache Formularfelder hinzu.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Die Response formen\n\n- `schema(name)` validiert die Response mit einem Schema und gibt das Modell zurück. Ein Statuscode ab `400` ist hier ein Fehler.\n- `map('id:number,name:string')` behält nur die aufgeführten Felder und wandelt sie um; `id:number:itemid` benennt außerdem `id` in `itemid` um.\n- `convert('price:number,date:date')` wandelt Felder der Response mit `CONVERT()` um.\n- `cache('5 minutes')` speichert eine erfolgreiche (`200`) Response in `F.cache` zwischen.\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Total.js-API-Endpunkte aufrufen\n\n`RESTBuilder.API(url, operation, [data])` sendet ein `POST` mit dem JSON `{ schema: operation, data: data }`, dem Format von Total.js-API-Routen:\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Globale Änderungen\n\n`RESTBuilder.upgrade(fn)` führt `fn(builder)` für jeden Builder aus, bevor er den Request sendet, zum Beispiel um allen Requests einen Header hinzuzufügen. `RESTBuilder.addTransform(name, fn, [isDefault])` registriert eine Funktion, die jede geparste Response ändert.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` sendet einen HTTP-Request. Der Body, den du sendest, muss ein String oder ein `Buffer` sein; der Body der Response ist bei Text und `application/*`-Typen ein String, sonst ein `Buffer`. Ohne Callback gibt es eine Promise zurück.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nMit `custom: true` bekommst du `response.stream` (die eingehende Nachricht) statt des Bodys. Das Framework folgt `301`- und `302`-Weiterleitungen und kopiert ihre Cookies in den nächsten Request; `noredirect: true` schaltet das ab.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` schreibt die Response in eine Datei. Eine relative URL (`/sitemap.xml`) wird von deiner eigenen laufenden Anwendung angefordert.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` schickt jeden Request über einen Proxy-Server, außer Requests an `localhost`, `127.0.0.1` und `0.0.0.0`. `proxy(url)` und die Option `proxy` setzen einen Proxy für einen einzelnen Request. Der Wert kann Zugangsdaten enthalten: `http://user:password@proxy.example.com:8080`.\n\nDer Konfigurationsschlüssel `default_restbuilder_timeout` (Standard `10000`) ist der Timeout von `REQUEST()`-Aufrufen ohne eigenen `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmGT3ii61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Peticiones HTTP","summary":"Llama a otros servicios HTTP con RESTBuilder, REQUEST() y DOWNLOAD().","markdown":"---\ntitle: Peticiones HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Peticiones HTTP\n\n> Llama a otros servicios HTTP con RESTBuilder, REQUEST() y DOWNLOAD().\n\nTotal.js tiene tres herramientas para llamar a otros servicios HTTP desde tu aplicación:\n\n- **`RESTBuilder`** construye una petición paso a paso, la envía y analiza la respuesta (JSON, XML o URL-encoded). Úsalo para APIs REST.\n- **`REQUEST(options, [callback])`** es el cliente HTTP de bajo nivel que usa `RESTBuilder`. Devuelve el cuerpo sin procesar, o un stream.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** guarda una respuesta directamente en un archivo.\n\nLas tres son globales: puedes usarlas en controladores, esquemas, definiciones y módulos sin `require()`.\n\n## RESTBuilder\n\nUn método estático crea el builder para el método HTTP que necesitas. Los datos que pasas a `POST`, `PUT`, `PATCH` y `DELETE` se envían como JSON; los datos de `GET` se convierten en la query string.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nEl callback recibe tres argumentos:\n\n| Argumento | Qué contiene |\n| --- | --- |\n| `err` | Un error, o `null` |\n| `response` | El cuerpo analizado: un objeto para las respuestas JSON, XML y URL-encoded; en otro caso, un objeto vacío |\n| `output` | Detalles: `value`, `response` (el cuerpo sin procesar), `status`, `headers`, `hostname`, `origin`, `cache` y el método `cookie(name)` |\n\nUn código de estado `400` o superior **no** es un error por defecto: comprueba `output.status`, o llama a `strict()` para obtener el código de estado como `err`. Cuando el servicio responde con un array de errores de Total.js (`[{ name, error }]`), `err` es un `ErrorBuilder` con esos errores.\n\n### Promesas\n\n`promise()` envía la petición y devuelve una promesa del cuerpo analizado. Pasa `$` (las opciones de una operación de esquema) y el error va a `$.invalid()` en lugar de rechazar la promesa.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\n`callback()` sin función también devuelve una promesa.\n\n### Construir la petición\n\nCada método devuelve el builder, así que puedes encadenarlos. No se envía nada hasta que llamas a `callback()`, `exec()`, `promise()` o `stream()`.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Área | Métodos |\n| --- | --- |\n| Dirección y método | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| Cabeceras | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Cuerpo | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookies | `cookie()`, `cookies()`, `cook()` |\n| Conexión | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Respuesta | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Envío | `callback()`, `exec()`, `promise()`, `stream()` |\n\nEl tiempo límite por defecto es de 10 segundos. El builder envía `User-Agent: Total.js/v...` y acepta JSON, texto y XML.\n\n### Subir archivos\n\n`file()` añade un archivo y cambia la petición a `multipart/form-data` (un `GET` se convierte en un `POST`). El contenido puede ser una ruta, un `Buffer` o una URL que el framework descarga y reenvía. `set()` añade campos de formulario simples.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Dar forma a la respuesta\n\n- `schema(name)` valida la respuesta con un esquema y devuelve el modelo. Aquí un código de estado `400` o superior es un error.\n- `map('id:number,name:string')` conserva solo los campos listados y los convierte; `id:number:itemid` además renombra `id` a `itemid`.\n- `convert('price:number,date:date')` convierte campos de la respuesta con `CONVERT()`.\n- `cache('5 minutes')` guarda en caché una respuesta correcta (`200`) en `F.cache`.\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Llamar a endpoints de API de Total.js\n\n`RESTBuilder.API(url, operation, [data])` envía un `POST` con el JSON `{ schema: operation, data: data }`, el formato de las rutas API de Total.js:\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Cambios globales\n\n`RESTBuilder.upgrade(fn)` ejecuta `fn(builder)` para cada builder antes de que envíe la petición, por ejemplo para añadir una cabecera a todas las peticiones. `RESTBuilder.addTransform(name, fn, [isDefault])` registra una función que modifica cada respuesta analizada.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` envía una petición HTTP. El cuerpo que envías debe ser un string o un `Buffer`; el cuerpo de la respuesta es un string para los tipos de texto y `application/*`, y en otro caso un `Buffer`. Sin callback devuelve una promesa.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nCon `custom: true` obtienes `response.stream` (el mensaje entrante) en lugar del cuerpo. El framework sigue las redirecciones `301` y `302` y copia sus cookies a la siguiente petición; `noredirect: true` lo desactiva.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` escribe la respuesta en un archivo. Una URL relativa (`/sitemap.xml`) se pide a tu propia aplicación en ejecución.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` envía cada petición a través de un servidor proxy, excepto las peticiones a `localhost`, `127.0.0.1` y `0.0.0.0`. `proxy(url)` y la opción `proxy` definen un proxy para una sola petición. El valor puede contener credenciales: `http://user:password@proxy.example.com:8080`.\n\nLa clave de configuración `default_restbuilder_timeout` (por defecto `10000`) es el tiempo límite de las llamadas a `REQUEST()` sin su propio `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmGT3ii61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Requêtes HTTP","summary":"Appelle d'autres services HTTP avec RESTBuilder, REQUEST() et DOWNLOAD().","markdown":"---\ntitle: \"Requêtes HTTP\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Requêtes HTTP\n\n> Appelle d'autres services HTTP avec RESTBuilder, REQUEST() et DOWNLOAD().\n\nTotal.js dispose de trois outils pour appeler d'autres services HTTP depuis ton application :\n\n- **`RESTBuilder`** construit une requête étape par étape, l'envoie et analyse la réponse (JSON, XML ou URL-encoded). Utilise-le pour les API REST.\n- **`REQUEST(options, [callback])`** est le client HTTP de bas niveau qu'utilise `RESTBuilder`. Il renvoie le corps brut, ou un flux.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** enregistre une réponse directement dans un fichier.\n\nLes trois sont globaux : tu peux les utiliser dans les contrôleurs, les schémas, les définitions et les modules sans `require()`.\n\n## RESTBuilder\n\nUne méthode statique crée le builder pour la méthode HTTP dont tu as besoin. Les données que tu passes à `POST`, `PUT`, `PATCH` et `DELETE` sont envoyées en JSON ; les données de `GET` deviennent la query string.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nLe callback reçoit trois arguments :\n\n| Argument | Ce qu'il contient |\n| --- | --- |\n| `err` | Une erreur, ou `null` |\n| `response` | Le corps analysé : un objet pour les réponses JSON, XML et URL-encoded, sinon un objet vide |\n| `output` | Les détails : `value`, `response` (le corps brut), `status`, `headers`, `hostname`, `origin`, `cache` et la méthode `cookie(name)` |\n\nUn code de statut `400` ou supérieur n'est **pas** une erreur par défaut : vérifie `output.status`, ou appelle `strict()` pour obtenir le code de statut dans `err`. Quand le service répond avec un tableau d'erreurs Total.js (`[{ name, error }]`), `err` est un `ErrorBuilder` contenant ces erreurs.\n\n### Promesses\n\n`promise()` envoie la requête et renvoie une promesse du corps analysé. Passe `$` (les options d'une opération de schéma) et l'erreur va à `$.invalid()` au lieu de rejeter la promesse.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\n`callback()` sans fonction renvoie aussi une promesse.\n\n### Construire la requête\n\nChaque méthode renvoie le builder ; tu peux donc les enchaîner. Rien n'est envoyé tant que tu n'appelles pas `callback()`, `exec()`, `promise()` ou `stream()`.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Domaine | Méthodes |\n| --- | --- |\n| Adresse et méthode | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| En-têtes | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Corps | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookies | `cookie()`, `cookies()`, `cook()` |\n| Connexion | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Réponse | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Envoi | `callback()`, `exec()`, `promise()`, `stream()` |\n\nLe délai d'expiration par défaut est de 10 secondes. Le builder envoie `User-Agent: Total.js/v...` et accepte JSON, texte et XML.\n\n### Envoyer des fichiers\n\n`file()` ajoute un fichier et fait passer la requête en `multipart/form-data` (un `GET` devient un `POST`). Le contenu peut être un chemin, un `Buffer` ou une URL que le framework télécharge et transmet. `set()` ajoute de simples champs de formulaire.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Façonner la réponse\n\n- `schema(name)` valide la réponse avec un schéma et renvoie le modèle. Ici, un code de statut `400` ou supérieur est une erreur.\n- `map('id:number,name:string')` ne conserve que les champs listés et les convertit ; `id:number:itemid` renomme aussi `id` en `itemid`.\n- `convert('price:number,date:date')` convertit des champs de la réponse avec `CONVERT()`.\n- `cache('5 minutes')` met en cache une réponse réussie (`200`) dans `F.cache`.\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Appeler des points d'accès d'API Total.js\n\n`RESTBuilder.API(url, operation, [data])` envoie un `POST` avec le JSON `{ schema: operation, data: data }`, le format des routes d'API Total.js :\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Modifications globales\n\n`RESTBuilder.upgrade(fn)` exécute `fn(builder)` pour chaque builder avant l'envoi de la requête, par exemple pour ajouter un en-tête à toutes les requêtes. `RESTBuilder.addTransform(name, fn, [isDefault])` enregistre une fonction qui modifie chaque réponse analysée.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` envoie une requête HTTP. Le corps que tu envoies doit être une chaîne ou un `Buffer` ; le corps de la réponse est une chaîne pour les types texte et `application/*`, sinon un `Buffer`. Sans callback, il renvoie une promesse.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nAvec `custom: true`, tu obtiens `response.stream` (le message entrant) au lieu du corps. Le framework suit les redirections `301` et `302` et copie leurs cookies vers la requête suivante ; `noredirect: true` désactive ce comportement.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` écrit la réponse dans un fichier. Une URL relative (`/sitemap.xml`) est demandée à ta propre application en cours d'exécution.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` fait passer chaque requête par un serveur proxy, sauf les requêtes vers `localhost`, `127.0.0.1` et `0.0.0.0`. `proxy(url)` et l'option `proxy` définissent un proxy pour une seule requête. La valeur peut contenir des identifiants : `http://user:password@proxy.example.com:8080`.\n\nLa clé de configuration `default_restbuilder_timeout` (par défaut `10000`) est le délai d'expiration des appels `REQUEST()` qui n'ont pas leur propre `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmGT3ii61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Richieste HTTP","summary":"Chiama altri servizi HTTP con RESTBuilder, REQUEST() e DOWNLOAD().","markdown":"---\ntitle: Richieste HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Richieste HTTP\n\n> Chiama altri servizi HTTP con RESTBuilder, REQUEST() e DOWNLOAD().\n\nTotal.js ha tre strumenti per chiamare altri servizi HTTP dalla tua applicazione:\n\n- **`RESTBuilder`** costruisce una richiesta passo dopo passo, la invia e analizza la risposta (JSON, XML o URL-encoded). Usalo per le API REST.\n- **`REQUEST(options, [callback])`** è il client HTTP di basso livello che `RESTBuilder` usa. Restituisce il corpo grezzo, oppure uno stream.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** salva una risposta direttamente in un file.\n\nTutti e tre sono globali: puoi usarli in controller, schemi, definizioni e moduli senza `require()`.\n\n## RESTBuilder\n\nUn metodo statico crea il builder per il metodo HTTP che ti serve. I dati che passi a `POST`, `PUT`, `PATCH` e `DELETE` vengono inviati come JSON; i dati di `GET` diventano la query string.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nLa callback riceve tre argomenti:\n\n| Argomento | Cosa contiene |\n| --- | --- |\n| `err` | Un errore, oppure `null` |\n| `response` | Il corpo analizzato: un oggetto per le risposte JSON, XML e URL-encoded, altrimenti un oggetto vuoto |\n| `output` | Dettagli: `value`, `response` (il corpo grezzo), `status`, `headers`, `hostname`, `origin`, `cache` e il metodo `cookie(name)` |\n\nUn codice di stato `400` o superiore **non** è un errore per impostazione predefinita: controlla `output.status`, oppure chiama `strict()` per ottenere il codice di stato come `err`. Quando il servizio risponde con un array di errori Total.js (`[{ name, error }]`), `err` è un `ErrorBuilder` con quegli errori.\n\n### Promise\n\n`promise()` invia la richiesta e restituisce una promise del corpo analizzato. Passa `$` (le opzioni di un'operazione di schema) e l'errore va a `$.invalid()` invece di rifiutare la promise.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\nAnche `callback()` senza una funzione restituisce una promise.\n\n### Costruire la richiesta\n\nOgni metodo restituisce il builder, così puoi concatenarli. Non viene inviato nulla finché non chiami `callback()`, `exec()`, `promise()` o `stream()`.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Ambito | Metodi |\n| --- | --- |\n| Indirizzo e metodo | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| Intestazioni | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Corpo | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookie | `cookie()`, `cookies()`, `cook()` |\n| Connessione | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Risposta | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Invio | `callback()`, `exec()`, `promise()`, `stream()` |\n\nIl timeout predefinito è di 10 secondi. Il builder invia `User-Agent: Total.js/v...` e accetta JSON, testo e XML.\n\n### Caricare file\n\n`file()` aggiunge un file e fa passare la richiesta a `multipart/form-data` (un `GET` diventa un `POST`). Il contenuto può essere un percorso, un `Buffer` o un URL che il framework scarica e inoltra. `set()` aggiunge campi semplici del form.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Dare forma alla risposta\n\n- `schema(name)` valida la risposta con uno schema e restituisce il modello. Qui un codice di stato `400` o superiore è un errore.\n- `map('id:number,name:string')` mantiene solo i campi elencati e li converte; `id:number:itemid` rinomina anche `id` in `itemid`.\n- `convert('price:number,date:date')` converte i campi della risposta con `CONVERT()`.\n- `cache('5 minutes')` mette in cache in `F.cache` una risposta riuscita (`200`).\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Chiamare gli endpoint API di Total.js\n\n`RESTBuilder.API(url, operation, [data])` invia un `POST` con il JSON `{ schema: operation, data: data }`, il formato delle route API di Total.js:\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Modifiche globali\n\n`RESTBuilder.upgrade(fn)` esegue `fn(builder)` per ogni builder prima che invii la richiesta, per esempio per aggiungere un'intestazione a tutte le richieste. `RESTBuilder.addTransform(name, fn, [isDefault])` registra una funzione che modifica ogni risposta analizzata.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` invia una singola richiesta HTTP. Il corpo che invii deve essere una stringa o un `Buffer`; il corpo della risposta è una stringa per i tipi di testo e `application/*`, altrimenti un `Buffer`. Senza callback restituisce una promise.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nCon `custom: true` ottieni `response.stream` (il messaggio in arrivo) invece del corpo. Il framework segue i redirect `301` e `302` e copia i loro cookie nella richiesta successiva; `noredirect: true` lo disattiva.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` scrive la risposta in un file. Un URL relativo (`/sitemap.xml`) viene richiesto alla tua stessa applicazione in esecuzione.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` invia ogni richiesta attraverso un server proxy, tranne le richieste a `localhost`, `127.0.0.1` e `0.0.0.0`. `proxy(url)` e l'opzione `proxy` impostano un proxy per una singola richiesta. Il valore può contenere credenziali: `http://user:password@proxy.example.com:8080`.\n\nLa chiave di configurazione `default_restbuilder_timeout` (predefinito `10000`) è il timeout delle chiamate `REQUEST()` senza un proprio `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmGT3ii61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/http-requests/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"HTTP požiadavky","summary":"Volaj iné HTTP služby cez RESTBuilder, REQUEST() a DOWNLOAD().","markdown":"---\ntitle: \"HTTP požiadavky\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/http-requests/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTTP požiadavky\n\n> Volaj iné HTTP služby cez RESTBuilder, REQUEST() a DOWNLOAD().\n\nTotal.js má tri nástroje na volanie iných HTTP služieb z tvojej aplikácie:\n\n- **`RESTBuilder`** zostaví požiadavku krok za krokom, pošle ju a sparsuje odpoveď (JSON, XML alebo URL-encoded). Použi ho pre REST API.\n- **`REQUEST(options, [callback])`** je nízkoúrovňový HTTP klient, ktorý používa `RESTBuilder`. Vracia surové telo alebo stream.\n- **`DOWNLOAD(url, filename, [callback], [timeout])`** uloží odpoveď priamo do súboru.\n\nVšetky tri sú globálne: môžeš ich používať v kontroléroch, schémach, definíciách a moduloch bez `require()`.\n\n## RESTBuilder\n\nStatická metóda vytvorí builder pre HTTP metódu, ktorú potrebuješ. Dáta, ktoré odovzdáš do `POST`, `PUT`, `PATCH` a `DELETE`, sa pošlú ako JSON; dáta `GET` sa stanú query stringom.\n\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 1 }).callback(function(err, response, output) {\n\tif (err) {\n\t\tconsole.log('Error:', err);\n\t\treturn;\n\t}\n\tconsole.log(response);      // the parsed body\n\tconsole.log(output.status); // the HTTP status code\n});\n\nRESTBuilder.POST('https://api.example.com/orders/', { product: 'P01', count: 2 }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\nCallback dostane tri argumenty:\n\n| Argument | Čo obsahuje |\n| --- | --- |\n| `err` | Chybu alebo `null` |\n| `response` | Sparsované telo: objekt pre odpovede JSON, XML a URL-encoded, inak prázdny objekt |\n| `output` | Podrobnosti: `value`, `response` (surové telo), `status`, `headers`, `hostname`, `origin`, `cache` a metóda `cookie(name)` |\n\nStavový kód `400` alebo vyšší predvolene **nie je** chyba: kontroluj `output.status` alebo zavolaj `strict()`, ak chceš stavový kód dostať ako `err`. Keď služba odpovie poľom chýb Total.js (`[{ name, error }]`), `err` je `ErrorBuilder` s týmito chybami.\n\n### Promises\n\n`promise()` pošle požiadavku a vráti promise sparsovaného tela. Odovzdaj `$` (voľby operácie schémy) a chyba pôjde do `$.invalid()` namiesto zamietnutia promise.\n\n```js\nNEWSCHEMA('Weather', function(schema) {\n\tschema.action('current', {\n\t\tname: 'Current weather',\n\t\taction: async function($) {\n\t\t\tvar data = await RESTBuilder.GET('https://api.example.com/weather/', { city: 'Bratislava' }).promise($);\n\t\t\t$.callback(data);\n\t\t}\n\t});\n});\n```\n\n`callback()` bez funkcie tiež vráti promise.\n\n### Zostavenie požiadavky\n\nKaždá metóda vracia builder, takže ich môžeš reťaziť. Nič sa nepošle, kým nezavoláš `callback()`, `exec()`, `promise()` alebo `stream()`.\n\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/invoices/');\n\tbuilder.method('POST');\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.auth('user', 'password');\n\tbuilder.timeout(5000);\n\tbuilder.json({ number: '2024001', total: 120 });\n\tbuilder.callback(function(err, response, output) {\n\t\tconsole.log(output.status, response);\n\t});\n});\n```\n\n| Oblasť | Metódy |\n| --- | --- |\n| Adresa a metóda | `url()`, `method()`, `get()`, `post()`, `put()`, `patch()`, `delete()`, `head()` |\n| Hlavičky | `header()`, `type()`, `accept()`, `auth()`, `referrer()`, `xhr()` |\n| Telo | `json()`, `urlencoded()`, `xml()`, `plain()`, `raw()`, `set()`, `rem()`, `file()` |\n| Cookies | `cookie()`, `cookies()`, `cook()` |\n| Spojenie | `timeout()`, `keepalive()`, `proxy()`, `cert()`, `insecure()`, `nodnscache()`, `redirect()`, `unixsocket()` |\n| Odpoveď | `strict()`, `noparse()`, `schema()`, `map()`, `convert()`, `cache()`, `progress()` |\n| Odoslanie | `callback()`, `exec()`, `promise()`, `stream()` |\n\nPredvolený časový limit je 10 sekúnd. Builder posiela `User-Agent: Total.js/v...` a akceptuje JSON, text a XML.\n\n### Nahrávanie súborov\n\n`file()` pridá súbor a prepne požiadavku na `multipart/form-data` (`GET` sa zmení na `POST`). Obsahom môže byť cesta, `Buffer` alebo URL, ktorú framework stiahne a prepošle. `set()` pridá obyčajné polia formulára.\n\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('file', 'report.pdf', PATH.databases('report.pdf'))\n\t.set('folder', 'reports')\n\t.callback(function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n```\n\n### Úprava odpovede\n\n- `schema(name)` zvaliduje odpoveď schémou a vráti model. Stavový kód `400` alebo vyšší je tu chybou.\n- `map('id:number,name:string')` ponechá len uvedené polia a prevedie ich; `id:number:itemid` navyše premenuje `id` na `itemid`.\n- `convert('price:number,date:date')` prevedie polia odpovede cez `CONVERT()`.\n- `cache('5 minutes')` uloží úspešnú (`200`) odpoveď do cache v `F.cache`.\n\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\t// users === [{ id: 1, name: 'Peter' }, ...]\n});\n```\n\n### Volanie API endpointov Total.js\n\n`RESTBuilder.API(url, operation, [data])` pošle `POST` s JSON `{ schema: operation, data: data }`, vo formáte API trás Total.js:\n\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_list', { search: 'Bike' }).callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### Globálne zmeny\n\n`RESTBuilder.upgrade(fn)` spustí `fn(builder)` pre každý builder pred odoslaním požiadavky, napríklad na pridanie hlavičky do všetkých požiadaviek. `RESTBuilder.addTransform(name, fn, [isDefault])` zaregistruje funkciu, ktorá mení každú sparsovanú odpoveď.\n\n## REQUEST()\n\n`REQUEST(options, [callback])` pošle jednu HTTP požiadavku. Telo, ktoré posielaš, musí byť reťazec alebo `Buffer`; telo odpovede je reťazec pre textové typy a typy `application/*`, inak `Buffer`. Bez callbacku vráti promise.\n\n```js\nREQUEST({ url: 'https://api.example.com/status/', method: 'GET', timeout: 5000 }, function(err, response) {\n\tif (err)\n\t\treturn;\n\tconsole.log(response.status, response.headers, response.body);\n});\n\nvar response = await REQUEST({ url: 'https://api.example.com/items/', method: 'POST', type: 'json', body: JSON.stringify({ name: 'Item' }) });\n```\n\nS `custom: true` dostaneš namiesto tela `response.stream` (prichádzajúcu správu). Framework nasleduje presmerovania `301` a `302` a ich cookies kopíruje do ďalšej požiadavky; `noredirect: true` to vypne.\n\n## DOWNLOAD()\n\n`DOWNLOAD(url, filename, [callback], [timeout])` zapíše odpoveď do súboru. Relatívna URL (`/sitemap.xml`) sa vyžiada z tvojej vlastnej bežiacej aplikácie.\n\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tconsole.log(err, response.status);\n});\n```\n\n## Proxy\n\n`CONF.default_proxy` posiela každú požiadavku cez proxy server, okrem požiadaviek na `localhost`, `127.0.0.1` a `0.0.0.0`. `proxy(url)` a voľba `proxy` nastavia proxy pre jednu požiadavku. Hodnota môže obsahovať prihlasovacie údaje: `http://user:password@proxy.example.com:8080`.\n\nKonfiguračný kľúč `default_restbuilder_timeout` (predvolene `10000`) je časový limit volaní `REQUEST()` bez vlastného `timeout`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Sending email","summary":"Send email from views, HTML or logs with the SMTP server of the configuration, and send messages to any server with the Mail module.","markdown":"---\ntitle: Sending email\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Sending email\n\n> Send email from views, HTML or logs with the SMTP server of the configuration, and send messages to any server with the Mail module.\n\nTotal.js sends email over SMTP with its own client, the `Mail` module. The global functions `MAIL()`, `HTMLMAIL()` and `LOGMAIL()` and the controller method `controller.mail()` create a message from the configuration, send it on the next tick and return it, so you can still add recipients or attachments. The full list of functions, options and message methods is in the reference of [Mail](../../reference/mail/).\n\n## Configuration\n\nPut the SMTP server and the sender in the `config` file:\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Key | What it does |\n| --- | --- |\n| `mail_smtp` | The host name of the SMTP server |\n| `mail_smtp_options` | The connection options, a JavaScript object written as text |\n| `mail_from` | The sender address; the sender name is the `name` key of the configuration |\n| `mail_reply` | A `Reply-To` address added to every message |\n| `mail_cc`, `mail_bcc` | A copy of every message for this address |\n| `mail_smtp_keepalive` | How long a connection stays open for the next messages (default `10 minutes`) |\n\nThe options of `mail_smtp_options`:\n\n| Option | Default | Description |\n| --- | --- | --- |\n| `port` | `25`, or `465` with `secure` | The port of the server |\n| `secure` | `false` | Connects with TLS from the start (SMTPS) |\n| `user`, `password` | `''` | The login; the client uses `AUTH LOGIN` or `AUTH PLAIN`, as the server offers |\n| `token` | `''` | An OAuth 2.0 access token, sent with `AUTH XOAUTH2` together with `user` |\n| `tls` | `null` | Options for the TLS connection; the client upgrades the connection with `STARTTLS` |\n| `timeout` | `10000` | The socket timeout in milliseconds |\n\nWhen the server announces ESMTP and you set `user` and `password`, the client upgrades a plain connection with `STARTTLS` before it signs in, so port `587` works without `secure`:\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nWithout `mail_smtp`, the framework uses `smtp.` plus the domain of the sender address. You can also check a server and save it at run time with `Mail.use()`:\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## A message from a view\n\n`MAIL(address, subject, view, [model], [language], [callback])` renders a view from `views/` without a layout and sends the result as HTML. The model is available as `model` in the view:\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nWith `language`, the subject and the `@(...)` texts of the view are translated to this language. A view name such as `=green/mails/welcome` takes the view from the theme `green`.\n\nInside an action, `this.mail()` does the same with the language of the request:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` can be one address or an array of addresses. Each address in the array becomes a `To` recipient.\n\n## Raw HTML and logs\n\n`HTMLMAIL()` sends HTML that you already have. When the body has no `<body>` element, it is wrapped in a full HTML document with the subject as the title:\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` is for notifications to yourself. An object is serialized as JSON, and the subject defaults to the name and the version of the application:\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Changing the message\n\nAll these functions return the message. It is sent on the next tick, so you can change it in the same call stack:\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nAn address can contain a name: `'Peter Sirka <peter@example.com>'`, or pass the name as the second argument of `to()` and `cc()`. The `clear` argument of `to()`, `cc()`, `bcc()` and `reply()` removes the addresses added before, for example the `mail_reply` address from the configuration.\n\n`attachment(filename, [name], [contentid])` adds a file from the disk; `attachmentfs(storage, id, [name], [contentid])` adds a file from a `FILESTORAGE()`. With `contentid`, the file is an inline attachment that the HTML refers to as `cid:`:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nTo prepare a message asynchronously, stop the automatic sending with `manually()` and call `send2()` when it is ready:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callbacks and errors\n\nThe callback of `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()` is the callback of the message: `function(err, message)`. When the SMTP server rejects the message, `err` is its reply line, for example `550 MAILBOX UNAVAILABLE`. Connection errors are logged with `F.error()` and emitted as the `error` event of `Mail`:\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nEvery message emits the global event `mail` before it is written to the server, which you can use to log or audit outgoing email:\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nTo debug the conversation with the server, set `Mail.debug = true`; every SMTP command and reply is printed to the console.\n\n## Sending without the configuration\n\nThe `Mail` module also sends messages to any server. `Mail.create()` creates an empty message, and `Mail.send()` sends one message or an array of messages over one connection:\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` does the same with `mail_smtp` and `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` only connects, signs in and quits, and returns a promise without a callback:\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Connections\n\nWhile the application runs a web server, messages sent with the configuration reuse one connection per SMTP host for `mail_smtp_keepalive`. Set `mail_smtp_keepalive : false` to open a new connection for every message. After you change `CONF.mail_smtp` or `CONF.mail_smtp_options` in code, run `CMD('clear_smtpcache')` so the next message reads them again; `Mail.use()` and `LOADCONFIG()` do it for you.\n\n## Message-ID\n\nEvery message has a `Message-ID` header generated by the framework. The identifier ends with the domain of the sender address, as mail servers expect, for example `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"E-Mails senden","summary":"Sende E-Mails aus Views, HTML oder Logs über den SMTP-Server der Konfiguration und sende Nachrichten mit dem Mail-Modul an einen beliebigen Server.","markdown":"---\ntitle: E-Mails senden\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# E-Mails senden\n\n> Sende E-Mails aus Views, HTML oder Logs über den SMTP-Server der Konfiguration und sende Nachrichten mit dem Mail-Modul an einen beliebigen Server.\n\nTotal.js sendet E-Mails über SMTP mit seinem eigenen Client, dem Modul `Mail`. Die globalen Funktionen `MAIL()`, `HTMLMAIL()` und `LOGMAIL()` und die Controller-Methode `controller.mail()` erstellen eine Nachricht aus der Konfiguration, senden sie im nächsten Tick und geben sie zurück, sodass du noch Empfänger oder Anhänge hinzufügen kannst. Die vollständige Liste der Funktionen, Optionen und Methoden der Nachricht steht in der Referenz zu [Mail](../../reference/mail/).\n\n## Konfiguration\n\nTrage den SMTP-Server und den Absender in die Datei `config` ein:\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Schlüssel | Was er tut |\n| --- | --- |\n| `mail_smtp` | Der Hostname des SMTP-Servers |\n| `mail_smtp_options` | Die Verbindungsoptionen, ein als Text geschriebenes JavaScript-Objekt |\n| `mail_from` | Die Absenderadresse; der Absendername ist der Schlüssel `name` der Konfiguration |\n| `mail_reply` | Eine `Reply-To`-Adresse, die zu jeder Nachricht hinzugefügt wird |\n| `mail_cc`, `mail_bcc` | Eine Kopie jeder Nachricht an diese Adresse |\n| `mail_smtp_keepalive` | Wie lange eine Verbindung für die nächsten Nachrichten offen bleibt (Standard `10 minutes`) |\n\nDie Optionen von `mail_smtp_options`:\n\n| Option | Standard | Beschreibung |\n| --- | --- | --- |\n| `port` | `25` oder `465` mit `secure` | Der Port des Servers |\n| `secure` | `false` | Verbindet sich von Anfang an mit TLS (SMTPS) |\n| `user`, `password` | `''` | Die Anmeldung; der Client verwendet `AUTH LOGIN` oder `AUTH PLAIN`, je nachdem, was der Server anbietet |\n| `token` | `''` | Ein OAuth-2.0-Access-Token, das mit `AUTH XOAUTH2` zusammen mit `user` gesendet wird |\n| `tls` | `null` | Optionen für die TLS-Verbindung; der Client stuft die Verbindung mit `STARTTLS` hoch |\n| `timeout` | `10000` | Der Socket-Timeout in Millisekunden |\n\nWenn der Server ESMTP ankündigt und du `user` und `password` setzt, stuft der Client eine unverschlüsselte Verbindung mit `STARTTLS` hoch, bevor er sich anmeldet, sodass Port `587` ohne `secure` funktioniert:\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nOhne `mail_smtp` verwendet das Framework `smtp.` plus die Domain der Absenderadresse. Du kannst einen Server auch zur Laufzeit mit `Mail.use()` prüfen und speichern:\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## Eine Nachricht aus einer View\n\n`MAIL(address, subject, view, [model], [language], [callback])` rendert eine View aus `views/` ohne Layout und sendet das Ergebnis als HTML. Das Modell ist in der View als `model` verfügbar:\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nMit `language` werden der Betreff und die `@(...)`-Texte der View in diese Sprache übersetzt. Ein View-Name wie `=green/mails/welcome` nimmt die View aus dem Theme `green`.\n\nInnerhalb einer Action tut `this.mail()` dasselbe mit der Sprache des Requests:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` kann eine Adresse oder ein Array von Adressen sein. Jede Adresse im Array wird zu einem `To`-Empfänger.\n\n## Rohes HTML und Logs\n\n`HTMLMAIL()` sendet HTML, das du bereits hast. Hat der Body kein `<body>`-Element, wird er in ein vollständiges HTML-Dokument mit dem Betreff als Titel eingeschlossen:\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` ist für Benachrichtigungen an dich selbst. Ein Objekt wird als JSON serialisiert, und der Betreff ist standardmäßig der Name und die Version der Anwendung:\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Die Nachricht ändern\n\nAlle diese Funktionen geben die Nachricht zurück. Sie wird im nächsten Tick gesendet, sodass du sie im selben Call-Stack ändern kannst:\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nEine Adresse kann einen Namen enthalten: `'Peter Sirka <peter@example.com>'`, oder übergib den Namen als zweites Argument von `to()` und `cc()`. Das Argument `clear` von `to()`, `cc()`, `bcc()` und `reply()` entfernt die zuvor hinzugefügten Adressen, zum Beispiel die Adresse `mail_reply` aus der Konfiguration.\n\n`attachment(filename, [name], [contentid])` fügt eine Datei von der Festplatte hinzu; `attachmentfs(storage, id, [name], [contentid])` fügt eine Datei aus einem `FILESTORAGE()` hinzu. Mit `contentid` ist die Datei ein Inline-Anhang, auf den das HTML als `cid:` verweist:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nUm eine Nachricht asynchron vorzubereiten, stoppe das automatische Senden mit `manually()` und rufe `send2()` auf, wenn sie bereit ist:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callbacks und Fehler\n\nDer Callback von `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `controller.mail()` ist der Callback der Nachricht: `function(err, message)`. Lehnt der SMTP-Server die Nachricht ab, ist `err` seine Antwortzeile, zum Beispiel `550 MAILBOX UNAVAILABLE`. Verbindungsfehler werden mit `F.error()` protokolliert und als Event `error` von `Mail` ausgegeben:\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nJede Nachricht gibt das globale Event `mail` aus, bevor sie an den Server geschrieben wird, was du nutzen kannst, um ausgehende E-Mails zu protokollieren oder zu prüfen:\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nUm die Kommunikation mit dem Server zu debuggen, setze `Mail.debug = true`; jeder SMTP-Befehl und jede Antwort wird in der Konsole ausgegeben.\n\n## Senden ohne die Konfiguration\n\nDas Modul `Mail` sendet Nachrichten auch an einen beliebigen Server. `Mail.create()` erstellt eine leere Nachricht, und `Mail.send()` sendet eine Nachricht oder ein Array von Nachrichten über eine Verbindung:\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` tut dasselbe mit `mail_smtp` und `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` verbindet sich nur, meldet sich an und beendet die Verbindung, und gibt ohne Callback eine Promise zurück:\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Verbindungen\n\nWährend die Anwendung einen Webserver betreibt, verwenden Nachrichten, die mit der Konfiguration gesendet werden, für `mail_smtp_keepalive` eine Verbindung pro SMTP-Host wieder. Setze `mail_smtp_keepalive : false`, um für jede Nachricht eine neue Verbindung zu öffnen. Nachdem du `CONF.mail_smtp` oder `CONF.mail_smtp_options` im Code geändert hast, führe `CMD('clear_smtpcache')` aus, damit die nächste Nachricht sie neu liest; `Mail.use()` und `LOADCONFIG()` erledigen das für dich.\n\n## Message-ID\n\nJede Nachricht hat einen `Message-ID`-Header, den das Framework erzeugt. Der Bezeichner endet mit der Domain der Absenderadresse, wie Mailserver es erwarten, zum Beispiel `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Enviar correo electrónico","summary":"Envía correo electrónico desde vistas, HTML o logs con el servidor SMTP de la configuración, y envía mensajes a cualquier servidor con el módulo Mail.","markdown":"---\ntitle: \"Enviar correo electrónico\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Enviar correo electrónico\n\n> Envía correo electrónico desde vistas, HTML o logs con el servidor SMTP de la configuración, y envía mensajes a cualquier servidor con el módulo Mail.\n\nTotal.js envía correo electrónico por SMTP con su propio cliente, el módulo `Mail`. Las funciones globales `MAIL()`, `HTMLMAIL()` y `LOGMAIL()` y el método de controlador `controller.mail()` crean un mensaje a partir de la configuración, lo envían en el siguiente tick y lo devuelven, así que todavía puedes añadir destinatarios o adjuntos. La lista completa de funciones, opciones y métodos del mensaje está en la referencia de [Mail](../../reference/mail/).\n\n## Configuración\n\nPon el servidor SMTP y el remitente en el archivo `config`:\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Clave | Qué hace |\n| --- | --- |\n| `mail_smtp` | El nombre de host del servidor SMTP |\n| `mail_smtp_options` | Las opciones de conexión, un objeto JavaScript escrito como texto |\n| `mail_from` | La dirección del remitente; el nombre del remitente es la clave `name` de la configuración |\n| `mail_reply` | Una dirección `Reply-To` que se añade a cada mensaje |\n| `mail_cc`, `mail_bcc` | Una copia de cada mensaje para esta dirección |\n| `mail_smtp_keepalive` | Cuánto tiempo permanece abierta una conexión para los siguientes mensajes (por defecto `10 minutes`) |\n\nLas opciones de `mail_smtp_options`:\n\n| Opción | Por defecto | Descripción |\n| --- | --- | --- |\n| `port` | `25`, o `465` con `secure` | El puerto del servidor |\n| `secure` | `false` | Se conecta con TLS desde el principio (SMTPS) |\n| `user`, `password` | `''` | El inicio de sesión; el cliente usa `AUTH LOGIN` o `AUTH PLAIN`, según lo que ofrezca el servidor |\n| `token` | `''` | Un token de acceso OAuth 2.0, enviado con `AUTH XOAUTH2` junto con `user` |\n| `tls` | `null` | Opciones para la conexión TLS; el cliente actualiza la conexión con `STARTTLS` |\n| `timeout` | `10000` | El tiempo límite del socket en milisegundos |\n\nCuando el servidor anuncia ESMTP y defines `user` y `password`, el cliente actualiza una conexión sin cifrar con `STARTTLS` antes de iniciar sesión, así que el puerto `587` funciona sin `secure`:\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nSin `mail_smtp`, el framework usa `smtp.` más el dominio de la dirección del remitente. También puedes comprobar un servidor y guardarlo en tiempo de ejecución con `Mail.use()`:\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## Un mensaje desde una vista\n\n`MAIL(address, subject, view, [model], [language], [callback])` renderiza una vista de `views/` sin plantilla (layout) y envía el resultado como HTML. El modelo está disponible como `model` en la vista:\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nCon `language`, el asunto y los textos `@(...)` de la vista se traducen a ese idioma. Un nombre de vista como `=green/mails/welcome` toma la vista del tema `green`.\n\nDentro de una acción, `this.mail()` hace lo mismo con el idioma de la petición:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` puede ser una dirección o un array de direcciones. Cada dirección del array se convierte en un destinatario `To`.\n\n## HTML sin procesar y logs\n\n`HTMLMAIL()` envía HTML que ya tienes. Cuando el cuerpo no tiene un elemento `<body>`, se envuelve en un documento HTML completo con el asunto como título:\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` es para notificaciones a ti mismo. Un objeto se serializa como JSON, y el asunto por defecto es el nombre y la versión de la aplicación:\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Modificar el mensaje\n\nTodas estas funciones devuelven el mensaje. Se envía en el siguiente tick, así que puedes modificarlo en la misma pila de llamadas:\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nUna dirección puede contener un nombre: `'Peter Sirka <peter@example.com>'`, o pasa el nombre como segundo argumento de `to()` y `cc()`. El argumento `clear` de `to()`, `cc()`, `bcc()` y `reply()` elimina las direcciones añadidas antes, por ejemplo la dirección `mail_reply` de la configuración.\n\n`attachment(filename, [name], [contentid])` añade un archivo del disco; `attachmentfs(storage, id, [name], [contentid])` añade un archivo de un `FILESTORAGE()`. Con `contentid`, el archivo es un adjunto en línea al que el HTML se refiere como `cid:`:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nPara preparar un mensaje de forma asíncrona, detén el envío automático con `manually()` y llama a `send2()` cuando esté listo:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callbacks y errores\n\nEl callback de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `controller.mail()` es el callback del mensaje: `function(err, message)`. Cuando el servidor SMTP rechaza el mensaje, `err` es su línea de respuesta, por ejemplo `550 MAILBOX UNAVAILABLE`. Los errores de conexión se registran con `F.error()` y se emiten como el evento `error` de `Mail`:\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nCada mensaje emite el evento global `mail` antes de escribirse en el servidor, que puedes usar para registrar o auditar el correo electrónico saliente:\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nPara depurar la conversación con el servidor, pon `Mail.debug = true`; cada comando y respuesta SMTP se imprime en la consola.\n\n## Enviar sin la configuración\n\nEl módulo `Mail` también envía mensajes a cualquier servidor. `Mail.create()` crea un mensaje vacío, y `Mail.send()` envía un mensaje o un array de mensajes por una sola conexión:\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` hace lo mismo con `mail_smtp` y `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` solo se conecta, inicia sesión y sale, y devuelve una promesa si no hay callback:\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Conexiones\n\nMientras la aplicación ejecuta un servidor web, los mensajes enviados con la configuración reutilizan una conexión por host SMTP durante `mail_smtp_keepalive`. Pon `mail_smtp_keepalive : false` para abrir una nueva conexión para cada mensaje. Después de cambiar `CONF.mail_smtp` o `CONF.mail_smtp_options` en el código, ejecuta `CMD('clear_smtpcache')` para que el siguiente mensaje los vuelva a leer; `Mail.use()` y `LOADCONFIG()` lo hacen por ti.\n\n## Message-ID\n\nCada mensaje tiene una cabecera `Message-ID` generada por el framework. El identificador termina con el dominio de la dirección del remitente, como esperan los servidores de correo, por ejemplo `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Envoyer des e-mails","summary":"Envoie des e-mails depuis des vues, du HTML ou des logs avec le serveur SMTP de la configuration, et envoie des messages vers n'importe quel serveur avec le module Mail.","markdown":"---\ntitle: Envoyer des e-mails\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Envoyer des e-mails\n\n> Envoie des e-mails depuis des vues, du HTML ou des logs avec le serveur SMTP de la configuration, et envoie des messages vers n'importe quel serveur avec le module Mail.\n\nTotal.js envoie les e-mails en SMTP avec son propre client, le module `Mail`. Les fonctions globales `MAIL()`, `HTMLMAIL()` et `LOGMAIL()` et la méthode de contrôleur `controller.mail()` créent un message à partir de la configuration, l'envoient au tick suivant et le renvoient ; tu peux donc encore ajouter des destinataires ou des pièces jointes. La liste complète des fonctions, des options et des méthodes des messages se trouve dans la référence de [Mail](../../reference/mail/).\n\n## Configuration\n\nPlace le serveur SMTP et l'expéditeur dans le fichier `config` :\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Clé | Ce qu'elle fait |\n| --- | --- |\n| `mail_smtp` | Le nom d'hôte du serveur SMTP |\n| `mail_smtp_options` | Les options de connexion, un objet JavaScript écrit sous forme de texte |\n| `mail_from` | L'adresse de l'expéditeur ; le nom de l'expéditeur est la clé `name` de la configuration |\n| `mail_reply` | Une adresse `Reply-To` ajoutée à chaque message |\n| `mail_cc`, `mail_bcc` | Une copie de chaque message pour cette adresse |\n| `mail_smtp_keepalive` | Durée pendant laquelle une connexion reste ouverte pour les messages suivants (par défaut `10 minutes`) |\n\nLes options de `mail_smtp_options` :\n\n| Option | Par défaut | Description |\n| --- | --- | --- |\n| `port` | `25`, ou `465` avec `secure` | Le port du serveur |\n| `secure` | `false` | Se connecte en TLS dès le départ (SMTPS) |\n| `user`, `password` | `''` | Les identifiants ; le client utilise `AUTH LOGIN` ou `AUTH PLAIN`, selon ce que propose le serveur |\n| `token` | `''` | Un jeton d'accès OAuth 2.0, envoyé avec `AUTH XOAUTH2` en même temps que `user` |\n| `tls` | `null` | Options de la connexion TLS ; le client met à niveau la connexion avec `STARTTLS` |\n| `timeout` | `10000` | Le délai d'expiration du socket en millisecondes |\n\nQuand le serveur annonce ESMTP et que tu définis `user` et `password`, le client met à niveau une connexion en clair avec `STARTTLS` avant de s'authentifier ; le port `587` fonctionne donc sans `secure` :\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nSans `mail_smtp`, le framework utilise `smtp.` suivi du domaine de l'adresse de l'expéditeur. Tu peux aussi vérifier un serveur et l'enregistrer à l'exécution avec `Mail.use()` :\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## Un message à partir d'une vue\n\n`MAIL(address, subject, view, [model], [language], [callback])` rend une vue de `views/` sans layout et envoie le résultat en HTML. Le modèle est disponible sous le nom `model` dans la vue :\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nAvec `language`, le sujet et les textes `@(...)` de la vue sont traduits dans cette langue. Un nom de vue comme `=green/mails/welcome` prend la vue du thème `green`.\n\nDans une action, `this.mail()` fait de même avec la langue de la requête :\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` peut être une adresse ou un tableau d'adresses. Chaque adresse du tableau devient un destinataire `To`.\n\n## HTML brut et logs\n\n`HTMLMAIL()` envoie du HTML que tu as déjà. Quand le corps n'a pas d'élément `<body>`, il est enveloppé dans un document HTML complet avec le sujet comme titre :\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` sert aux notifications que tu t'adresses. Un objet est sérialisé en JSON, et le sujet vaut par défaut le nom et la version de l'application :\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Modifier le message\n\nToutes ces fonctions renvoient le message. Il est envoyé au tick suivant ; tu peux donc le modifier dans la même pile d'appels :\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nUne adresse peut contenir un nom : `'Peter Sirka <peter@example.com>'`, ou passe le nom en deuxième argument de `to()` et `cc()`. L'argument `clear` de `to()`, `cc()`, `bcc()` et `reply()` supprime les adresses ajoutées auparavant, par exemple l'adresse `mail_reply` de la configuration.\n\n`attachment(filename, [name], [contentid])` ajoute un fichier du disque ; `attachmentfs(storage, id, [name], [contentid])` ajoute un fichier d'un `FILESTORAGE()`. Avec `contentid`, le fichier est une pièce jointe intégrée que le HTML référence par `cid:` :\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nPour préparer un message de manière asynchrone, arrête l'envoi automatique avec `manually()` et appelle `send2()` quand il est prêt :\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callbacks et erreurs\n\nLe callback de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `controller.mail()` est le callback du message : `function(err, message)`. Quand le serveur SMTP rejette le message, `err` est sa ligne de réponse, par exemple `550 MAILBOX UNAVAILABLE`. Les erreurs de connexion sont journalisées avec `F.error()` et émises comme événement `error` de `Mail` :\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nChaque message émet l'événement global `mail` avant d'être écrit vers le serveur, ce que tu peux utiliser pour journaliser ou auditer les e-mails sortants :\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nPour déboguer la conversation avec le serveur, définis `Mail.debug = true` ; chaque commande SMTP et chaque réponse sont affichées dans la console.\n\n## Envoyer sans la configuration\n\nLe module `Mail` envoie aussi des messages vers n'importe quel serveur. `Mail.create()` crée un message vide, et `Mail.send()` envoie un message ou un tableau de messages sur une seule connexion :\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` fait de même avec `mail_smtp` et `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` se contente de se connecter, de s'authentifier et de quitter, et renvoie une promesse sans callback :\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Connexions\n\nTant que l'application fait tourner un serveur web, les messages envoyés avec la configuration réutilisent une connexion par hôte SMTP pendant `mail_smtp_keepalive`. Définis `mail_smtp_keepalive : false` pour ouvrir une nouvelle connexion pour chaque message. Après avoir modifié `CONF.mail_smtp` ou `CONF.mail_smtp_options` dans le code, exécute `CMD('clear_smtpcache')` pour que le message suivant les relise ; `Mail.use()` et `LOADCONFIG()` le font pour toi.\n\n## Message-ID\n\nChaque message a un en-tête `Message-ID` généré par le framework. L'identifiant se termine par le domaine de l'adresse de l'expéditeur, comme l'attendent les serveurs de messagerie, par exemple `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Inviare e-mail","summary":"Invia e-mail da viste, HTML o log con il server SMTP della configurazione, e invia messaggi a qualsiasi server con il modulo Mail.","markdown":"---\ntitle: Inviare e-mail\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Inviare e-mail\n\n> Invia e-mail da viste, HTML o log con il server SMTP della configurazione, e invia messaggi a qualsiasi server con il modulo Mail.\n\nTotal.js invia e-mail via SMTP con un proprio client, il modulo `Mail`. Le funzioni globali `MAIL()`, `HTMLMAIL()` e `LOGMAIL()` e il metodo del controller `controller.mail()` creano un messaggio dalla configurazione, lo inviano al tick successivo e lo restituiscono, così puoi ancora aggiungere destinatari o allegati. L'elenco completo di funzioni, opzioni e metodi del messaggio è nel riferimento di [Mail](../../reference/mail/).\n\n## Configurazione\n\nMetti il server SMTP e il mittente nel file `config`:\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Chiave | Cosa fa |\n| --- | --- |\n| `mail_smtp` | Il nome host del server SMTP |\n| `mail_smtp_options` | Le opzioni di connessione, un oggetto JavaScript scritto come testo |\n| `mail_from` | L'indirizzo del mittente; il nome del mittente è la chiave `name` della configurazione |\n| `mail_reply` | Un indirizzo `Reply-To` aggiunto a ogni messaggio |\n| `mail_cc`, `mail_bcc` | Una copia di ogni messaggio per questo indirizzo |\n| `mail_smtp_keepalive` | Per quanto tempo una connessione resta aperta per i messaggi successivi (predefinito `10 minutes`) |\n\nLe opzioni di `mail_smtp_options`:\n\n| Opzione | Predefinito | Descrizione |\n| --- | --- | --- |\n| `port` | `25`, oppure `465` con `secure` | La porta del server |\n| `secure` | `false` | Si connette con TLS fin dall'inizio (SMTPS) |\n| `user`, `password` | `''` | Il login; il client usa `AUTH LOGIN` o `AUTH PLAIN`, in base a ciò che offre il server |\n| `token` | `''` | Un access token OAuth 2.0, inviato con `AUTH XOAUTH2` insieme a `user` |\n| `tls` | `null` | Opzioni per la connessione TLS; il client aggiorna la connessione con `STARTTLS` |\n| `timeout` | `10000` | Il timeout del socket in millisecondi |\n\nQuando il server annuncia ESMTP e imposti `user` e `password`, il client aggiorna una connessione in chiaro con `STARTTLS` prima di autenticarsi, quindi la porta `587` funziona senza `secure`:\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nSenza `mail_smtp`, il framework usa `smtp.` più il dominio dell'indirizzo del mittente. Puoi anche verificare un server e salvarlo a runtime con `Mail.use()`:\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## Un messaggio da una vista\n\n`MAIL(address, subject, view, [model], [language], [callback])` renderizza una vista da `views/` senza layout e invia il risultato come HTML. Il modello è disponibile come `model` nella vista:\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nCon `language`, l'oggetto e i testi `@(...)` della vista vengono tradotti in questa lingua. Un nome di vista come `=green/mails/welcome` prende la vista dal tema `green`.\n\nDentro un'azione, `this.mail()` fa lo stesso con la lingua della richiesta:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` può essere un indirizzo o un array di indirizzi. Ogni indirizzo nell'array diventa un destinatario `To`.\n\n## HTML grezzo e log\n\n`HTMLMAIL()` invia HTML che hai già. Quando il corpo non ha un elemento `<body>`, viene racchiuso in un documento HTML completo con l'oggetto come titolo:\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` serve per le notifiche a te stesso. Un oggetto viene serializzato come JSON, e l'oggetto predefinito è il nome e la versione dell'applicazione:\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Modificare il messaggio\n\nTutte queste funzioni restituiscono il messaggio. Viene inviato al tick successivo, così puoi modificarlo nello stesso call stack:\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nUn indirizzo può contenere un nome: `'Peter Sirka <peter@example.com>'`, oppure passa il nome come secondo argomento di `to()` e `cc()`. L'argomento `clear` di `to()`, `cc()`, `bcc()` e `reply()` rimuove gli indirizzi aggiunti prima, per esempio l'indirizzo `mail_reply` della configurazione.\n\n`attachment(filename, [name], [contentid])` aggiunge un file dal disco; `attachmentfs(storage, id, [name], [contentid])` aggiunge un file da un `FILESTORAGE()`. Con `contentid`, il file è un allegato inline a cui l'HTML fa riferimento come `cid:`:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nPer preparare un messaggio in modo asincrono, ferma l'invio automatico con `manually()` e chiama `send2()` quando è pronto:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callback ed errori\n\nLa callback di `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `controller.mail()` è la callback del messaggio: `function(err, message)`. Quando il server SMTP rifiuta il messaggio, `err` è la sua riga di risposta, per esempio `550 MAILBOX UNAVAILABLE`. Gli errori di connessione vengono registrati con `F.error()` ed emessi come evento `error` di `Mail`:\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nOgni messaggio emette l'evento globale `mail` prima di essere scritto sul server, che puoi usare per registrare o verificare le e-mail in uscita:\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nPer fare il debug della conversazione con il server, imposta `Mail.debug = true`; ogni comando e risposta SMTP viene stampato nella console.\n\n## Inviare senza la configurazione\n\nIl modulo `Mail` invia messaggi anche a qualsiasi server. `Mail.create()` crea un messaggio vuoto, e `Mail.send()` invia un messaggio o un array di messaggi su un'unica connessione:\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` fa lo stesso con `mail_smtp` e `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` si limita a connettersi, autenticarsi e chiudere, e senza callback restituisce una promise:\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Connessioni\n\nMentre l'applicazione esegue un server web, i messaggi inviati con la configurazione riutilizzano una connessione per host SMTP per la durata di `mail_smtp_keepalive`. Imposta `mail_smtp_keepalive : false` per aprire una nuova connessione per ogni messaggio. Dopo aver modificato `CONF.mail_smtp` o `CONF.mail_smtp_options` nel codice, esegui `CMD('clear_smtpcache')` così il messaggio successivo li rilegge; `Mail.use()` e `LOADCONFIG()` lo fanno al posto tuo.\n\n## Message-ID\n\nOgni messaggio ha un'intestazione `Message-ID` generata dal framework. L'identificatore termina con il dominio dell'indirizzo del mittente, come si aspettano i server di posta, per esempio `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmM83HV60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/mail/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Odosielanie e-mailov","summary":"Posielaj e-maily z pohľadov, HTML alebo logov cez SMTP server z konfigurácie a posielaj správy na akýkoľvek server cez modul Mail.","markdown":"---\ntitle: Odosielanie e-mailov\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/mail/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Odosielanie e-mailov\n\n> Posielaj e-maily z pohľadov, HTML alebo logov cez SMTP server z konfigurácie a posielaj správy na akýkoľvek server cez modul Mail.\n\nTotal.js posiela e-maily cez SMTP vlastným klientom, modulom `Mail`. Globálne funkcie `MAIL()`, `HTMLMAIL()` a `LOGMAIL()` a metóda kontroléra `controller.mail()` vytvoria správu z konfigurácie, pošlú ju v nasledujúcom tiku a vrátia ju, takže ešte môžeš pridať príjemcov alebo prílohy. Úplný zoznam funkcií, volieb a metód správy nájdeš v referencii [Mail](../../reference/mail/).\n\n## Konfigurácia\n\nSMTP server a odosielateľa daj do súboru `config`:\n\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n| Kľúč | Čo robí |\n| --- | --- |\n| `mail_smtp` | Názov hostiteľa SMTP servera |\n| `mail_smtp_options` | Voľby spojenia, JavaScript objekt zapísaný ako text |\n| `mail_from` | Adresa odosielateľa; meno odosielateľa je kľúč `name` v konfigurácii |\n| `mail_reply` | Adresa `Reply-To` pridaná ku každej správe |\n| `mail_cc`, `mail_bcc` | Kópia každej správy pre túto adresu |\n| `mail_smtp_keepalive` | Ako dlho zostane spojenie otvorené pre ďalšie správy (predvolene `10 minutes`) |\n\nVoľby `mail_smtp_options`:\n\n| Voľba | Predvolene | Popis |\n| --- | --- | --- |\n| `port` | `25`, alebo `465` so `secure` | Port servera |\n| `secure` | `false` | Pripojí sa cez TLS hneď od začiatku (SMTPS) |\n| `user`, `password` | `''` | Prihlasovacie údaje; klient použije `AUTH LOGIN` alebo `AUTH PLAIN` podľa toho, čo server ponúka |\n| `token` | `''` | Prístupový token OAuth 2.0, posielaný cez `AUTH XOAUTH2` spolu s `user` |\n| `tls` | `null` | Voľby pre TLS spojenie; klient spojenie povýši cez `STARTTLS` |\n| `timeout` | `10000` | Časový limit socketu v milisekundách |\n\nKeď server ohlási ESMTP a nastavíš `user` a `password`, klient pred prihlásením povýši nešifrované spojenie cez `STARTTLS`, takže port `587` funguje bez `secure`:\n\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nBez `mail_smtp` framework použije `smtp.` a doménu adresy odosielateľa. Server môžeš aj overiť a uložiť za behu cez `Mail.use()`:\n\n```js\nMail.use('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\t// On success, CONF.mail_smtp and CONF.mail_smtp_options are set\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n## Správa z pohľadu\n\n`MAIL(address, subject, view, [model], [language], [callback])` vyrenderuje pohľad z `views/` bez layoutu a výsledok pošle ako HTML. Model je v pohľade dostupný ako `model`:\n\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n```html\n<!-- views/mails/welcome.html -->\n<p>Hello @{model.name},</p>\n<p>@(your account is ready.)</p>\n```\n\nS `language` sa predmet a texty `@(...)` v pohľade preložia do tohto jazyka. Názov pohľadu ako `=green/mails/welcome` vezme pohľad z témy `green`.\n\nVnútri akcie robí `this.mail()` to isté s jazykom požiadavky:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n`address` môže byť jedna adresa alebo pole adries. Každá adresa v poli sa stane príjemcom `To`.\n\n## Surové HTML a logy\n\n`HTMLMAIL()` pošle HTML, ktoré už máš. Keď telo nemá element `<body>`, zabalí sa do úplného HTML dokumentu s predmetom ako titulkom:\n\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n`LOGMAIL()` je pre notifikácie tebe samému. Objekt sa serializuje ako JSON a predmet je predvolene názov a verzia aplikácie:\n\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\n## Zmena správy\n\nVšetky tieto funkcie vracajú správu. Pošle sa v nasledujúcom tiku, takže ju môžeš zmeniť v tom istom zásobníku volaní:\n\n```js\nMAIL('peter@example.com', 'Invoice', 'mails/invoice', invoice)\n\t.cc('accounting@example.com')\n\t.bcc('archive@example.com')\n\t.reply('billing@example.com', true)\n\t.attachment(PATH.root('invoices/' + invoice.id + '.pdf'), 'invoice.pdf');\n```\n\nAdresa môže obsahovať meno: `'Peter Sirka <peter@example.com>'`, alebo odovzdaj meno ako druhý argument `to()` a `cc()`. Argument `clear` v `to()`, `cc()`, `bcc()` a `reply()` odstráni predtým pridané adresy, napríklad adresu `mail_reply` z konfigurácie.\n\n`attachment(filename, [name], [contentid])` pridá súbor z disku; `attachmentfs(storage, id, [name], [contentid])` pridá súbor z `FILESTORAGE()`. S `contentid` je súbor inline prílohou, na ktorú sa HTML odkazuje ako `cid:`:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\nAk chceš správu pripraviť asynchrónne, zastav automatické odoslanie cez `manually()` a zavolaj `send2()`, keď je pripravená:\n\n```js\nvar message = HTMLMAIL('peter@example.com', 'Your export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n## Callbacky a chyby\n\nCallback `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `controller.mail()` je callback správy: `function(err, message)`. Keď SMTP server správu odmietne, `err` je jeho riadok odpovede, napríklad `550 MAILBOX UNAVAILABLE`. Chyby spojenia sa logujú cez `F.error()` a vysielajú ako udalosť `error` modulu `Mail`:\n\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\nKaždá správa vyšle globálnu udalosť `mail` predtým, ako sa zapíše na server, čo môžeš využiť na logovanie alebo audit odchádzajúcich e-mailov:\n\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\nAk chceš ladiť komunikáciu so serverom, nastav `Mail.debug = true`; každý SMTP príkaz a odpoveď sa vypíše do konzoly.\n\n## Odosielanie bez konfigurácie\n\nModul `Mail` posiela správy aj na akýkoľvek server. `Mail.create()` vytvorí prázdnu správu a `Mail.send()` pošle jednu správu alebo pole správ cez jedno spojenie:\n\n```js\nvar message = Mail.create('Hello', '<p>Hello from the server.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\n\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\n`Mail.send2(messages, callback)` robí to isté s `mail_smtp` a `mail_smtp_options`. `Mail.try(smtp, [options], [callback])` sa len pripojí, prihlási a odpojí a bez callbacku vráti promise:\n\n```js\nMail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' }).then(function() {\n\tconsole.log('SMTP works');\n}).catch(function(err) {\n\tconsole.log('SMTP failed', err);\n});\n```\n\n## Spojenia\n\nKým aplikácia beží s webovým serverom, správy odoslané s konfiguráciou opakovane používajú jedno spojenie na SMTP hostiteľa počas `mail_smtp_keepalive`. Nastav `mail_smtp_keepalive : false`, ak chceš pre každú správu otvoriť nové spojenie. Keď v kóde zmeníš `CONF.mail_smtp` alebo `CONF.mail_smtp_options`, spusti `CMD('clear_smtpcache')`, aby ich ďalšia správa prečítala znova; `Mail.use()` a `LOADCONFIG()` to urobia za teba.\n\n## Message-ID\n\nKaždá správa má hlavičku `Message-ID` generovanú frameworkom. Identifikátor končí doménou adresy odosielateľa, ako mailové servery očakávajú, napríklad `<total4X...@example.com>`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnPI1fl60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Scheduling and events","summary":"Run jobs at a time, by cron or every few minutes, and react to framework events with ON() and EMIT().","markdown":"---\ntitle: Scheduling and events\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Scheduling and events\n\n> Run jobs at a time, by cron or every few minutes, and react to framework events with ON() and EMIT().\n\nTotal.js 4 runs a **service** once a minute. It clears caches, fires the `service` event and starts the jobs you registered with `SCHEDULE()`. Framework events let your code react to the life of the application: start, requests, errors, exit. This guide shows both. The exact signatures are in the reference [Scheduling and events](../../reference/scheduling-and-events/).\n\n## Run code at a set time\n\n`SCHEDULE(date, [repeat], fn)` registers a job. The `date` can be a time, a `Date`, a timestamp in milliseconds or a cron expression.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- A time such as `'03:00'` is today at that time. If that time has already passed and you set `repeat`, the first run moves forward by one `repeat` (here to tomorrow).\n- `repeat` is a period that `Date.add()` understands: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. You can write `'each'` for one: `'each day'` is the same as `'1 day'`.\n- Without `repeat` the job runs once and then removes itself.\n- Times are read in the time zone of the application, which is the `default_timezone` setting (`utc` by default).\n\nThe service checks the jobs once a minute, so a job runs on the first check at or after its time. Do not expect precision below one minute.\n\nA string that contains a space is always read as a cron expression. To run a job once at a specific date, pass a `Date` object or a timestamp:\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Cron expressions\n\nA cron expression has five fields separated by spaces: **minute**, **hour**, **day of month**, **month** (1-12) and **day of week**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Field value | Meaning |\n| --- | --- |\n| `*` | any value |\n| `5` | exactly 5 |\n| `1,15,30` | one of the listed values |\n| `9-17` | any value between 9 and 17, both included |\n\nDays of the week are numbers from `0` (Sunday) to `6` (Saturday), or names. Only the first two letters of a name count: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (so `monday` also works).\n\nA cron job has no `repeat` argument. It runs at every minute that matches the expression, until you remove it. To run a job every few minutes, list the minutes (`'0,15,30,45 * * * *'`) or use a time with `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Stop or trigger a job\n\n`SCHEDULE()` returns the job. Keep it to stop the job later or to run it at once:\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## The service event\n\nIf you need something every minute, listen to `service`. The argument is the number of runs since the application started, so you can derive longer periods:\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nThe same tick clears the internal caches. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) and `default_interval_clear_dnscache` (30) set how many minutes pass between those clean-ups, and each one emits the `clear` event.\n\n## Listen to events\n\n`ON(name, fn)` adds a listener. `ONCE(name, fn)` adds one that is removed after its first call. `OFF(name, [fn])` removes listeners. `this` inside a listener is the framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` and `ready` are special: if the application has already loaded when you call `ON()`, the function runs immediately. So a plugin or a module that is installed late still gets its `ready` call.\n\nTo remove one listener, pass the same function you added:\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` without a function removes every listener of that event, including the framework's own. Call `OFF()` with no arguments only if you really mean to remove all listeners of all events.\n\n## Your own events\n\nAny name works with `EMIT()`. Use events to let parts of the app talk without requiring each other:\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` passes up to seven arguments and calls the listeners synchronously, in the order they were added.\n\n`EMIT2(name, [a], ...)` sends the event to the **other** processes of the application: the threads, the cluster, or the parent process of a worker. It passes up to five arguments, so they must be serialisable values. In a single process without threads or a cluster it does nothing; use `EMIT()` there.\n\n## Built-in events\n\n| Event | Arguments | When |\n| --- | --- | --- |\n| `init` | | Configuration is loaded, before the app files load |\n| `load`, `ready` | | All files are loaded; `ready` comes right after `load` |\n| `service` | `counter` | Every minute |\n| `request` | `req, res` | A request arrives, before routing |\n| `request_begin` | `req, res` | The request is prepared for routing |\n| `request_end` | `req, res` | The response has finished |\n| `controller` | `controller, name, options` | Before a route action runs |\n| `errorNNN` | `req, res, exception` | An error page is sent, for example `error404` |\n| `error` | `obj` | The framework logs an error |\n| `route` | `type, route` | A route is registered |\n| `install` | `type, name, module` | A file (controller, model, plugin...) is installed |\n| `configure` | `CONF` | Configuration has been (re)loaded |\n| `websocket` | `req, socket, head` | A WebSocket upgrade request arrives |\n| `websocket_begin`, `websocket_end` | `controller, client` | A WebSocket client connects or disconnects |\n| `clear` | `type, [value]` | An internal cache is cleared |\n| `cache_set`, `cache_expired` | `key, value, ...` | A `CACHE` value is set or expires |\n| `mail` | `message` | An email is being sent |\n| `message` | `msg, handle` | The process receives an IPC message |\n| `exit` | `signal` | The application stops |\n\nEach event has its own entry in the reference with the exact arguments.\n\n## Clean up streams\n\n`CLEANUP(stream, [callback])` waits until a stream has finished, destroys it and then calls the callback. Without a callback it returns a Promise. Use it to release file handles after you pipe a stream:\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Wait and delay\n\n`WAIT(validator, callback, [timeout], [interval])` checks `validator()` every `interval` ms (500) until it returns `true`, or fails after `timeout` ms (5000):\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` is a named timeout. Calling it again with the same name cancels the previous timer, so the function runs once after the last call (a debounce). With `limit`, after that many postponements the function runs at once. `clearTimeout2(name)` cancels it.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` makes the server answer every request with `503` while at least one name is paused, for example during a migration.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPI1fl60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Zeitplanung und Events","summary":"Führe Jobs zu einer Uhrzeit, per Cron oder alle paar Minuten aus und reagiere mit ON() und EMIT() auf Events des Frameworks.","markdown":"---\ntitle: Zeitplanung und Events\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Zeitplanung und Events\n\n> Führe Jobs zu einer Uhrzeit, per Cron oder alle paar Minuten aus und reagiere mit ON() und EMIT() auf Events des Frameworks.\n\nTotal.js 4 führt einmal pro Minute einen **Service** aus. Er leert Caches, löst das Event `service` aus und startet die Jobs, die du mit `SCHEDULE()` registriert hast. Mit Events des Frameworks reagiert dein Code auf den Lebenszyklus der Anwendung: Start, Requests, Fehler, Beenden. Dieser Leitfaden zeigt beides. Die genauen Signaturen stehen in der Referenz [Zeitplanung und Events](../../reference/scheduling-and-events/).\n\n## Code zu einer festen Zeit ausführen\n\n`SCHEDULE(date, [repeat], fn)` registriert einen Job. `date` kann eine Uhrzeit, ein `Date`, ein Zeitstempel in Millisekunden oder ein Cron-Ausdruck sein.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- Eine Uhrzeit wie `'03:00'` bedeutet heute zu dieser Uhrzeit. Ist diese Uhrzeit schon vorbei und du hast `repeat` gesetzt, verschiebt sich der erste Lauf um ein `repeat` nach vorne (hier auf morgen).\n- `repeat` ist ein Zeitraum, den `Date.add()` versteht: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. Für eins kannst du `'each'` schreiben: `'each day'` ist dasselbe wie `'1 day'`.\n- Ohne `repeat` läuft der Job einmal und entfernt sich dann selbst.\n- Uhrzeiten werden in der Zeitzone der Anwendung gelesen, also der Einstellung `default_timezone` (standardmäßig `utc`).\n\nDer Service prüft die Jobs einmal pro Minute, daher läuft ein Job bei der ersten Prüfung zu oder nach seiner Uhrzeit. Erwarte keine Genauigkeit unter einer Minute.\n\nEin String, der ein Leerzeichen enthält, wird immer als Cron-Ausdruck gelesen. Um einen Job einmal zu einem bestimmten Datum auszuführen, übergib ein `Date`-Objekt oder einen Zeitstempel:\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Cron-Ausdrücke\n\nEin Cron-Ausdruck hat fünf durch Leerzeichen getrennte Felder: **Minute**, **Stunde**, **Tag des Monats**, **Monat** (1-12) und **Wochentag**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Feldwert | Bedeutung |\n| --- | --- |\n| `*` | beliebiger Wert |\n| `5` | genau 5 |\n| `1,15,30` | einer der aufgeführten Werte |\n| `9-17` | jeder Wert zwischen 9 und 17, beide eingeschlossen |\n\nWochentage sind Zahlen von `0` (Sonntag) bis `6` (Samstag) oder Namen. Nur die ersten zwei Buchstaben eines Namens zählen: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (also funktioniert auch `monday`).\n\nEin Cron-Job hat kein Argument `repeat`. Er läuft in jeder Minute, die zum Ausdruck passt, bis du ihn entfernst. Um einen Job alle paar Minuten auszuführen, liste die Minuten auf (`'0,15,30,45 * * * *'`) oder verwende eine Uhrzeit mit `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Einen Job stoppen oder auslösen\n\n`SCHEDULE()` gibt den Job zurück. Bewahre ihn auf, um den Job später zu stoppen oder ihn sofort auszuführen:\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## Das Event service\n\nWenn du etwas jede Minute brauchst, höre auf `service`. Das Argument ist die Anzahl der Läufe seit dem Start der Anwendung, sodass du längere Zeiträume ableiten kannst:\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nDerselbe Takt leert die internen Caches. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) und `default_interval_clear_dnscache` (30) legen fest, wie viele Minuten zwischen diesen Bereinigungen vergehen, und jede gibt das Event `clear` aus.\n\n## Auf Events hören\n\n`ON(name, fn)` fügt einen Listener hinzu. `ONCE(name, fn)` fügt einen hinzu, der nach seinem ersten Aufruf entfernt wird. `OFF(name, [fn])` entfernt Listener. `this` ist in einem Listener das Framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` und `ready` sind besonders: Ist die Anwendung beim Aufruf von `ON()` bereits geladen, läuft die Funktion sofort. So bekommt auch ein spät installiertes Plugin oder Modul noch seinen `ready`-Aufruf.\n\nUm einen Listener zu entfernen, übergib dieselbe Funktion, die du hinzugefügt hast:\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` ohne Funktion entfernt jeden Listener dieses Events, auch die des Frameworks selbst. Rufe `OFF()` ohne Argumente nur auf, wenn du wirklich alle Listener aller Events entfernen willst.\n\n## Eigene Events\n\nMit `EMIT()` funktioniert jeder Name. Verwende Events, damit Teile der App miteinander sprechen, ohne sich gegenseitig zu laden:\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` übergibt bis zu sieben Argumente und ruft die Listener synchron auf, in der Reihenfolge, in der sie hinzugefügt wurden.\n\n`EMIT2(name, [a], ...)` sendet das Event an die **anderen** Prozesse der Anwendung: die Threads, den Cluster oder den Elternprozess eines Workers. Es übergibt bis zu fünf Argumente, die daher serialisierbare Werte sein müssen. In einem einzelnen Prozess ohne Threads oder Cluster tut es nichts; verwende dort `EMIT()`.\n\n## Eingebaute Events\n\n| Event | Argumente | Wann |\n| --- | --- | --- |\n| `init` | | Die Konfiguration ist geladen, bevor die App-Dateien geladen werden |\n| `load`, `ready` | | Alle Dateien sind geladen; `ready` kommt direkt nach `load` |\n| `service` | `counter` | Jede Minute |\n| `request` | `req, res` | Ein Request kommt an, vor dem Routing |\n| `request_begin` | `req, res` | Der Request wird für das Routing vorbereitet |\n| `request_end` | `req, res` | Die Response ist fertig |\n| `controller` | `controller, name, options` | Bevor eine Route-Action läuft |\n| `errorNNN` | `req, res, exception` | Eine Fehlerseite wird gesendet, zum Beispiel `error404` |\n| `error` | `obj` | Das Framework protokolliert einen Fehler |\n| `route` | `type, route` | Eine Route wird registriert |\n| `install` | `type, name, module` | Eine Datei (Controller, Modell, Plugin...) wird installiert |\n| `configure` | `CONF` | Die Konfiguration wurde (neu) geladen |\n| `websocket` | `req, socket, head` | Ein WebSocket-Upgrade-Request kommt an |\n| `websocket_begin`, `websocket_end` | `controller, client` | Ein WebSocket-Client verbindet sich oder trennt die Verbindung |\n| `clear` | `type, [value]` | Ein interner Cache wird geleert |\n| `cache_set`, `cache_expired` | `key, value, ...` | Ein `CACHE`-Wert wird gesetzt oder läuft ab |\n| `mail` | `message` | Eine E-Mail wird gesendet |\n| `message` | `msg, handle` | Der Prozess empfängt eine IPC-Nachricht |\n| `exit` | `signal` | Die Anwendung stoppt |\n\nJedes Event hat einen eigenen Eintrag in der Referenz mit den genauen Argumenten.\n\n## Streams aufräumen\n\n`CLEANUP(stream, [callback])` wartet, bis ein Stream fertig ist, zerstört ihn und ruft dann den Callback auf. Ohne Callback gibt es eine Promise zurück. Verwende es, um Datei-Handles freizugeben, nachdem du einen Stream per Pipe weitergeleitet hast:\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Warten und verzögern\n\n`WAIT(validator, callback, [timeout], [interval])` prüft `validator()` alle `interval` ms (500), bis es `true` zurückgibt, oder schlägt nach `timeout` ms (5000) fehl:\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` ist ein benannter Timeout. Ein erneuter Aufruf mit demselben Namen bricht den vorherigen Timer ab, sodass die Funktion einmal nach dem letzten Aufruf läuft (ein Debounce). Mit `limit` läuft die Funktion nach so vielen Verschiebungen sofort. `clearTimeout2(name)` bricht ihn ab.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` lässt den Server jeden Request mit `503` beantworten, solange mindestens ein Name pausiert ist, zum Beispiel während einer Migration.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPI1fl60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Programación y eventos","summary":"Ejecuta trabajos a una hora, por cron o cada pocos minutos, y reacciona a los eventos del framework con ON() y EMIT().","markdown":"---\ntitle: \"Programación y eventos\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Programación y eventos\n\n> Ejecuta trabajos a una hora, por cron o cada pocos minutos, y reacciona a los eventos del framework con ON() y EMIT().\n\nTotal.js 4 ejecuta un **servicio** una vez por minuto. Limpia las cachés, dispara el evento `service` e inicia los trabajos que registraste con `SCHEDULE()`. Los eventos del framework permiten que tu código reaccione a la vida de la aplicación: arranque, peticiones, errores, salida. Esta guía muestra ambos. Las firmas exactas están en la referencia [Programación y eventos](../../reference/scheduling-and-events/).\n\n## Ejecutar código a una hora fija\n\n`SCHEDULE(date, [repeat], fn)` registra un trabajo. `date` puede ser una hora, un `Date`, un timestamp en milisegundos o una expresión cron.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- Una hora como `'03:00'` es hoy a esa hora. Si esa hora ya pasó y defines `repeat`, la primera ejecución avanza un `repeat` (aquí, a mañana).\n- `repeat` es un periodo que entiende `Date.add()`: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. Puedes escribir `'each'` en lugar de uno: `'each day'` es lo mismo que `'1 day'`.\n- Sin `repeat` el trabajo se ejecuta una vez y luego se elimina.\n- Las horas se leen en la zona horaria de la aplicación, que es el ajuste `default_timezone` (`utc` por defecto).\n\nEl servicio revisa los trabajos una vez por minuto, así que un trabajo se ejecuta en la primera revisión en su hora o después. No esperes una precisión inferior a un minuto.\n\nUn string que contiene un espacio siempre se lee como una expresión cron. Para ejecutar un trabajo una sola vez en una fecha concreta, pasa un objeto `Date` o un timestamp:\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Expresiones cron\n\nUna expresión cron tiene cinco campos separados por espacios: **minuto**, **hora**, **día del mes**, **mes** (1-12) y **día de la semana**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Valor del campo | Significado |\n| --- | --- |\n| `*` | cualquier valor |\n| `5` | exactamente 5 |\n| `1,15,30` | uno de los valores listados |\n| `9-17` | cualquier valor entre 9 y 17, ambos incluidos |\n\nLos días de la semana son números de `0` (domingo) a `6` (sábado), o nombres. Solo cuentan las dos primeras letras de un nombre: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (así que `monday` también funciona).\n\nUn trabajo cron no tiene argumento `repeat`. Se ejecuta en cada minuto que coincide con la expresión, hasta que lo eliminas. Para ejecutar un trabajo cada pocos minutos, enumera los minutos (`'0,15,30,45 * * * *'`) o usa una hora con `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Detener o disparar un trabajo\n\n`SCHEDULE()` devuelve el trabajo. Guárdalo para detenerlo más tarde o para ejecutarlo de inmediato:\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## El evento service\n\nSi necesitas algo cada minuto, escucha `service`. El argumento es el número de ejecuciones desde que arrancó la aplicación, así que puedes derivar periodos más largos:\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nEl mismo tick limpia las cachés internas. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) y `default_interval_clear_dnscache` (30) definen cuántos minutos pasan entre esas limpiezas, y cada una emite el evento `clear`.\n\n## Escuchar eventos\n\n`ON(name, fn)` añade un listener. `ONCE(name, fn)` añade uno que se elimina tras su primera llamada. `OFF(name, [fn])` elimina listeners. `this` dentro de un listener es el framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` y `ready` son especiales: si la aplicación ya se cargó cuando llamas a `ON()`, la función se ejecuta inmediatamente. Así, un plugin o un módulo que se instala tarde sigue recibiendo su llamada `ready`.\n\nPara eliminar un listener, pasa la misma función que añadiste:\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` sin función elimina todos los listeners de ese evento, incluidos los del propio framework. Llama a `OFF()` sin argumentos solo si de verdad quieres eliminar todos los listeners de todos los eventos.\n\n## Tus propios eventos\n\nCualquier nombre funciona con `EMIT()`. Usa eventos para que las partes de la aplicación se comuniquen sin requerirse entre sí:\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` pasa hasta siete argumentos y llama a los listeners de forma síncrona, en el orden en que se añadieron.\n\n`EMIT2(name, [a], ...)` envía el evento a los **otros** procesos de la aplicación: los hilos, el clúster o el proceso padre de un worker. Pasa hasta cinco argumentos, así que deben ser valores serializables. En un único proceso sin hilos ni clúster no hace nada; usa `EMIT()` en ese caso.\n\n## Eventos integrados\n\n| Evento | Argumentos | Cuándo |\n| --- | --- | --- |\n| `init` | | La configuración está cargada, antes de que se carguen los archivos de la aplicación |\n| `load`, `ready` | | Todos los archivos están cargados; `ready` llega justo después de `load` |\n| `service` | `counter` | Cada minuto |\n| `request` | `req, res` | Llega una petición, antes del enrutamiento |\n| `request_begin` | `req, res` | La petición se prepara para el enrutamiento |\n| `request_end` | `req, res` | La respuesta ha terminado |\n| `controller` | `controller, name, options` | Antes de que se ejecute la acción de una ruta |\n| `errorNNN` | `req, res, exception` | Se envía una página de error, por ejemplo `error404` |\n| `error` | `obj` | El framework registra un error |\n| `route` | `type, route` | Se registra una ruta |\n| `install` | `type, name, module` | Se instala un archivo (controlador, modelo, plugin...) |\n| `configure` | `CONF` | La configuración se ha (re)cargado |\n| `websocket` | `req, socket, head` | Llega una petición de upgrade a WebSocket |\n| `websocket_begin`, `websocket_end` | `controller, client` | Un cliente WebSocket se conecta o se desconecta |\n| `clear` | `type, [value]` | Se limpia una caché interna |\n| `cache_set`, `cache_expired` | `key, value, ...` | Se define un valor de `CACHE` o expira |\n| `mail` | `message` | Se está enviando un email |\n| `message` | `msg, handle` | El proceso recibe un mensaje IPC |\n| `exit` | `signal` | La aplicación se detiene |\n\nCada evento tiene su propia entrada en la referencia con los argumentos exactos.\n\n## Limpiar streams\n\n`CLEANUP(stream, [callback])` espera a que un stream termine, lo destruye y luego llama al callback. Sin callback devuelve una Promise. Úsalo para liberar los descriptores de archivo después de hacer pipe de un stream:\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Esperar y retrasar\n\n`WAIT(validator, callback, [timeout], [interval])` comprueba `validator()` cada `interval` ms (500) hasta que devuelve `true`, o falla tras `timeout` ms (5000):\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` es un timeout con nombre. Llamarlo de nuevo con el mismo nombre cancela el temporizador anterior, así que la función se ejecuta una vez tras la última llamada (un debounce). Con `limit`, tras ese número de aplazamientos la función se ejecuta de inmediato. `clearTimeout2(name)` lo cancela.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` hace que el servidor responda a cada petición con `503` mientras haya al menos un nombre en pausa, por ejemplo durante una migración.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPI1fl60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Planification et événements","summary":"Exécute des tâches à une heure donnée, par cron ou toutes les quelques minutes, et réagis aux événements du framework avec ON() et EMIT().","markdown":"---\ntitle: \"Planification et événements\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Planification et événements\n\n> Exécute des tâches à une heure donnée, par cron ou toutes les quelques minutes, et réagis aux événements du framework avec ON() et EMIT().\n\nTotal.js 4 exécute un **service** une fois par minute. Il vide les caches, déclenche l'événement `service` et lance les jobs que tu as enregistrés avec `SCHEDULE()`. Les événements du framework permettent à ton code de réagir à la vie de l'application : démarrage, requêtes, erreurs, arrêt. Ce guide présente les deux. Les signatures exactes se trouvent dans la référence [Planification et événements](../../reference/scheduling-and-events/).\n\n## Exécuter du code à une heure fixe\n\n`SCHEDULE(date, [repeat], fn)` enregistre un job. La `date` peut être une heure, une `Date`, un timestamp en millisecondes ou une expression cron.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- Une heure comme `'03:00'` correspond à aujourd'hui à cette heure. Si cette heure est déjà passée et que tu définis `repeat`, la première exécution est décalée d'une période `repeat` (ici à demain).\n- `repeat` est une période que `Date.add()` comprend : `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. Tu peux écrire `'each'` à la place de un : `'each day'` équivaut à `'1 day'`.\n- Sans `repeat`, le job s'exécute une seule fois puis se supprime.\n- Les heures sont lues dans le fuseau horaire de l'application, défini par le paramètre `default_timezone` (`utc` par défaut).\n\nLe service vérifie les jobs une fois par minute ; un job s'exécute donc lors de la première vérification à son heure ou après. N'attends pas une précision inférieure à la minute.\n\nUne chaîne qui contient un espace est toujours lue comme une expression cron. Pour exécuter un job une seule fois à une date précise, passe un objet `Date` ou un timestamp :\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Expressions cron\n\nUne expression cron comporte cinq champs séparés par des espaces : **minute**, **heure**, **jour du mois**, **mois** (1-12) et **jour de la semaine**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Valeur du champ | Signification |\n| --- | --- |\n| `*` | n'importe quelle valeur |\n| `5` | exactement 5 |\n| `1,15,30` | l'une des valeurs listées |\n| `9-17` | n'importe quelle valeur entre 9 et 17, bornes incluses |\n\nLes jours de la semaine sont des nombres de `0` (dimanche) à `6` (samedi), ou des noms. Seules les deux premières lettres d'un nom comptent : `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (donc `monday` fonctionne aussi).\n\nUn job cron n'a pas d'argument `repeat`. Il s'exécute à chaque minute qui correspond à l'expression, jusqu'à ce que tu le supprimes. Pour exécuter un job toutes les quelques minutes, liste les minutes (`'0,15,30,45 * * * *'`) ou utilise une heure avec `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Arrêter ou déclencher un job\n\n`SCHEDULE()` renvoie le job. Conserve-le pour arrêter le job plus tard ou pour l'exécuter immédiatement :\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## L'événement service\n\nSi tu as besoin de faire quelque chose chaque minute, écoute `service`. L'argument est le nombre d'exécutions depuis le démarrage de l'application ; tu peux donc en déduire des périodes plus longues :\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nLe même tick vide les caches internes. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) et `default_interval_clear_dnscache` (30) définissent le nombre de minutes entre ces nettoyages, et chacun émet l'événement `clear`.\n\n## Écouter des événements\n\n`ON(name, fn)` ajoute un listener. `ONCE(name, fn)` en ajoute un qui est supprimé après son premier appel. `OFF(name, [fn])` supprime des listeners. Dans un listener, `this` est le framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` et `ready` sont particuliers : si l'application est déjà chargée quand tu appelles `ON()`, la fonction s'exécute immédiatement. Ainsi, un plugin ou un module installé tardivement reçoit tout de même son appel `ready`.\n\nPour supprimer un listener, passe la même fonction que celle que tu as ajoutée :\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` sans fonction supprime tous les listeners de cet événement, y compris ceux du framework lui-même. N'appelle `OFF()` sans arguments que si tu veux vraiment supprimer tous les listeners de tous les événements.\n\n## Tes propres événements\n\nN'importe quel nom fonctionne avec `EMIT()`. Utilise les événements pour faire communiquer des parties de l'application sans qu'elles se requièrent mutuellement :\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` passe jusqu'à sept arguments et appelle les listeners de manière synchrone, dans l'ordre où ils ont été ajoutés.\n\n`EMIT2(name, [a], ...)` envoie l'événement aux **autres** processus de l'application : les threads, le cluster ou le processus parent d'un worker. Il passe jusqu'à cinq arguments, qui doivent donc être des valeurs sérialisables. Dans un processus unique sans threads ni cluster, il ne fait rien ; utilise `EMIT()` dans ce cas.\n\n## Événements intégrés\n\n| Événement | Arguments | Quand |\n| --- | --- | --- |\n| `init` | | La configuration est chargée, avant le chargement des fichiers de l'application |\n| `load`, `ready` | | Tous les fichiers sont chargés ; `ready` arrive juste après `load` |\n| `service` | `counter` | Chaque minute |\n| `request` | `req, res` | Une requête arrive, avant le routage |\n| `request_begin` | `req, res` | La requête est préparée pour le routage |\n| `request_end` | `req, res` | La réponse est terminée |\n| `controller` | `controller, name, options` | Avant l'exécution de l'action d'une route |\n| `errorNNN` | `req, res, exception` | Une page d'erreur est envoyée, par exemple `error404` |\n| `error` | `obj` | Le framework journalise une erreur |\n| `route` | `type, route` | Une route est enregistrée |\n| `install` | `type, name, module` | Un fichier (contrôleur, modèle, plugin...) est installé |\n| `configure` | `CONF` | La configuration a été (re)chargée |\n| `websocket` | `req, socket, head` | Une requête d'upgrade WebSocket arrive |\n| `websocket_begin`, `websocket_end` | `controller, client` | Un client WebSocket se connecte ou se déconnecte |\n| `clear` | `type, [value]` | Un cache interne est vidé |\n| `cache_set`, `cache_expired` | `key, value, ...` | Une valeur `CACHE` est définie ou expire |\n| `mail` | `message` | Un e-mail est en cours d'envoi |\n| `message` | `msg, handle` | Le processus reçoit un message IPC |\n| `exit` | `signal` | L'application s'arrête |\n\nChaque événement a sa propre entrée dans la référence, avec les arguments exacts.\n\n## Nettoyer les flux\n\n`CLEANUP(stream, [callback])` attend qu'un flux soit terminé, le détruit puis appelle le callback. Sans callback, il renvoie une Promise. Utilise-le pour libérer les descripteurs de fichiers après un pipe de flux :\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Attendre et différer\n\n`WAIT(validator, callback, [timeout], [interval])` vérifie `validator()` toutes les `interval` ms (500) jusqu'à ce qu'il renvoie `true`, ou échoue après `timeout` ms (5000) :\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` est un timeout nommé. Le rappeler avec le même nom annule le timer précédent, de sorte que la fonction s'exécute une seule fois après le dernier appel (un debounce). Avec `limit`, après ce nombre de reports, la fonction s'exécute immédiatement. `clearTimeout2(name)` l'annule.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` fait répondre le serveur `503` à chaque requête tant qu'au moins un nom est en pause, par exemple pendant une migration.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPI1fl60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Pianificazione ed eventi","summary":"Esegui job a un orario, tramite cron o ogni pochi minuti, e reagisci agli eventi del framework con ON() ed EMIT().","markdown":"---\ntitle: Pianificazione ed eventi\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Pianificazione ed eventi\n\n> Esegui job a un orario, tramite cron o ogni pochi minuti, e reagisci agli eventi del framework con ON() ed EMIT().\n\nTotal.js 4 esegue un **servizio** una volta al minuto. Svuota le cache, emette l'evento `service` e avvia i job che hai registrato con `SCHEDULE()`. Gli eventi del framework permettono al tuo codice di reagire alla vita dell'applicazione: avvio, richieste, errori, uscita. Questa guida mostra entrambi. Le firme esatte sono nel riferimento [Pianificazione ed eventi](../../reference/scheduling-and-events/).\n\n## Eseguire codice a un orario prestabilito\n\n`SCHEDULE(date, [repeat], fn)` registra un job. `date` può essere un orario, un `Date`, un timestamp in millisecondi o un'espressione cron.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- Un orario come `'03:00'` indica oggi a quell'ora. Se quell'ora è già passata e imposti `repeat`, la prima esecuzione si sposta in avanti di un `repeat` (qui a domani).\n- `repeat` è un periodo che `Date.add()` comprende: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. Puoi scrivere `'each'` al posto di uno: `'each day'` equivale a `'1 day'`.\n- Senza `repeat` il job viene eseguito una volta e poi si rimuove da solo.\n- Gli orari vengono letti nel fuso orario dell'applicazione, cioè l'impostazione `default_timezone` (`utc` per impostazione predefinita).\n\nIl servizio controlla i job una volta al minuto, quindi un job viene eseguito al primo controllo pari o successivo al suo orario. Non aspettarti una precisione inferiore al minuto.\n\nUna stringa che contiene uno spazio viene sempre letta come espressione cron. Per eseguire un job una sola volta a una data specifica, passa un oggetto `Date` o un timestamp:\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Espressioni cron\n\nUn'espressione cron ha cinque campi separati da spazi: **minuto**, **ora**, **giorno del mese**, **mese** (1-12) e **giorno della settimana**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Valore del campo | Significato |\n| --- | --- |\n| `*` | qualsiasi valore |\n| `5` | esattamente 5 |\n| `1,15,30` | uno dei valori elencati |\n| `9-17` | qualsiasi valore tra 9 e 17, entrambi inclusi |\n\nI giorni della settimana sono numeri da `0` (domenica) a `6` (sabato), oppure nomi. Contano solo le prime due lettere di un nome: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (quindi funziona anche `monday`).\n\nUn job cron non ha l'argomento `repeat`. Viene eseguito a ogni minuto che corrisponde all'espressione, finché non lo rimuovi. Per eseguire un job ogni pochi minuti, elenca i minuti (`'0,15,30,45 * * * *'`) oppure usa un orario con `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Fermare o avviare un job\n\n`SCHEDULE()` restituisce il job. Conservalo per fermare il job in seguito o per eseguirlo subito:\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## L'evento service\n\nSe ti serve qualcosa ogni minuto, ascolta `service`. L'argomento è il numero di esecuzioni dall'avvio dell'applicazione, così puoi ricavare periodi più lunghi:\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nLo stesso tick svuota le cache interne. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) e `default_interval_clear_dnscache` (30) impostano quanti minuti passano tra queste pulizie, e ognuna emette l'evento `clear`.\n\n## Ascoltare gli eventi\n\n`ON(name, fn)` aggiunge un listener. `ONCE(name, fn)` ne aggiunge uno che viene rimosso dopo la prima chiamata. `OFF(name, [fn])` rimuove i listener. `this` dentro un listener è il framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` e `ready` sono speciali: se l'applicazione è già stata caricata quando chiami `ON()`, la funzione viene eseguita immediatamente. Così anche un plugin o un modulo installato in ritardo riceve la sua chiamata `ready`.\n\nPer rimuovere un listener, passa la stessa funzione che hai aggiunto:\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` senza funzione rimuove tutti i listener di quell'evento, compresi quelli del framework. Chiama `OFF()` senza argomenti solo se vuoi davvero rimuovere tutti i listener di tutti gli eventi.\n\n## I tuoi eventi\n\nCon `EMIT()` funziona qualsiasi nome. Usa gli eventi per far comunicare parti dell'app senza che si richiedano a vicenda:\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` passa fino a sette argomenti e chiama i listener in modo sincrono, nell'ordine in cui sono stati aggiunti.\n\n`EMIT2(name, [a], ...)` invia l'evento agli **altri** processi dell'applicazione: i thread, il cluster o il processo padre di un worker. Passa fino a cinque argomenti, quindi devono essere valori serializzabili. In un singolo processo senza thread né cluster non fa nulla; lì usa `EMIT()`.\n\n## Eventi integrati\n\n| Evento | Argomenti | Quando |\n| --- | --- | --- |\n| `init` | | La configurazione è caricata, prima del caricamento dei file dell'app |\n| `load`, `ready` | | Tutti i file sono caricati; `ready` arriva subito dopo `load` |\n| `service` | `counter` | Ogni minuto |\n| `request` | `req, res` | Arriva una richiesta, prima del routing |\n| `request_begin` | `req, res` | La richiesta è preparata per il routing |\n| `request_end` | `req, res` | La risposta è terminata |\n| `controller` | `controller, name, options` | Prima che venga eseguita l'azione di una route |\n| `errorNNN` | `req, res, exception` | Viene inviata una pagina di errore, per esempio `error404` |\n| `error` | `obj` | Il framework registra un errore nel log |\n| `route` | `type, route` | Viene registrata una route |\n| `install` | `type, name, module` | Viene installato un file (controller, modello, plugin...) |\n| `configure` | `CONF` | La configurazione è stata (ri)caricata |\n| `websocket` | `req, socket, head` | Arriva una richiesta di upgrade WebSocket |\n| `websocket_begin`, `websocket_end` | `controller, client` | Un client WebSocket si connette o si disconnette |\n| `clear` | `type, [value]` | Viene svuotata una cache interna |\n| `cache_set`, `cache_expired` | `key, value, ...` | Un valore di `CACHE` viene impostato o scade |\n| `mail` | `message` | Si sta inviando un'e-mail |\n| `message` | `msg, handle` | Il processo riceve un messaggio IPC |\n| `exit` | `signal` | L'applicazione si ferma |\n\nOgni evento ha la propria voce nel riferimento con gli argomenti esatti.\n\n## Ripulire gli stream\n\n`CLEANUP(stream, [callback])` attende che uno stream abbia finito, lo distrugge e poi chiama la callback. Senza callback restituisce una Promise. Usalo per liberare gli handle dei file dopo aver fatto il pipe di uno stream:\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Attesa e ritardo\n\n`WAIT(validator, callback, [timeout], [interval])` controlla `validator()` ogni `interval` ms (500) finché non restituisce `true`, oppure fallisce dopo `timeout` ms (5000):\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` è un timeout con nome. Chiamarlo di nuovo con lo stesso nome annulla il timer precedente, quindi la funzione viene eseguita una volta dopo l'ultima chiamata (un debounce). Con `limit`, dopo quel numero di rinvii la funzione viene eseguita subito. `clearTimeout2(name)` lo annulla.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` fa rispondere il server a ogni richiesta con `503` finché almeno un nome è in pausa, per esempio durante una migrazione.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPI1fl60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Plánovanie a udalosti","summary":"Spúšťaj úlohy v určený čas, cez cron alebo každých pár minút a reaguj na udalosti frameworku cez ON() a EMIT().","markdown":"---\ntitle: \"Plánovanie a udalosti\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Plánovanie a udalosti\n\n> Spúšťaj úlohy v určený čas, cez cron alebo každých pár minút a reaguj na udalosti frameworku cez ON() a EMIT().\n\nTotal.js 4 spúšťa raz za minútu **službu**. Tá čistí cache, vyšle udalosť `service` a spustí úlohy, ktoré si zaregistroval cez `SCHEDULE()`. Udalosti frameworku umožňujú tvojmu kódu reagovať na život aplikácie: štart, požiadavky, chyby, ukončenie. Tento návod ukazuje oboje. Presné signatúry nájdeš v referencii [Plánovanie a udalosti](../../reference/scheduling-and-events/).\n\n## Spustenie kódu v určený čas\n\n`SCHEDULE(date, [repeat], fn)` zaregistruje úlohu. `date` môže byť čas, `Date`, časová značka v milisekundách alebo cron výraz.\n\n```js\n// definitions/jobs.js\n\n// Every day at 03:00\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n\n// Once, in ten minutes\nSCHEDULE(Date.now() + 1000 * 60 * 10, function() {\n\tconsole.log('Ten minutes later');\n});\n```\n\n- Čas ako `'03:00'` znamená dnes v tom čase. Ak ten čas už prešiel a nastavíš `repeat`, prvé spustenie sa posunie o jedno `repeat` (tu na zajtra).\n- `repeat` je obdobie, ktorému rozumie `Date.add()`: `'5 minutes'`, `'2 hours'`, `'1 day'`, `'1 week'`. Pre jednotku môžeš napísať `'each'`: `'each day'` je to isté ako `'1 day'`.\n- Bez `repeat` sa úloha spustí raz a potom sa sama odstráni.\n- Časy sa čítajú v časovom pásme aplikácie, čo je nastavenie `default_timezone` (predvolene `utc`).\n\nSlužba kontroluje úlohy raz za minútu, takže úloha sa spustí pri prvej kontrole v jej čase alebo po ňom. Nečakaj presnosť pod jednu minútu.\n\nReťazec, ktorý obsahuje medzeru, sa vždy číta ako cron výraz. Ak chceš úlohu spustiť raz v konkrétny dátum, odovzdaj objekt `Date` alebo časovú značku:\n\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve, 08:00');\n});\n```\n\n## Cron výrazy\n\nCron výraz má päť polí oddelených medzerami: **minúta**, **hodina**, **deň v mesiaci**, **mesiac** (1-12) a **deň v týždni**.\n\n```js\n// At 02:30 every day\nSCHEDULE('30 2 * * *', backup);\n\n// At 08:00 from Monday to Friday\nSCHEDULE('0 8 * * mo-fr', report);\n\n// At 00 and 30 minutes of every hour\nSCHEDULE('0,30 * * * *', sync);\n```\n\n| Hodnota poľa | Význam |\n| --- | --- |\n| `*` | ľubovoľná hodnota |\n| `5` | presne 5 |\n| `1,15,30` | jedna z uvedených hodnôt |\n| `9-17` | ľubovoľná hodnota medzi 9 a 17, vrátane oboch |\n\nDni v týždni sú čísla od `0` (nedeľa) po `6` (sobota) alebo názvy. Počítajú sa len prvé dve písmená názvu: `su`, `mo`, `tu`, `we`, `th`, `fr`, `sa` (takže funguje aj `monday`).\n\nCron úloha nemá argument `repeat`. Spúšťa sa v každej minúte, ktorá zodpovedá výrazu, kým ju neodstrániš. Ak chceš úlohu spúšťať každých pár minút, vymenuj minúty (`'0,15,30,45 * * * *'`) alebo použi čas s `repeat` (`SCHEDULE('00:00', '15 minutes', fn)`).\n\n## Zastavenie alebo spustenie úlohy\n\n`SCHEDULE()` vráti úlohu. Odlož si ju, aby si ju neskôr mohol zastaviť alebo ju hneď spustiť:\n\n```js\nvar job = SCHEDULE('0 * * * *', function() {\n\tconsole.log('Every full hour');\n});\n\n// Run it now, outside its time\njob.exec();\n\n// Stop it\njob.remove();\n```\n\n## Udalosť service\n\nAk potrebuješ niečo každú minútu, počúvaj `service`. Argumentom je počet spustení od štartu aplikácie, takže z neho môžeš odvodiť dlhšie obdobia:\n\n```js\nON('service', function(counter) {\n\n\t// Every 5 minutes\n\tif (counter % 5 === 0)\n\t\trefreshrates();\n\n\t// Every hour\n\tif (counter % 60 === 0)\n\t\tcleanold();\n});\n```\n\nTen istý tik čistí interné cache. `default_interval_clear_cache` (10), `default_interval_clear_resources` (20) a `default_interval_clear_dnscache` (30) určujú, koľko minút uplynie medzi týmito čisteniami, a každé z nich vyšle udalosť `clear`.\n\n## Počúvanie udalostí\n\n`ON(name, fn)` pridá poslucháča. `ONCE(name, fn)` pridá poslucháča, ktorý sa po prvom zavolaní odstráni. `OFF(name, [fn])` poslucháčov odstráni. `this` vnútri poslucháča je framework (`F`).\n\n```js\nON('ready', function() {\n\tconsole.log('The application is ready');\n});\n\nON('request_end', function(req, res) {\n\t// every finished request\n});\n\nONCE('service', function() {\n\tconsole.log('The first service tick');\n});\n```\n\n`init`, `load` a `ready` sú špeciálne: ak je aplikácia už načítaná, keď zavoláš `ON()`, funkcia sa spustí okamžite. Takže aj plugin alebo modul nainštalovaný neskoro dostane svoje volanie `ready`.\n\nAk chceš odstrániť jedného poslucháča, odovzdaj tú istú funkciu, ktorú si pridal:\n\n```js\nfunction onrequest(req, res) {\n\tconsole.log(req.method, req.url);\n}\n\nON('request', onrequest);\n\n// later\nOFF('request', onrequest);\n```\n\n`OFF(name)` bez funkcie odstráni všetkých poslucháčov tejto udalosti vrátane vlastných poslucháčov frameworku. `OFF()` bez argumentov volaj len vtedy, ak naozaj chceš odstrániť všetkých poslucháčov všetkých udalostí.\n\n## Vlastné udalosti\n\nS `EMIT()` funguje akýkoľvek názov. Udalosti použi na to, aby časti aplikácie mohli komunikovať bez toho, aby sa navzájom requirovali:\n\n```js\n// schemas/orders.js\nEMIT('order_created', order);\n\n// definitions/notify.js\nON('order_created', function(order) {\n\tMAIL(order.email, 'Thank you', '@mail/order', order);\n});\n```\n\n`EMIT(name, [a], [b], ...)` odovzdá až sedem argumentov a volá poslucháčov synchrónne, v poradí, v akom boli pridaní.\n\n`EMIT2(name, [a], ...)` pošle udalosť **ostatným** procesom aplikácie: vláknam, klastru alebo rodičovskému procesu workera. Odovzdá až päť argumentov, takže musia byť serializovateľné. V jednom procese bez vlákien alebo klastra nerobí nič; tam použi `EMIT()`.\n\n## Vstavané udalosti\n\n| Udalosť | Argumenty | Kedy |\n| --- | --- | --- |\n| `init` | | Konfigurácia je načítaná, pred načítaním súborov aplikácie |\n| `load`, `ready` | | Všetky súbory sú načítané; `ready` príde hneď po `load` |\n| `service` | `counter` | Každú minútu |\n| `request` | `req, res` | Prišla požiadavka, pred smerovaním |\n| `request_begin` | `req, res` | Požiadavka je pripravená na smerovanie |\n| `request_end` | `req, res` | Odpoveď skončila |\n| `controller` | `controller, name, options` | Pred spustením akcie trasy |\n| `errorNNN` | `req, res, exception` | Odosiela sa chybová stránka, napríklad `error404` |\n| `error` | `obj` | Framework zaloguje chybu |\n| `route` | `type, route` | Zaregistruje sa trasa |\n| `install` | `type, name, module` | Nainštaluje sa súbor (kontrolér, model, plugin...) |\n| `configure` | `CONF` | Konfigurácia bola (znovu) načítaná |\n| `websocket` | `req, socket, head` | Prišla požiadavka na WebSocket upgrade |\n| `websocket_begin`, `websocket_end` | `controller, client` | WebSocket klient sa pripojí alebo odpojí |\n| `clear` | `type, [value]` | Vyčistí sa interná cache |\n| `cache_set`, `cache_expired` | `key, value, ...` | Hodnota `CACHE` sa nastaví alebo vyprší |\n| `mail` | `message` | Odosiela sa e-mail |\n| `message` | `msg, handle` | Proces prijme IPC správu |\n| `exit` | `signal` | Aplikácia sa zastavuje |\n\nKaždá udalosť má v referencii vlastný záznam s presnými argumentmi.\n\n## Upratovanie streamov\n\n`CLEANUP(stream, [callback])` počká, kým stream skončí, zničí ho a potom zavolá callback. Bez callbacku vráti Promise. Použi ho na uvoľnenie súborových handlerov po tom, čo stream presmeruješ cez pipe:\n\n```js\nvar stream = F.Fs.createReadStream(PATH.public('big.zip'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('big.zip')));\nCLEANUP(stream, function() {\n\tconsole.log('The file is closed');\n});\n```\n\n## Čakanie a oneskorenie\n\n`WAIT(validator, callback, [timeout], [interval])` kontroluje `validator()` každých `interval` ms (500), kým nevráti `true`, alebo zlyhá po `timeout` ms (5000):\n\n```js\nWAIT(() => MAIN.db != null, function(err) {\n\tif (err)\n\t\tconsole.log('The database did not connect in time');\n\telse\n\t\tconsole.log('Connected');\n}, 10000, 200);\n```\n\n`setTimeout2(name, fn, timeout, [limit], [param])` je pomenovaný timeout. Ďalšie zavolanie s rovnakým názvom zruší predchádzajúci časovač, takže funkcia sa spustí raz po poslednom volaní (debounce). S `limit` sa funkcia po toľkých odloženiach spustí okamžite. `clearTimeout2(name)` ho zruší.\n\n```js\nON('request_end', function() {\n\t// write statistics 5 s after the last request,\n\t// but at least every 100 requests\n\tsetTimeout2('stats', savestats, 5000, 100);\n});\n```\n\n`PAUSESERVER(name, [enable])` spôsobí, že server odpovedá na každú požiadavku kódom `503`, kým je pozastavený aspoň jeden názov, napríklad počas migrácie.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmFh3di60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"File storage","summary":"Save, read, serve and manage binary files with FILESTORAGE().","markdown":"---\ntitle: File storage\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# File storage\n\n> Save, read, serve and manage binary files with FILESTORAGE().\n\n`FILESTORAGE(name)` returns a file storage: a folder on the disk that keeps binary files under an ID, together with their name, content type, size and other metadata. Use it for uploads, attachments, photos and exports that the application stores itself. The full list of methods is in the reference of [File storage](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nThe first call creates the storage object; later calls with the same name return the same object.\n\n## Where the files live\n\nA storage named `photos` lives in `databases/fs-photos/` (`PATH.filestorage('photos')`, inside the folder set by `directory_databases`). Files are spread into subfolders with four-digit names, computed from a hash of the ID, so one folder never holds too many files:\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Each `.file` has a header of 2000 bytes with the metadata as JSON, followed by the content of the file.\n- `files.log` is a NoSQL text database with the metadata of all files. `browse()` and `count()` read it; `save()`, `rename()`, `remove()` and `clean()` keep it up to date; `rebuild()` creates it again from the files.\n\nThe ID is part of the file name on the disk. Use IDs that you generate (`UID()`), and never pass an unchecked value from a request as the ID.\n\n## Saving files\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` stores `data` under `id`. `name` is the file name with its extension; the extension sets the content type. `data` can be:\n\n- a path to a file on the disk,\n- a `Buffer`,\n- a readable stream,\n- a URL (`http://` or `https://`): the file is downloaded first; `headers` are sent with that request.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` is any value you want to keep with the file; it comes back as `meta.custom`. `expire` is a period such as `'1 hour'` or `'7 days'`: after it, the file can no longer be read and `clean()` removes it. `savejson(id, value)` saves an object as a JSON file and `readjson(id, callback)` reads it back.\n\n## The meta object\n\nEvery read returns the metadata of the file:\n\n| Property | What it contains |\n| --- | --- |\n| `id` | The ID of the file |\n| `name` | The file name (at most 250 characters) |\n| `ext` | The extension, without the dot |\n| `type` | The content type, from the extension |\n| `size` | The size of the content in bytes |\n| `date` | When the file was saved |\n| `width`, `height` | The dimensions of a GIF, PNG, JPEG or SVG image |\n| `custom` | The `custom` value given to `save()` |\n| `expire` | The expiration date, when `expire` was given to `save()` |\n\n## Reading files\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` gives an error `File not found`, `Invalid file` or `File is expired`, or the error of the file system when the file does not exist. Pass `true` as the third argument of `read()` to get the metadata without opening a stream. `readbase64()` returns the content as a Base64 string, and `image(id, callback)` returns an `Image` object to resize or convert the stored picture.\n\nWithout a callback, most methods return a promise:\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Serving files over HTTP\n\nA controller sends a stored file with `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nThe response has the stored content type, the `Last-Modified` header and the headers `X-Size`, `X-Width` and `X-Height`. A request with `If-Modified-Since` gets `304 Not Modified`, and a request with a `Range` header gets a part of the file (`206`), so audio and video can be played from the storage. A file that does not exist or has expired gives `404`.\n\n`checkmeta(meta)` decides whether the file may be sent; return `false` to answer with `404`:\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` processes the image with GraphicsMagick (or ImageMagick, see `default_image_converter`) and caches the result in the temporary folder, so the processing runs once per URL. The same methods exist on the response object as `res.filefs()` and `res.imagefs()`, for routes that work with `req` and `res`.\n\n## Uploaded files\n\nEvery file in `controller.files` has the method `fs(storage, id, [custom], [expire], [callback])`. It saves the uploaded file into the storage with its original file name:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Changing and removing files\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` writes the content of a file to a path on the disk, and `clone(id, [newid], [callback])` makes a copy of a file inside the storage under a new ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Listing and maintenance\n\n`browse()` returns a NoSQL query builder over `files.log`, so you filter, sort and page the files like any other NoSQL query:\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` returns the number and total size of files from `files.log` and updates `fs.total` and `fs.size`.\n- `browse2()`, `stream()` and `count2()` read the files on the disk instead of `files.log`.\n- `rebuild()` creates `files.log` again from the files on the disk.\n- `backup(filename)` writes all files into one backup file and `restore(filename)` replaces the content of the storage with a backup.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmFh3di60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Dateispeicher","summary":"Speichere, lies, liefere und verwalte Binärdateien mit FILESTORAGE().","markdown":"---\ntitle: Dateispeicher\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Dateispeicher\n\n> Speichere, lies, liefere und verwalte Binärdateien mit FILESTORAGE().\n\n`FILESTORAGE(name)` gibt einen Dateispeicher zurück: einen Ordner auf der Festplatte, der Binärdateien unter einer ID aufbewahrt, zusammen mit ihrem Namen, Content-Type, ihrer Größe und weiteren Metadaten. Verwende ihn für Uploads, Anhänge, Fotos und Exporte, die die Anwendung selbst speichert. Die vollständige Liste der Methoden steht in der Referenz zu [Dateispeicher](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nDer erste Aufruf erstellt das Speicher-Objekt; spätere Aufrufe mit demselben Namen geben dasselbe Objekt zurück.\n\n## Wo die Dateien liegen\n\nEin Speicher namens `photos` liegt in `databases/fs-photos/` (`PATH.filestorage('photos')`, innerhalb des Ordners, der mit `directory_databases` festgelegt ist). Die Dateien werden auf Unterordner mit vierstelligen Namen verteilt, die aus einem Hash der ID berechnet werden, sodass ein Ordner nie zu viele Dateien enthält:\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Jede `.file` hat einen Header von 2000 Bytes mit den Metadaten als JSON, gefolgt vom Inhalt der Datei.\n- `files.log` ist eine NoSQL-Textdatenbank mit den Metadaten aller Dateien. `browse()` und `count()` lesen sie; `save()`, `rename()`, `remove()` und `clean()` halten sie aktuell; `rebuild()` erstellt sie aus den Dateien neu.\n\nDie ID ist Teil des Dateinamens auf der Festplatte. Verwende IDs, die du erzeugst (`UID()`), und übergib nie einen ungeprüften Wert aus einem Request als ID.\n\n## Dateien speichern\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` speichert `data` unter `id`. `name` ist der Dateiname mit seiner Erweiterung; die Erweiterung bestimmt den Content-Type. `data` kann sein:\n\n- ein Pfad zu einer Datei auf der Festplatte,\n- ein `Buffer`,\n- ein lesbarer Stream,\n- eine URL (`http://` oder `https://`): Die Datei wird zuerst heruntergeladen; `headers` werden mit diesem Request gesendet.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` ist ein beliebiger Wert, den du mit der Datei aufbewahren willst; er kommt als `meta.custom` zurück. `expire` ist ein Zeitraum wie `'1 hour'` oder `'7 days'`: Danach kann die Datei nicht mehr gelesen werden, und `clean()` entfernt sie. `savejson(id, value)` speichert ein Objekt als JSON-Datei, und `readjson(id, callback)` liest es zurück.\n\n## Das Meta-Objekt\n\nJedes Lesen gibt die Metadaten der Datei zurück:\n\n| Eigenschaft | Was sie enthält |\n| --- | --- |\n| `id` | Die ID der Datei |\n| `name` | Der Dateiname (höchstens 250 Zeichen) |\n| `ext` | Die Erweiterung, ohne den Punkt |\n| `type` | Der Content-Type, aus der Erweiterung |\n| `size` | Die Größe des Inhalts in Bytes |\n| `date` | Wann die Datei gespeichert wurde |\n| `width`, `height` | Die Abmessungen eines GIF-, PNG-, JPEG- oder SVG-Bildes |\n| `custom` | Der Wert `custom`, der an `save()` übergeben wurde |\n| `expire` | Das Ablaufdatum, wenn `expire` an `save()` übergeben wurde |\n\n## Dateien lesen\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` liefert einen Fehler `File not found`, `Invalid file` oder `File is expired` oder den Fehler des Dateisystems, wenn die Datei nicht existiert. Übergib `true` als drittes Argument von `read()`, um die Metadaten zu erhalten, ohne einen Stream zu öffnen. `readbase64()` gibt den Inhalt als Base64-String zurück, und `image(id, callback)` gibt ein `Image`-Objekt zurück, um das gespeicherte Bild zu skalieren oder umzuwandeln.\n\nOhne Callback geben die meisten Methoden eine Promise zurück:\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Dateien über HTTP ausliefern\n\nEin Controller sendet eine gespeicherte Datei mit `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nDie Response hat den gespeicherten Content-Type, den Header `Last-Modified` und die Header `X-Size`, `X-Width` und `X-Height`. Ein Request mit `If-Modified-Since` erhält `304 Not Modified`, und ein Request mit einem `Range`-Header erhält einen Teil der Datei (`206`), sodass Audio und Video aus dem Speicher abgespielt werden können. Eine Datei, die nicht existiert oder abgelaufen ist, ergibt `404`.\n\n`checkmeta(meta)` entscheidet, ob die Datei gesendet werden darf; gib `false` zurück, um mit `404` zu antworten:\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` verarbeitet das Bild mit GraphicsMagick (oder ImageMagick, siehe `default_image_converter`) und speichert das Ergebnis im temporären Ordner zwischen, sodass die Verarbeitung einmal pro URL läuft. Dieselben Methoden gibt es auf dem Response-Objekt als `res.filefs()` und `res.imagefs()`, für Routen, die mit `req` und `res` arbeiten.\n\n## Hochgeladene Dateien\n\nJede Datei in `controller.files` hat die Methode `fs(storage, id, [custom], [expire], [callback])`. Sie speichert die hochgeladene Datei mit ihrem ursprünglichen Dateinamen im Speicher:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Dateien ändern und entfernen\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` schreibt den Inhalt einer Datei in einen Pfad auf der Festplatte, und `clone(id, [newid], [callback])` erstellt eine Kopie einer Datei innerhalb des Speichers unter einer neuen ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Auflisten und Wartung\n\n`browse()` gibt einen NoSQL-Query-Builder über `files.log` zurück, sodass du die Dateien wie bei jeder anderen NoSQL-Abfrage filterst, sortierst und seitenweise abrufst:\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` gibt die Anzahl und die Gesamtgröße der Dateien aus `files.log` zurück und aktualisiert `fs.total` und `fs.size`.\n- `browse2()`, `stream()` und `count2()` lesen die Dateien auf der Festplatte statt `files.log`.\n- `rebuild()` erstellt `files.log` aus den Dateien auf der Festplatte neu.\n- `backup(filename)` schreibt alle Dateien in eine Sicherungsdatei, und `restore(filename)` ersetzt den Inhalt des Speichers durch eine Sicherung.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmFh3di60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Almacenamiento de archivos","summary":"Guarda, lee, sirve y gestiona archivos binarios con FILESTORAGE().","markdown":"---\ntitle: Almacenamiento de archivos\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Almacenamiento de archivos\n\n> Guarda, lee, sirve y gestiona archivos binarios con FILESTORAGE().\n\n`FILESTORAGE(name)` devuelve un almacenamiento de archivos: una carpeta en el disco que guarda archivos binarios bajo un ID, junto con su nombre, tipo de contenido, tamaño y otros metadatos. Úsalo para subidas, adjuntos, fotos y exportaciones que la propia aplicación almacena. La lista completa de métodos está en la referencia de [Almacenamiento de archivos](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nLa primera llamada crea el objeto de almacenamiento; las llamadas posteriores con el mismo nombre devuelven el mismo objeto.\n\n## Dónde viven los archivos\n\nUn almacenamiento llamado `photos` vive en `databases/fs-photos/` (`PATH.filestorage('photos')`, dentro de la carpeta definida por `directory_databases`). Los archivos se reparten en subcarpetas con nombres de cuatro dígitos, calculados a partir de un hash del ID, para que una carpeta nunca contenga demasiados archivos:\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Cada `.file` tiene una cabecera de 2000 bytes con los metadatos en JSON, seguida del contenido del archivo.\n- `files.log` es una base de datos de texto NoSQL con los metadatos de todos los archivos. `browse()` y `count()` la leen; `save()`, `rename()`, `remove()` y `clean()` la mantienen actualizada; `rebuild()` la vuelve a crear a partir de los archivos.\n\nEl ID forma parte del nombre del archivo en el disco. Usa IDs que generes tú (`UID()`) y nunca pases como ID un valor de una petición sin comprobar.\n\n## Guardar archivos\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` guarda `data` bajo `id`. `name` es el nombre del archivo con su extensión; la extensión define el tipo de contenido. `data` puede ser:\n\n- una ruta a un archivo en el disco,\n- un `Buffer`,\n- un stream de lectura,\n- una URL (`http://` o `https://`): primero se descarga el archivo; `headers` se envían con esa petición.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` es cualquier valor que quieras guardar con el archivo; vuelve como `meta.custom`. `expire` es un periodo como `'1 hour'` o `'7 days'`: después, el archivo ya no se puede leer y `clean()` lo elimina. `savejson(id, value)` guarda un objeto como archivo JSON y `readjson(id, callback)` lo vuelve a leer.\n\n## El objeto meta\n\nCada lectura devuelve los metadatos del archivo:\n\n| Propiedad | Qué contiene |\n| --- | --- |\n| `id` | El ID del archivo |\n| `name` | El nombre del archivo (como máximo 250 caracteres) |\n| `ext` | La extensión, sin el punto |\n| `type` | El tipo de contenido, según la extensión |\n| `size` | El tamaño del contenido en bytes |\n| `date` | Cuándo se guardó el archivo |\n| `width`, `height` | Las dimensiones de una imagen GIF, PNG, JPEG o SVG |\n| `custom` | El valor `custom` pasado a `save()` |\n| `expire` | La fecha de expiración, cuando se pasó `expire` a `save()` |\n\n## Leer archivos\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` da un error `File not found`, `Invalid file` o `File is expired`, o el error del sistema de archivos cuando el archivo no existe. Pasa `true` como tercer argumento de `read()` para obtener los metadatos sin abrir un stream. `readbase64()` devuelve el contenido como un string Base64, e `image(id, callback)` devuelve un objeto `Image` para redimensionar o convertir la imagen guardada.\n\nSin callback, la mayoría de los métodos devuelven una promesa:\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Servir archivos por HTTP\n\nUn controlador envía un archivo guardado con `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nLa respuesta tiene el tipo de contenido guardado, la cabecera `Last-Modified` y las cabeceras `X-Size`, `X-Width` y `X-Height`. Una petición con `If-Modified-Since` obtiene `304 Not Modified`, y una petición con cabecera `Range` obtiene una parte del archivo (`206`), así que el audio y el vídeo se pueden reproducir desde el almacenamiento. Un archivo que no existe o que ha expirado da `404`.\n\n`checkmeta(meta)` decide si el archivo se puede enviar; devuelve `false` para responder con `404`:\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` procesa la imagen con GraphicsMagick (o ImageMagick, consulta `default_image_converter`) y guarda el resultado en caché en la carpeta temporal, así que el procesamiento se ejecuta una vez por URL. Los mismos métodos existen en el objeto de respuesta como `res.filefs()` y `res.imagefs()`, para rutas que trabajan con `req` y `res`.\n\n## Archivos subidos\n\nCada archivo de `controller.files` tiene el método `fs(storage, id, [custom], [expire], [callback])`. Guarda el archivo subido en el almacenamiento con su nombre de archivo original:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Modificar y eliminar archivos\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` escribe el contenido de un archivo en una ruta del disco, y `clone(id, [newid], [callback])` hace una copia de un archivo dentro del almacenamiento bajo un nuevo ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Listado y mantenimiento\n\n`browse()` devuelve un query builder NoSQL sobre `files.log`, así que filtras, ordenas y paginas los archivos como cualquier otra consulta NoSQL:\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` devuelve el número y el tamaño total de los archivos de `files.log` y actualiza `fs.total` y `fs.size`.\n- `browse2()`, `stream()` y `count2()` leen los archivos del disco en lugar de `files.log`.\n- `rebuild()` vuelve a crear `files.log` a partir de los archivos del disco.\n- `backup(filename)` escribe todos los archivos en un único archivo de copia de seguridad y `restore(filename)` reemplaza el contenido del almacenamiento con una copia de seguridad.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmFh3di60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Stockage de fichiers","summary":"Enregistre, lis, sers et gère des fichiers binaires avec FILESTORAGE().","markdown":"---\ntitle: Stockage de fichiers\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Stockage de fichiers\n\n> Enregistre, lis, sers et gère des fichiers binaires avec FILESTORAGE().\n\n`FILESTORAGE(name)` renvoie un stockage de fichiers : un dossier sur le disque qui conserve des fichiers binaires sous un ID, avec leur nom, leur type de contenu, leur taille et d'autres métadonnées. Utilise-le pour les uploads, les pièces jointes, les photos et les exports que l'application stocke elle-même. La liste complète des méthodes se trouve dans la référence du [Stockage de fichiers](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nLe premier appel crée l'objet de stockage ; les appels suivants avec le même nom renvoient le même objet.\n\n## Où se trouvent les fichiers\n\nUn stockage nommé `photos` se trouve dans `databases/fs-photos/` (`PATH.filestorage('photos')`, dans le dossier défini par `directory_databases`). Les fichiers sont répartis dans des sous-dossiers aux noms à quatre chiffres, calculés à partir d'un hash de l'ID, de sorte qu'un dossier ne contient jamais trop de fichiers :\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Chaque `.file` a un en-tête de 2000 octets contenant les métadonnées en JSON, suivi du contenu du fichier.\n- `files.log` est une base de données texte NoSQL avec les métadonnées de tous les fichiers. `browse()` et `count()` la lisent ; `save()`, `rename()`, `remove()` et `clean()` la maintiennent à jour ; `rebuild()` la recrée à partir des fichiers.\n\nL'ID fait partie du nom du fichier sur le disque. Utilise des ID que tu génères (`UID()`), et ne passe jamais comme ID une valeur non vérifiée provenant d'une requête.\n\n## Enregistrer des fichiers\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` stocke `data` sous `id`. `name` est le nom du fichier avec son extension ; l'extension détermine le type de contenu. `data` peut être :\n\n- un chemin vers un fichier sur le disque,\n- un `Buffer`,\n- un flux lisible,\n- une URL (`http://` ou `https://`) : le fichier est d'abord téléchargé ; les `headers` sont envoyés avec cette requête.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` est n'importe quelle valeur que tu veux conserver avec le fichier ; elle revient sous la forme `meta.custom`. `expire` est une période comme `'1 hour'` ou `'7 days'` : passé ce délai, le fichier ne peut plus être lu et `clean()` le supprime. `savejson(id, value)` enregistre un objet sous forme de fichier JSON et `readjson(id, callback)` le relit.\n\n## L'objet meta\n\nChaque lecture renvoie les métadonnées du fichier :\n\n| Propriété | Ce qu'elle contient |\n| --- | --- |\n| `id` | L'ID du fichier |\n| `name` | Le nom du fichier (250 caractères au maximum) |\n| `ext` | L'extension, sans le point |\n| `type` | Le type de contenu, déduit de l'extension |\n| `size` | La taille du contenu en octets |\n| `date` | La date d'enregistrement du fichier |\n| `width`, `height` | Les dimensions d'une image GIF, PNG, JPEG ou SVG |\n| `custom` | La valeur `custom` passée à `save()` |\n| `expire` | La date d'expiration, quand `expire` a été passé à `save()` |\n\n## Lire des fichiers\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` renvoie une erreur `File not found`, `Invalid file` ou `File is expired`, ou l'erreur du système de fichiers quand le fichier n'existe pas. Passe `true` en troisième argument de `read()` pour obtenir les métadonnées sans ouvrir de flux. `readbase64()` renvoie le contenu sous forme de chaîne Base64, et `image(id, callback)` renvoie un objet `Image` pour redimensionner ou convertir l'image stockée.\n\nSans callback, la plupart des méthodes renvoient une promesse :\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Servir des fichiers en HTTP\n\nUn contrôleur envoie un fichier stocké avec `this.filefs(name, id, [download], [headers], [callback], [checkmeta])` :\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nLa réponse comporte le type de contenu stocké, l'en-tête `Last-Modified` et les en-têtes `X-Size`, `X-Width` et `X-Height`. Une requête avec `If-Modified-Since` reçoit `304 Not Modified`, et une requête avec un en-tête `Range` reçoit une partie du fichier (`206`) ; l'audio et la vidéo peuvent donc être lus depuis le stockage. Un fichier inexistant ou expiré donne `404`.\n\n`checkmeta(meta)` décide si le fichier peut être envoyé ; renvoie `false` pour répondre `404` :\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` traite l'image avec GraphicsMagick (ou ImageMagick, voir `default_image_converter`) et met le résultat en cache dans le dossier temporaire ; le traitement ne s'exécute donc qu'une fois par URL. Les mêmes méthodes existent sur l'objet réponse sous les noms `res.filefs()` et `res.imagefs()`, pour les routes qui travaillent avec `req` et `res`.\n\n## Fichiers uploadés\n\nChaque fichier de `controller.files` possède la méthode `fs(storage, id, [custom], [expire], [callback])`. Elle enregistre le fichier uploadé dans le stockage avec son nom de fichier d'origine :\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Modifier et supprimer des fichiers\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` écrit le contenu d'un fichier vers un chemin sur le disque, et `clone(id, [newid], [callback])` crée une copie d'un fichier à l'intérieur du stockage sous un nouvel ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Liste et maintenance\n\n`browse()` renvoie un query builder NoSQL sur `files.log` ; tu filtres, tries et pagines donc les fichiers comme n'importe quelle autre requête NoSQL :\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` renvoie le nombre et la taille totale des fichiers depuis `files.log` et met à jour `fs.total` et `fs.size`.\n- `browse2()`, `stream()` et `count2()` lisent les fichiers sur le disque au lieu de `files.log`.\n- `rebuild()` recrée `files.log` à partir des fichiers sur le disque.\n- `backup(filename)` écrit tous les fichiers dans un seul fichier de sauvegarde et `restore(filename)` remplace le contenu du stockage par une sauvegarde.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmFh3di60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Archiviazione file","summary":"Salva, leggi, servi e gestisci file binari con FILESTORAGE().","markdown":"---\ntitle: Archiviazione file\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Archiviazione file\n\n> Salva, leggi, servi e gestisci file binari con FILESTORAGE().\n\n`FILESTORAGE(name)` restituisce un'archiviazione file: una cartella sul disco che conserva file binari sotto un ID, insieme a nome, content type, dimensione e altri metadati. Usala per upload, allegati, foto ed esportazioni che l'applicazione salva da sé. L'elenco completo dei metodi è nel riferimento di [Archiviazione file](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nLa prima chiamata crea l'oggetto di archiviazione; le chiamate successive con lo stesso nome restituiscono lo stesso oggetto.\n\n## Dove si trovano i file\n\nUn'archiviazione chiamata `photos` si trova in `databases/fs-photos/` (`PATH.filestorage('photos')`, dentro la cartella impostata da `directory_databases`). I file sono distribuiti in sottocartelle con nomi di quattro cifre, calcolati da un hash dell'ID, così una cartella non contiene mai troppi file:\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Ogni `.file` ha un'intestazione di 2000 byte con i metadati in JSON, seguita dal contenuto del file.\n- `files.log` è un database di testo NoSQL con i metadati di tutti i file. `browse()` e `count()` lo leggono; `save()`, `rename()`, `remove()` e `clean()` lo mantengono aggiornato; `rebuild()` lo ricrea a partire dai file.\n\nL'ID fa parte del nome del file sul disco. Usa ID che generi tu (`UID()`) e non passare mai come ID un valore non verificato proveniente da una richiesta.\n\n## Salvare i file\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` salva `data` sotto `id`. `name` è il nome del file con la sua estensione; l'estensione imposta il content type. `data` può essere:\n\n- un percorso a un file sul disco,\n- un `Buffer`,\n- uno stream leggibile,\n- un URL (`http://` o `https://`): il file viene prima scaricato; gli `headers` vengono inviati con quella richiesta.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` è qualsiasi valore che vuoi conservare con il file; torna indietro come `meta.custom`. `expire` è un periodo come `'1 hour'` o `'7 days'`: trascorso questo, il file non può più essere letto e `clean()` lo rimuove. `savejson(id, value)` salva un oggetto come file JSON e `readjson(id, callback)` lo rilegge.\n\n## L'oggetto meta\n\nOgni lettura restituisce i metadati del file:\n\n| Proprietà | Cosa contiene |\n| --- | --- |\n| `id` | L'ID del file |\n| `name` | Il nome del file (al massimo 250 caratteri) |\n| `ext` | L'estensione, senza il punto |\n| `type` | Il content type, dall'estensione |\n| `size` | La dimensione del contenuto in byte |\n| `date` | Quando il file è stato salvato |\n| `width`, `height` | Le dimensioni di un'immagine GIF, PNG, JPEG o SVG |\n| `custom` | Il valore `custom` passato a `save()` |\n| `expire` | La data di scadenza, quando `expire` è stato passato a `save()` |\n\n## Leggere i file\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` restituisce un errore `File not found`, `Invalid file` o `File is expired`, oppure l'errore del file system quando il file non esiste. Passa `true` come terzo argomento di `read()` per ottenere i metadati senza aprire uno stream. `readbase64()` restituisce il contenuto come stringa Base64, e `image(id, callback)` restituisce un oggetto `Image` per ridimensionare o convertire l'immagine salvata.\n\nSenza callback, la maggior parte dei metodi restituisce una promise:\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Servire i file via HTTP\n\nUn controller invia un file salvato con `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nLa risposta ha il content type salvato, l'intestazione `Last-Modified` e le intestazioni `X-Size`, `X-Width` e `X-Height`. Una richiesta con `If-Modified-Since` riceve `304 Not Modified`, e una richiesta con un'intestazione `Range` riceve una parte del file (`206`), così audio e video possono essere riprodotti dall'archiviazione. Un file che non esiste o è scaduto restituisce `404`.\n\n`checkmeta(meta)` decide se il file può essere inviato; restituisci `false` per rispondere con `404`:\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` elabora l'immagine con GraphicsMagick (o ImageMagick, vedi `default_image_converter`) e mette in cache il risultato nella cartella temporanea, così l'elaborazione viene eseguita una sola volta per URL. Gli stessi metodi esistono sull'oggetto risposta come `res.filefs()` e `res.imagefs()`, per le route che lavorano con `req` e `res`.\n\n## File caricati\n\nOgni file in `controller.files` ha il metodo `fs(storage, id, [custom], [expire], [callback])`. Salva il file caricato nell'archiviazione con il suo nome originale:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Modificare e rimuovere file\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` scrive il contenuto di un file in un percorso sul disco, e `clone(id, [newid], [callback])` crea una copia di un file all'interno dell'archiviazione con un nuovo ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Elenco e manutenzione\n\n`browse()` restituisce un query builder NoSQL su `files.log`, così filtri, ordini e pagini i file come qualsiasi altra query NoSQL:\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` restituisce il numero e la dimensione totale dei file da `files.log` e aggiorna `fs.total` e `fs.size`.\n- `browse2()`, `stream()` e `count2()` leggono i file sul disco invece di `files.log`.\n- `rebuild()` ricrea `files.log` a partire dai file sul disco.\n- `backup(filename)` scrive tutti i file in un unico file di backup e `restore(filename)` sostituisce il contenuto dell'archiviazione con un backup.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmFh3di60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/file-storage/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Úložisko súborov","summary":"Ukladaj, čítaj, poskytuj a spravuj binárne súbory cez FILESTORAGE().","markdown":"---\ntitle: \"Úložisko súborov\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Úložisko súborov\n\n> Ukladaj, čítaj, poskytuj a spravuj binárne súbory cez FILESTORAGE().\n\n`FILESTORAGE(name)` vráti úložisko súborov: priečinok na disku, ktorý uchováva binárne súbory pod ID spolu s ich názvom, typom obsahu, veľkosťou a ďalšími metadátami. Použi ho pre nahrané súbory, prílohy, fotky a exporty, ktoré si aplikácia ukladá sama. Úplný zoznam metód nájdeš v referencii [Úložisko súborov](../../reference/file-storage/).\n\n```js\nvar fs = FILESTORAGE('photos');\n\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'), function(err, meta) {\n\t// meta.id, meta.name, meta.size, meta.type, meta.width, meta.height\n\tconsole.log(meta);\n});\n```\n\nPrvé volanie vytvorí objekt úložiska; ďalšie volania s rovnakým názvom vrátia ten istý objekt.\n\n## Kde sú súbory uložené\n\nÚložisko s názvom `photos` je v `databases/fs-photos/` (`PATH.filestorage('photos')`, vnútri priečinka nastaveného cez `directory_databases`). Súbory sa rozdeľujú do podpriečinkov so štvormiestnymi názvami, vypočítanými z hashu ID, takže jeden priečinok nikdy nemá príliš veľa súborov:\n\n```\ndatabases/\n\tfs-photos/\n\t\tfiles.log\n\t\t0384/\n\t\t\t1fs3001xb41f.file\n\t\t7712/\n\t\t\t1fs3002xb41f.file\n```\n\n- Každý `.file` má hlavičku s veľkosťou 2000 bajtov s metadátami ako JSON, za ňou nasleduje obsah súboru.\n- `files.log` je textová NoSQL databáza s metadátami všetkých súborov. `browse()` a `count()` ju čítajú; `save()`, `rename()`, `remove()` a `clean()` ju udržiavajú aktuálnu; `rebuild()` ju vytvorí znova zo súborov.\n\nID je súčasťou názvu súboru na disku. Používaj ID, ktoré generuješ (`UID()`), a nikdy neodovzdávaj ako ID neskontrolovanú hodnotu z požiadavky.\n\n## Ukladanie súborov\n\n`save(id, name, data, [callback], [custom], [expire], [headers])` uloží `data` pod `id`. `name` je názov súboru s príponou; prípona určuje typ obsahu. `data` môže byť:\n\n- cesta k súboru na disku,\n- `Buffer`,\n- stream na čítanie,\n- URL (`http://` alebo `https://`): súbor sa najprv stiahne; `headers` sa pošlú s touto požiadavkou.\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// From a buffer, with custom data and an expiration\nfs.save(UID(), 'report.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.expire);\n}, { user: 'admin' }, '7 days');\n\n// From a URL, as a promise\nvar meta = await fs.save(UID(), 'avatar.jpg', 'https://example.com/avatar.jpg');\n```\n\n`custom` je ľubovoľná hodnota, ktorú chceš uchovať so súborom; vráti sa ako `meta.custom`. `expire` je obdobie ako `'1 hour'` alebo `'7 days'`: po ňom sa súbor už nedá čítať a `clean()` ho odstráni. `savejson(id, value)` uloží objekt ako JSON súbor a `readjson(id, callback)` ho prečíta späť.\n\n## Objekt meta\n\nKaždé čítanie vráti metadáta súboru:\n\n| Vlastnosť | Čo obsahuje |\n| --- | --- |\n| `id` | ID súboru |\n| `name` | Názov súboru (najviac 250 znakov) |\n| `ext` | Prípona, bez bodky |\n| `type` | Typ obsahu, podľa prípony |\n| `size` | Veľkosť obsahu v bajtoch |\n| `date` | Kedy bol súbor uložený |\n| `width`, `height` | Rozmery obrázka GIF, PNG, JPEG alebo SVG |\n| `custom` | Hodnota `custom` odovzdaná do `save()` |\n| `expire` | Dátum vypršania, keď bolo do `save()` odovzdané `expire` |\n\n## Čítanie súborov\n\n```js\nvar fs = FILESTORAGE('documents');\n\n// A stream of the content\nfs.read(id, function(err, meta) {\n\tif (err)\n\t\treturn;\n\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n\n// Only the metadata\nfs.readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.size);\n});\n\n// The whole content in memory\nfs.readbuffer(id, function(err, buffer, meta) {\n\tconsole.log(buffer.length);\n});\n```\n\n`read()` vráti chybu `File not found`, `Invalid file` alebo `File is expired`, prípadne chybu súborového systému, keď súbor neexistuje. Odovzdaj `true` ako tretí argument `read()`, ak chceš metadáta bez otvorenia streamu. `readbase64()` vráti obsah ako reťazec Base64 a `image(id, callback)` vráti objekt `Image` na zmenu veľkosti alebo prevod uloženého obrázka.\n\nBez callbacku väčšina metód vráti promise:\n\n```js\nvar meta = await FILESTORAGE('documents').read(id, null, true);\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n## Poskytovanie súborov cez HTTP\n\nKontrolér pošle uložený súbor cez `this.filefs(name, id, [download], [headers], [callback], [checkmeta])`:\n\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n\tROUTE('GET /photos/{id}/', photo);\n};\n\nfunction download(id) {\n\t// true: the browser downloads the file with its stored name\n\tthis.filefs('documents', id, true);\n}\n\nfunction photo(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resize(300, 300);\n\t\timage.quality(85);\n\t});\n}\n```\n\nOdpoveď má uložený typ obsahu, hlavičku `Last-Modified` a hlavičky `X-Size`, `X-Width` a `X-Height`. Požiadavka s `If-Modified-Since` dostane `304 Not Modified` a požiadavka s hlavičkou `Range` dostane časť súboru (`206`), takže audio a video sa dajú prehrávať priamo z úložiska. Súbor, ktorý neexistuje alebo mu vypršala platnosť, vráti `404`.\n\n`checkmeta(meta)` rozhodne, či sa súbor môže poslať; vráť `false`, ak chceš odpovedať `404`:\n\n```js\nfunction privatefile(id) {\n\tvar user = this.user;\n\tthis.filefs('documents', id, false, null, null, function(meta) {\n\t\treturn meta.custom && meta.custom.user === user.id;\n\t});\n}\n```\n\n`imagefs()` spracuje obrázok cez GraphicsMagick (alebo ImageMagick, pozri `default_image_converter`) a výsledok uloží do cache v dočasnom priečinku, takže spracovanie prebehne raz pre každú URL. Tie isté metódy existujú na objekte odpovede ako `res.filefs()` a `res.imagefs()` pre trasy, ktoré pracujú s `req` a `res`.\n\n## Nahrané súbory\n\nKaždý súbor v `controller.files` má metódu `fs(storage, id, [custom], [expire], [callback])`. Uloží nahraný súbor do úložiska s jeho pôvodným názvom:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nfunction upload() {\n\tvar self = this;\n\tvar output = [];\n\n\tself.files.wait(function(file, next) {\n\t\tfile.fs('documents', UID(), function(err, meta) {\n\t\t\t!err && output.push({ id: meta.id, name: meta.name, size: meta.size });\n\t\t\tnext();\n\t\t});\n\t}, function() {\n\t\tself.json(output);\n\t});\n}\n```\n\n## Zmena a odstraňovanie súborov\n\n```js\nvar fs = FILESTORAGE('documents');\n\nfs.rename(id, 'new-name.pdf');           // changes the stored name\nfs.move(id, newid);                      // changes the ID\nfs.remove(id);                           // removes one file\nfs.clean();                              // removes expired files\nfs.clear();                              // removes all files (also drop())\n```\n\n`copy(id, path, [callback])` zapíše obsah súboru na cestu na disku a `clone(id, [newid], [callback])` vytvorí kópiu súboru v rámci úložiska pod novým ID.\n\n```js\n// Export to a folder: the file keeps its stored name\nfs.copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log('Saved', meta.name);\n});\n\n// A second copy under a new ID\nfs.clone(id, UID(), function(err, meta) {\n\tconsole.log(meta.id);\n});\n```\n\n## Výpis a údržba\n\n`browse()` vráti NoSQL query builder nad `files.log`, takže súbory filtruješ, radíš a stránkuješ ako pri akomkoľvek inom NoSQL dotaze:\n\n```js\nFILESTORAGE('photos').browse().where('ext', 'png').sort('date_desc').take(20).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n- `count(callback)` vráti počet a celkovú veľkosť súborov z `files.log` a aktualizuje `fs.total` a `fs.size`.\n- `browse2()`, `stream()` a `count2()` čítajú súbory na disku namiesto `files.log`.\n- `rebuild()` vytvorí `files.log` znova zo súborov na disku.\n- `backup(filename)` zapíše všetky súbory do jedného záložného súboru a `restore(filename)` nahradí obsah úložiska zálohou.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm7g69r60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Operations and tasks","summary":"Reusable business logic with operations, chained operations, tasks with steps, commands, extensions and PROMISIFY().","markdown":"---\ntitle: Operations and tasks\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operations and tasks\n\n> Reusable business logic with operations, chained operations, tasks with steps, commands, extensions and PROMISIFY().\n\nOperations and tasks are small units of business logic that are not tied to a route. You declare them once and call them from controllers, schemas, schedulers or other operations. An **operation** is one function with a callback. A **task** is a named set of steps that jump from one to another. Both receive a `$` object that carries the value, the errors and, when there is one, the controller of the current request.\n\n## Declare an operation\n\n`NEWOPERATION(name, fn)` registers a function. The function receives `$` and the value. It must finish with `$.callback()`, `$.success()` or `$.invalid()`.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nPut operations in files in the `/operations/` directory. The framework loads them when the app starts.\n\n## Call an operation\n\n`OPERATION(name, [value], callback, [options], [controller])` runs one operation. The callback receives `err` (an `ErrorBuilder` or `null`), the response and the `options` argument.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nFrom a route, pass the controller. Then `$.user`, `$.query`, `$.params`, `$.body` and the other request properties work inside the operation, and the controller callback sends the answer:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nWithout a controller, request properties such as `$.user` or `$.query` are `null`.\n\n### Repeat, stop and bind errors\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` takes extra options:\n\n- `repeat {Number}` runs the operation again when it ends with an error, up to this number of times.\n- `stop {Boolean}` (default `true`) stops a `RUN()` chain when this operation fails.\n- `binderror {Boolean}` (default `false`) stores the error output as the response of this operation in a `RUN()` chain.\n- `filter {String}` is a schema for the query string. `$.filter` then returns the converted query.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Chain operations with RUN()\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` runs several operations one after another. `names` is a comma-separated string or an array. All operations share the same `$.value`, so one operation can prepare data for the next.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nThe response is an object with one key per operation. With `response_name`, the callback receives only the response of that operation:\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nInside a chain, `$.response` holds the results so far, `$.meta.current` and `$.meta.prev` hold the operation names, and `$.repeated` counts the repeats of the current one. When an operation fails and its `stop` option is `true` (the default), the chain stops and the callback receives the error. An operation name that does not exist is skipped.\n\n## Declare a task\n\n`NEWTASK(name, fn)` declares a set of steps. `fn` receives a `push(step, fn)` function. Each step receives `$` and the value. A step moves on with `$.next(step)` and finishes the task with `$.end()`, `$.success()` or `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nPut tasks in files in the `/tasks/` directory.\n\n## Run a task\n\n`TASK(name, step, callback, [options], [value])` creates the task and starts it at `step`. You can also write the name and the step together as `'name/step'`:\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nPass a controller or the `$` of a schema, operation or task as `options` to share its request and its errors. Anything else in `options` is used as the value. `TASK()` returns the task, so you can add steps with `$.push()` before it starts.\n\n`$.next(a, b, ...)` runs the first step that exists, and ends the task when none exists. `$.next2(step)` and `$.done()` return callbacks for asynchronous functions:\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Commands\n\nCommands are named handlers that any part of the app can trigger. `NEWCOMMAND(name, fn)` adds a handler, and the same name can have several handlers. `CMD(name, [a], [b], [c], [d])` calls all of them.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nThe framework itself uses commands such as `clear_viewscache`, `clear_smtpcache` and `refresh_tms`.\n\n## Extensions\n\n`NEWEXTENSION(code, [callback], [extend])` installs code at runtime from a string or a URL. The code uses `exports` like a module: `exports.install(next)`, `exports.make()`, `exports.done()` and `exports.uninstall()` are optional. Files in the `/extensions/` directory are installed when the app starts.\n\n## Promises\n\n`PROMISIFY(fn, [a], [b])` wraps a function that ends with a `callback(err, response)` in a `Promise`:\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\nThe `$` of a schema has a similar `$.promisify()` method; see [Schemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm7g69r60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Operations und Tasks","summary":"Wiederverwendbare Geschäftslogik mit Operations, verketteten Operations, Tasks mit Schritten, Befehlen, Erweiterungen und PROMISIFY().","markdown":"---\ntitle: Operations und Tasks\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operations und Tasks\n\n> Wiederverwendbare Geschäftslogik mit Operations, verketteten Operations, Tasks mit Schritten, Befehlen, Erweiterungen und PROMISIFY().\n\nOperations und Tasks sind kleine Einheiten von Geschäftslogik, die nicht an eine Route gebunden sind. Du deklarierst sie einmal und rufst sie aus Controllern, Schemas, Schedulern oder anderen Operations auf. Eine **Operation** ist eine Funktion mit einem Callback. Ein **Task** ist eine benannte Menge von Schritten, die von einem zum anderen springen. Beide erhalten ein `$`-Objekt, das den Wert, die Fehler und, falls vorhanden, den Controller des aktuellen Requests trägt.\n\n## Eine Operation deklarieren\n\n`NEWOPERATION(name, fn)` registriert eine Funktion. Die Funktion erhält `$` und den Wert. Sie muss mit `$.callback()`, `$.success()` oder `$.invalid()` enden.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nLege Operations in Dateien im Verzeichnis `/operations/` ab. Das Framework lädt sie beim Start der App.\n\n## Eine Operation aufrufen\n\n`OPERATION(name, [value], callback, [options], [controller])` führt eine Operation aus. Der Callback erhält `err` (einen `ErrorBuilder` oder `null`), die Antwort und das Argument `options`.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nAus einer Route übergibst du den Controller. Dann funktionieren `$.user`, `$.query`, `$.params`, `$.body` und die anderen Request-Eigenschaften innerhalb der Operation, und der Callback des Controllers sendet die Antwort:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nOhne Controller sind Request-Eigenschaften wie `$.user` oder `$.query` `null`.\n\n### Wiederholen, stoppen und Fehler binden\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` nimmt zusätzliche Optionen:\n\n- `repeat {Number}` führt die Operation erneut aus, wenn sie mit einem Fehler endet, bis zu dieser Anzahl von Malen.\n- `stop {Boolean}` (Standard `true`) stoppt eine `RUN()`-Kette, wenn diese Operation fehlschlägt.\n- `binderror {Boolean}` (Standard `false`) speichert die Fehlerausgabe als Antwort dieser Operation in einer `RUN()`-Kette.\n- `filter {String}` ist ein Schema für den Query-String. `$.filter` gibt dann die umgewandelte Query zurück.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Operations mit RUN() verketten\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` führt mehrere Operations nacheinander aus. `names` ist ein kommagetrennter String oder ein Array. Alle Operations teilen sich denselben `$.value`, sodass eine Operation Daten für die nächste vorbereiten kann.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nDie Antwort ist ein Objekt mit einem Schlüssel pro Operation. Mit `response_name` erhält der Callback nur die Antwort dieser Operation:\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nInnerhalb einer Kette enthält `$.response` die bisherigen Ergebnisse, `$.meta.current` und `$.meta.prev` enthalten die Namen der Operations, und `$.repeated` zählt die Wiederholungen der aktuellen. Wenn eine Operation fehlschlägt und ihre Option `stop` `true` ist (der Standard), stoppt die Kette, und der Callback erhält den Fehler. Ein Operation-Name, der nicht existiert, wird übersprungen.\n\n## Einen Task deklarieren\n\n`NEWTASK(name, fn)` deklariert eine Menge von Schritten. `fn` erhält eine Funktion `push(step, fn)`. Jeder Schritt erhält `$` und den Wert. Ein Schritt geht mit `$.next(step)` weiter und beendet den Task mit `$.end()`, `$.success()` oder `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nLege Tasks in Dateien im Verzeichnis `/tasks/` ab.\n\n## Einen Task ausführen\n\n`TASK(name, step, callback, [options], [value])` erstellt den Task und startet ihn bei `step`. Du kannst den Namen und den Schritt auch zusammen als `'name/step'` schreiben:\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nÜbergib einen Controller oder das `$` eines Schemas, einer Operation oder eines Tasks als `options`, um dessen Request und Fehler zu teilen. Alles andere in `options` wird als Wert verwendet. `TASK()` gibt den Task zurück, sodass du vor dem Start mit `$.push()` Schritte hinzufügen kannst.\n\n`$.next(a, b, ...)` führt den ersten Schritt aus, der existiert, und beendet den Task, wenn keiner existiert. `$.next2(step)` und `$.done()` geben Callbacks für asynchrone Funktionen zurück:\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Befehle\n\nBefehle sind benannte Handler, die jeder Teil der App auslösen kann. `NEWCOMMAND(name, fn)` fügt einen Handler hinzu, und derselbe Name kann mehrere Handler haben. `CMD(name, [a], [b], [c], [d])` ruft sie alle auf.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nDas Framework selbst verwendet Befehle wie `clear_viewscache`, `clear_smtpcache` und `refresh_tms`.\n\n## Erweiterungen\n\n`NEWEXTENSION(code, [callback], [extend])` installiert Code zur Laufzeit aus einem String oder einer URL. Der Code verwendet `exports` wie ein Modul: `exports.install(next)`, `exports.make()`, `exports.done()` und `exports.uninstall()` sind optional. Dateien im Verzeichnis `/extensions/` werden beim Start der App installiert.\n\n## Promises\n\n`PROMISIFY(fn, [a], [b])` verpackt eine Funktion, die mit einem `callback(err, response)` endet, in eine `Promise`:\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\nDas `$` eines Schemas hat eine ähnliche Methode `$.promisify()`; siehe [Schemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm7g69r60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Operaciones y tareas","summary":"Lógica de negocio reutilizable con operaciones, operaciones encadenadas, tareas con pasos, comandos, extensiones y PROMISIFY().","markdown":"---\ntitle: Operaciones y tareas\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operaciones y tareas\n\n> Lógica de negocio reutilizable con operaciones, operaciones encadenadas, tareas con pasos, comandos, extensiones y PROMISIFY().\n\nLas operaciones y las tareas son pequeñas unidades de lógica de negocio que no están ligadas a una ruta. Las declaras una vez y las llamas desde controladores, esquemas, programadores u otras operaciones. Una **operación** es una función con un callback. Una **tarea** es un conjunto de pasos con nombre que saltan de uno a otro. Ambas reciben un objeto `$` que lleva el valor, los errores y, cuando lo hay, el controlador de la petición actual.\n\n## Declarar una operación\n\n`NEWOPERATION(name, fn)` registra una función. La función recibe `$` y el valor. Debe terminar con `$.callback()`, `$.success()` o `$.invalid()`.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nPon las operaciones en archivos del directorio `/operations/`. El framework las carga cuando arranca la aplicación.\n\n## Llamar a una operación\n\n`OPERATION(name, [value], callback, [options], [controller])` ejecuta una operación. El callback recibe `err` (un `ErrorBuilder` o `null`), la respuesta y el argumento `options`.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nDesde una ruta, pasa el controlador. Así `$.user`, `$.query`, `$.params`, `$.body` y las demás propiedades de la petición funcionan dentro de la operación, y el callback del controlador envía la respuesta:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nSin controlador, las propiedades de la petición como `$.user` o `$.query` son `null`.\n\n### Repetir, detener y vincular errores\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` acepta opciones adicionales:\n\n- `repeat {Number}` vuelve a ejecutar la operación cuando termina con un error, hasta este número de veces.\n- `stop {Boolean}` (por defecto `true`) detiene una cadena `RUN()` cuando esta operación falla.\n- `binderror {Boolean}` (por defecto `false`) guarda la salida de error como respuesta de esta operación en una cadena `RUN()`.\n- `filter {String}` es un esquema para la query string. `$.filter` devuelve entonces la query convertida.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Encadenar operaciones con RUN()\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` ejecuta varias operaciones una tras otra. `names` es un string separado por comas o un array. Todas las operaciones comparten el mismo `$.value`, así que una operación puede preparar datos para la siguiente.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nLa respuesta es un objeto con una clave por operación. Con `response_name`, el callback recibe solo la respuesta de esa operación:\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nDentro de una cadena, `$.response` contiene los resultados obtenidos hasta el momento, `$.meta.current` y `$.meta.prev` contienen los nombres de las operaciones, y `$.repeated` cuenta las repeticiones de la actual. Cuando una operación falla y su opción `stop` es `true` (por defecto), la cadena se detiene y el callback recibe el error. Un nombre de operación que no existe se omite.\n\n## Declarar una tarea\n\n`NEWTASK(name, fn)` declara un conjunto de pasos. `fn` recibe una función `push(step, fn)`. Cada paso recibe `$` y el valor. Un paso avanza con `$.next(step)` y termina la tarea con `$.end()`, `$.success()` o `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nPon las tareas en archivos del directorio `/tasks/`.\n\n## Ejecutar una tarea\n\n`TASK(name, step, callback, [options], [value])` crea la tarea y la inicia en `step`. También puedes escribir el nombre y el paso juntos como `'name/step'`:\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nPasa un controlador o el `$` de un esquema, una operación o una tarea como `options` para compartir su petición y sus errores. Cualquier otra cosa en `options` se usa como valor. `TASK()` devuelve la tarea, así que puedes añadir pasos con `$.push()` antes de que empiece.\n\n`$.next(a, b, ...)` ejecuta el primer paso que existe y termina la tarea cuando no existe ninguno. `$.next2(step)` y `$.done()` devuelven callbacks para funciones asíncronas:\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Comandos\n\nLos comandos son handlers con nombre que cualquier parte de la aplicación puede disparar. `NEWCOMMAND(name, fn)` añade un handler, y un mismo nombre puede tener varios handlers. `CMD(name, [a], [b], [c], [d])` los llama a todos.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nEl propio framework usa comandos como `clear_viewscache`, `clear_smtpcache` y `refresh_tms`.\n\n## Extensiones\n\n`NEWEXTENSION(code, [callback], [extend])` instala código en tiempo de ejecución desde un string o una URL. El código usa `exports` como un módulo: `exports.install(next)`, `exports.make()`, `exports.done()` y `exports.uninstall()` son opcionales. Los archivos del directorio `/extensions/` se instalan cuando arranca la aplicación.\n\n## Promesas\n\n`PROMISIFY(fn, [a], [b])` envuelve en una `Promise` una función que termina con un `callback(err, response)`:\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\nEl `$` de un esquema tiene un método similar, `$.promisify()`; consulta [Esquemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm7g69r60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Opérations et tâches","summary":"Logique métier réutilisable avec les opérations, les opérations enchaînées, les tâches à étapes, les commandes, les extensions et PROMISIFY().","markdown":"---\ntitle: \"Opérations et tâches\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Opérations et tâches\n\n> Logique métier réutilisable avec les opérations, les opérations enchaînées, les tâches à étapes, les commandes, les extensions et PROMISIFY().\n\nLes opérations et les tâches sont de petites unités de logique métier qui ne sont pas liées à une route. Tu les déclares une fois et tu les appelles depuis des contrôleurs, des schémas, des planificateurs ou d'autres opérations. Une **opération** est une fonction avec un callback. Une **tâche** est un ensemble nommé d'étapes qui passent de l'une à l'autre. Toutes deux reçoivent un objet `$` qui transporte la valeur, les erreurs et, s'il existe, le contrôleur de la requête en cours.\n\n## Déclarer une opération\n\n`NEWOPERATION(name, fn)` enregistre une fonction. La fonction reçoit `$` et la valeur. Elle doit se terminer par `$.callback()`, `$.success()` ou `$.invalid()`.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nPlace les opérations dans des fichiers du répertoire `/operations/`. Le framework les charge au démarrage de l'application.\n\n## Appeler une opération\n\n`OPERATION(name, [value], callback, [options], [controller])` exécute une opération. Le callback reçoit `err` (un `ErrorBuilder` ou `null`), la réponse et l'argument `options`.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nDepuis une route, passe le contrôleur. Ainsi `$.user`, `$.query`, `$.params`, `$.body` et les autres propriétés de la requête fonctionnent dans l'opération, et le callback du contrôleur envoie la réponse :\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nSans contrôleur, les propriétés de la requête comme `$.user` ou `$.query` valent `null`.\n\n### Répéter, arrêter et lier les erreurs\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` accepte des options supplémentaires :\n\n- `repeat {Number}` exécute à nouveau l'opération quand elle se termine par une erreur, jusqu'à ce nombre de fois.\n- `stop {Boolean}` (par défaut `true`) arrête une chaîne `RUN()` quand cette opération échoue.\n- `binderror {Boolean}` (par défaut `false`) stocke la sortie d'erreur comme réponse de cette opération dans une chaîne `RUN()`.\n- `filter {String}` est un schéma pour la query string. `$.filter` renvoie alors la query convertie.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Enchaîner des opérations avec RUN()\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` exécute plusieurs opérations l'une après l'autre. `names` est une chaîne séparée par des virgules ou un tableau. Toutes les opérations partagent la même `$.value` ; une opération peut donc préparer des données pour la suivante.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nLa réponse est un objet avec une clé par opération. Avec `response_name`, le callback ne reçoit que la réponse de cette opération :\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nDans une chaîne, `$.response` contient les résultats obtenus jusque-là, `$.meta.current` et `$.meta.prev` contiennent les noms des opérations, et `$.repeated` compte les répétitions de l'opération en cours. Quand une opération échoue et que son option `stop` vaut `true` (la valeur par défaut), la chaîne s'arrête et le callback reçoit l'erreur. Un nom d'opération qui n'existe pas est ignoré.\n\n## Déclarer une tâche\n\n`NEWTASK(name, fn)` déclare un ensemble d'étapes. `fn` reçoit une fonction `push(step, fn)`. Chaque étape reçoit `$` et la valeur. Une étape passe à la suite avec `$.next(step)` et termine la tâche avec `$.end()`, `$.success()` ou `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nPlace les tâches dans des fichiers du répertoire `/tasks/`.\n\n## Exécuter une tâche\n\n`TASK(name, step, callback, [options], [value])` crée la tâche et la démarre à `step`. Tu peux aussi écrire le nom et l'étape ensemble sous la forme `'name/step'` :\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nPasse un contrôleur ou le `$` d'un schéma, d'une opération ou d'une tâche comme `options` pour partager sa requête et ses erreurs. Toute autre valeur dans `options` est utilisée comme valeur. `TASK()` renvoie la tâche ; tu peux donc ajouter des étapes avec `$.push()` avant son démarrage.\n\n`$.next(a, b, ...)` exécute la première étape qui existe, et termine la tâche si aucune n'existe. `$.next2(step)` et `$.done()` renvoient des callbacks pour les fonctions asynchrones :\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Commandes\n\nLes commandes sont des handlers nommés que n'importe quelle partie de l'application peut déclencher. `NEWCOMMAND(name, fn)` ajoute un handler, et un même nom peut avoir plusieurs handlers. `CMD(name, [a], [b], [c], [d])` les appelle tous.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nLe framework lui-même utilise des commandes comme `clear_viewscache`, `clear_smtpcache` et `refresh_tms`.\n\n## Extensions\n\n`NEWEXTENSION(code, [callback], [extend])` installe du code à l'exécution à partir d'une chaîne ou d'une URL. Le code utilise `exports` comme un module : `exports.install(next)`, `exports.make()`, `exports.done()` et `exports.uninstall()` sont facultatifs. Les fichiers du répertoire `/extensions/` sont installés au démarrage de l'application.\n\n## Promesses\n\n`PROMISIFY(fn, [a], [b])` enveloppe dans une `Promise` une fonction qui se termine par un `callback(err, response)` :\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\nLe `$` d'un schéma possède une méthode similaire `$.promisify()` ; voir [Schémas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm7g69r60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Operazioni e task","summary":"Logica di business riutilizzabile con operazioni, operazioni concatenate, task con step, comandi, estensioni e PROMISIFY().","markdown":"---\ntitle: Operazioni e task\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operazioni e task\n\n> Logica di business riutilizzabile con operazioni, operazioni concatenate, task con step, comandi, estensioni e PROMISIFY().\n\nOperazioni e task sono piccole unità di logica di business non legate a una route. Le dichiari una volta e le chiami da controller, schemi, scheduler o altre operazioni. Un'**operazione** è una funzione con una callback. Un **task** è un insieme di step con nome che saltano dall'uno all'altro. Entrambi ricevono un oggetto `$` che porta il valore, gli errori e, quando c'è, il controller della richiesta corrente.\n\n## Dichiarare un'operazione\n\n`NEWOPERATION(name, fn)` registra una funzione. La funzione riceve `$` e il valore. Deve terminare con `$.callback()`, `$.success()` o `$.invalid()`.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nMetti le operazioni in file nella directory `/operations/`. Il framework le carica all'avvio dell'app.\n\n## Chiamare un'operazione\n\n`OPERATION(name, [value], callback, [options], [controller])` esegue un'operazione. La callback riceve `err` (un `ErrorBuilder` o `null`), la risposta e l'argomento `options`.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nDa una route, passa il controller. Così `$.user`, `$.query`, `$.params`, `$.body` e le altre proprietà della richiesta funzionano dentro l'operazione, e la callback del controller invia la risposta:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nSenza un controller, le proprietà della richiesta come `$.user` o `$.query` sono `null`.\n\n### Ripetere, fermare e collegare gli errori\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` accetta opzioni aggiuntive:\n\n- `repeat {Number}` esegue di nuovo l'operazione quando termina con un errore, fino a questo numero di volte.\n- `stop {Boolean}` (predefinito `true`) ferma una catena `RUN()` quando questa operazione fallisce.\n- `binderror {Boolean}` (predefinito `false`) salva l'output dell'errore come risposta di questa operazione in una catena `RUN()`.\n- `filter {String}` è uno schema per la query string. `$.filter` restituisce allora la query convertita.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Concatenare operazioni con RUN()\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` esegue più operazioni una dopo l'altra. `names` è una stringa separata da virgole o un array. Tutte le operazioni condividono lo stesso `$.value`, così un'operazione può preparare i dati per la successiva.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nLa risposta è un oggetto con una chiave per ogni operazione. Con `response_name`, la callback riceve solo la risposta di quell'operazione:\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nDentro una catena, `$.response` contiene i risultati fin qui, `$.meta.current` e `$.meta.prev` contengono i nomi delle operazioni e `$.repeated` conta le ripetizioni di quella corrente. Quando un'operazione fallisce e la sua opzione `stop` è `true` (il valore predefinito), la catena si ferma e la callback riceve l'errore. Un nome di operazione che non esiste viene saltato.\n\n## Dichiarare un task\n\n`NEWTASK(name, fn)` dichiara un insieme di step. `fn` riceve una funzione `push(step, fn)`. Ogni step riceve `$` e il valore. Uno step passa al successivo con `$.next(step)` e termina il task con `$.end()`, `$.success()` o `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nMetti i task in file nella directory `/tasks/`.\n\n## Eseguire un task\n\n`TASK(name, step, callback, [options], [value])` crea il task e lo avvia da `step`. Puoi anche scrivere il nome e lo step insieme come `'name/step'`:\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nPassa un controller o il `$` di uno schema, di un'operazione o di un task come `options` per condividerne la richiesta e gli errori. Qualsiasi altra cosa in `options` viene usata come valore. `TASK()` restituisce il task, così puoi aggiungere step con `$.push()` prima che parta.\n\n`$.next(a, b, ...)` esegue il primo step che esiste e termina il task quando non ne esiste nessuno. `$.next2(step)` e `$.done()` restituiscono callback per le funzioni asincrone:\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Comandi\n\nI comandi sono handler con nome che qualsiasi parte dell'app può attivare. `NEWCOMMAND(name, fn)` aggiunge un handler, e lo stesso nome può avere più handler. `CMD(name, [a], [b], [c], [d])` li chiama tutti.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nIl framework stesso usa comandi come `clear_viewscache`, `clear_smtpcache` e `refresh_tms`.\n\n## Estensioni\n\n`NEWEXTENSION(code, [callback], [extend])` installa codice a runtime da una stringa o da un URL. Il codice usa `exports` come un modulo: `exports.install(next)`, `exports.make()`, `exports.done()` ed `exports.uninstall()` sono facoltativi. I file nella directory `/extensions/` vengono installati all'avvio dell'app.\n\n## Promise\n\n`PROMISIFY(fn, [a], [b])` avvolge in una `Promise` una funzione che termina con una `callback(err, response)`:\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\nIl `$` di uno schema ha un metodo simile, `$.promisify()`; vedi [Schemi](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm7g69r60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Operácie a úlohy","summary":"Opakovane použiteľná biznis logika s operáciami, reťazenými operáciami, úlohami s krokmi, príkazmi, rozšíreniami a PROMISIFY().","markdown":"---\ntitle: \"Operácie a úlohy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operácie a úlohy\n\n> Opakovane použiteľná biznis logika s operáciami, reťazenými operáciami, úlohami s krokmi, príkazmi, rozšíreniami a PROMISIFY().\n\nOperácie a úlohy sú malé jednotky biznis logiky, ktoré nie sú viazané na trasu. Deklaruješ ich raz a voláš ich z kontrolérov, schém, plánovačov alebo iných operácií. **Operácia** je jedna funkcia s callbackom. **Úloha** je pomenovaná sada krokov, ktoré preskakujú z jedného na druhý. Obe dostávajú objekt `$`, ktorý nesie hodnotu, chyby a, ak existuje, kontrolér aktuálnej požiadavky.\n\n## Deklarácia operácie\n\n`NEWOPERATION(name, fn)` zaregistruje funkciu. Funkcia dostane `$` a hodnotu. Musí skončiť cez `$.callback()`, `$.success()` alebo `$.invalid()`.\n\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nOperácie daj do súborov v adresári `/operations/`. Framework ich načíta pri štarte aplikácie.\n\n## Volanie operácie\n\n`OPERATION(name, [value], callback, [options], [controller])` spustí jednu operáciu. Callback dostane `err` (`ErrorBuilder` alebo `null`), odpoveď a argument `options`.\n\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nZ trasy odovzdaj kontrolér. Potom vnútri operácie fungujú `$.user`, `$.query`, `$.params`, `$.body` a ďalšie vlastnosti požiadavky a callback kontroléra pošle odpoveď:\n\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\nBez kontroléra sú vlastnosti požiadavky ako `$.user` alebo `$.query` `null`.\n\n### Opakovanie, zastavenie a väzba chýb\n\n`NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])` berie ďalšie voľby:\n\n- `repeat {Number}` spustí operáciu znova, keď skončí chybou, najviac toľkokrát.\n- `stop {Boolean}` (predvolene `true`) zastaví reťaz `RUN()`, keď táto operácia zlyhá.\n- `binderror {Boolean}` (predvolene `false`) uloží chybový výstup ako odpoveď tejto operácie v reťazi `RUN()`.\n- `filter {String}` je schéma pre query string. `$.filter` potom vráti prevedený query.\n\n```js\nNEWOPERATION('newsletter', function($) {\n\tMAIL($.value.email, 'Newsletter', '=?/mails/newsletter', $.value, $.done());\n}, 3);\n```\n\n## Reťazenie operácií cez RUN()\n\n`RUN(names, [value], callback, [options], [controller], [response_name])` spustí niekoľko operácií jednu po druhej. `names` je reťazec oddelený čiarkami alebo pole. Všetky operácie zdieľajú ten istý `$.value`, takže jedna operácia môže pripraviť dáta pre ďalšiu.\n\n```js\nNEWOPERATION('check', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email');\n\t\treturn;\n\t}\n\t$.value.email = $.value.email.toLowerCase();\n\t$.success();\n});\n\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done());\n});\n\nRUN('check, save', { email: 'Peter@Example.com' }, function(err, response) {\n\t// response.check = { success: true }\n\t// response.save = { success: true }\n\tconsole.log(err, response);\n});\n```\n\nOdpoveďou je objekt s jedným kľúčom pre každú operáciu. S `response_name` dostane callback len odpoveď tejto operácie:\n\n```js\nRUN('check, save', model, function(err, response) {\n\t// response = { success: true } from \"save\"\n}, 'save');\n```\n\nVnútri reťaze drží `$.response` doterajšie výsledky, `$.meta.current` a `$.meta.prev` držia názvy operácií a `$.repeated` počíta opakovania aktuálnej operácie. Keď operácia zlyhá a jej voľba `stop` je `true` (predvolené), reťaz sa zastaví a callback dostane chybu. Názov operácie, ktorá neexistuje, sa preskočí.\n\n## Deklarácia úlohy\n\n`NEWTASK(name, fn)` deklaruje sadu krokov. `fn` dostane funkciu `push(step, fn)`. Každý krok dostane `$` a hodnotu. Krok pokračuje cez `$.next(step)` a úlohu ukončí cez `$.end()`, `$.success()` alebo `$.invalid()`.\n\n```js\nNEWTASK('order', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.items || !value.items.length) {\n\t\t\t$.invalid('items');\n\t\t\treturn;\n\t\t}\n\t\t$.next('price');\n\t});\n\n\tpush('price', function($, value) {\n\t\tvalue.price = 0;\n\t\tfor (var item of value.items)\n\t\t\tvalue.price += item.price * item.count;\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('orders').insert(value).callback($.done(true));\n\t});\n\n});\n```\n\nÚlohy daj do súborov v adresári `/tasks/`.\n\n## Spustenie úlohy\n\n`TASK(name, step, callback, [options], [value])` vytvorí úlohu a spustí ju na kroku `step`. Názov a krok môžeš napísať aj spolu ako `'name/step'`:\n\n```js\nTASK('order', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { items: [{ price: 10, count: 2 }] });\n\n// The same with \"name/step\"\nTASK('order/check', function(err, response) {\n\tconsole.log(err, response);\n}, $, $.value);\n```\n\nOdovzdaj kontrolér alebo `$` schémy, operácie či úlohy ako `options`, aby sa zdieľala jeho požiadavka a chyby. Čokoľvek iné v `options` sa použije ako hodnota. `TASK()` vráti úlohu, takže pred jej štartom môžeš pridať kroky cez `$.push()`.\n\n`$.next(a, b, ...)` spustí prvý krok, ktorý existuje, a keď neexistuje žiadny, úlohu ukončí. `$.next2(step)` a `$.done()` vracajú callbacky pre asynchrónne funkcie:\n\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.next2('send'));\n});\n```\n\n## Príkazy\n\nPríkazy sú pomenované handlery, ktoré môže spustiť ktorákoľvek časť aplikácie. `NEWCOMMAND(name, fn)` pridá handler a ten istý názov môže mať viac handlerov. `CMD(name, [a], [b], [c], [d])` zavolá všetky.\n\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n\nCMD('clear_prices', 'books');\n```\n\nSamotný framework používa príkazy ako `clear_viewscache`, `clear_smtpcache` a `refresh_tms`.\n\n## Rozšírenia\n\n`NEWEXTENSION(code, [callback], [extend])` nainštaluje kód za behu z reťazca alebo URL. Kód používa `exports` ako modul: `exports.install(next)`, `exports.make()`, `exports.done()` a `exports.uninstall()` sú voliteľné. Súbory v adresári `/extensions/` sa nainštalujú pri štarte aplikácie.\n\n## Promises\n\n`PROMISIFY(fn, [a], [b])` zabalí funkciu, ktorá končí `callback(err, response)`, do `Promise`:\n\n```js\nvar count = await PROMISIFY(function(callback) {\n\tNOSQL('users').count().callback(callback);\n});\n```\n\n`$` schémy má podobnú metódu `$.promisify()`; pozri [Schémy](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Utilities","summary":"Global helpers and the U object: identifiers, object copies, paths, files, queues and text functions.","markdown":"---\ntitle: Utilities\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilities\n\n> Global helpers and the U object: identifiers, object copies, paths, files, queues and text functions.\n\nTotal.js puts a set of helpers into the global scope. You do not `require()` them: they are available in controllers, schemas, definitions, modules and plugins. Most of them live in the object `U` (the file `utils.js`), the rest are global functions and objects. The full list is in the reference of [Utilities](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` and `utils` are the same object. `Total` is an alias of the framework instance `F`.\n\n## Identifiers\n\n| Function | Result |\n| --- | --- |\n| `UID([type])` | A short time-based ID, for example `24j0y001xn51d` |\n| `UID16([type])` | The same with the time in base 16 |\n| `GUID()` | A UUID-like string `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Random lowercase letters and digits |\n| `U.random_text(length)` | Random letters and digits |\n| `U.random_number(length)` | Random digits as a string, never starting with `0` |\n| `U.random([max], [min])` | A random integer (`0` to `100000` by default) |\n\n`UID()` is the usual choice for primary keys: it is short, unique within the running instance and it sorts by time. The `type` argument keeps a separate counter for each collection. `CONF.default_uid` set to `r` switches `UID()` to random IDs.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nWhen an ID goes to the client and comes back in a URL, sign it with `U.encrypt_uid()`. `U.decrypt_uid()` returns `null` when somebody changed it. The value is not hidden, only protected.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Objects\n\n| Function | What it does |\n| --- | --- |\n| `CLONE(obj, [skip])` | A deep copy; `skip` is `{ key: 1 }` of keys to leave out |\n| `COPY(source, [target])` | Copies all keys of `source` to `target` |\n| `U.copy(source, [target])` | Copies only keys that `target` already has |\n| `U.extend(target, source, [rewrite])` | Adds keys; with `rewrite = false` it fills only missing values |\n| `U.reduce(obj, keys, [reverse])` | Keeps the listed keys, or removes them with `reverse` |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Read and write by a path like `address.city` |\n| `U.trim(obj, [clean])` | Trims all strings; `clean` turns empty strings into `undefined` |\n| `DIFFARR(key, db, form)` | Compares two lists: `{ add, upd, rem }` |\n\n`U.copy()` is useful when you update a stored record from a form: only the fields the record already has are written.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` tells you what to insert, update and remove when a user saves an edited list.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## Shared state\n\nThe framework creates empty global objects for your app: `MAIN`, `REPO` and `FUNC`. It never writes into them, so they are a safe place for shared data and helpers. `TEMP` is cleared regularly (every 10 minutes by default). `NOW` is a `Date` the framework refreshes about every minute; use it for timestamps where a precision of a minute is enough. `EMPTYOBJECT` and `EMPTYARRAY` are frozen defaults and `NOOP` is an empty callback.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nLoaded modules are in `MODS`, and `MODULE(name)` returns one of them or `null`.\n\n## Paths and files\n\n`PATH` returns paths to the directories of the app. Each directory comes from its `CONF.directory_*` option. `PATH.temp()`, `PATH.databases()` and `PATH.logs()` also create the directory when it is missing.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` joins paths relative to the root of the app, `U.join()` joins parts of a URL path, and `U.path()` adds a trailing slash. `U.getExtension()`, `U.getName()` and `U.getContentType()` work with file names. `U.setContentType()` adds a new extension to the table the framework uses for static files.\n\n`U.ls()` lists a directory with all its subdirectories. Without a callback it returns a Promise. The `unified` argument gives paths with `/` on Windows. `U.ls2()` adds the `fs.Stats` of each file.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` appends a line with a date to `/logs/{name}.log`.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Asynchronous helpers\n\n`U.queue(name, max, fn)` runs at most `max` functions of one queue at the same time; each function calls `next()` when it is done. `WAIT(validator, callback, [timeout], [interval])` checks a condition until it is true or the time runs out. `PROMISIFY(fn, [a], [b], [c])` turns a function with a `callback(err, response)` into a Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Text and data\n\n| Function | Result |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | HTML entities |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | A numeric hash, or `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Unique words for a search index |\n| `U.parseXML(xml)` | A flat object with dot paths as keys |\n| `U.parseInt(value, [def])` | A number from any value (also `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | A URL with a query string |\n| `U.sortcomparer('price_desc,name')` | A compare function for `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | Kilometres between two GPS points |\n| `U.minify_css/js/html(value)` | Code minified by the built-in compilers |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nThe methods of `String`, `Number`, `Date` and `Array` that the framework adds are described on their own page.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Hilfsfunktionen","summary":"Globale Helfer und das Objekt U: Bezeichner, Objektkopien, Pfade, Dateien, Warteschlangen und Textfunktionen.","markdown":"---\ntitle: Hilfsfunktionen\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Hilfsfunktionen\n\n> Globale Helfer und das Objekt U: Bezeichner, Objektkopien, Pfade, Dateien, Warteschlangen und Textfunktionen.\n\nTotal.js stellt eine Reihe von Helfern in den globalen Gültigkeitsbereich. Du lädst sie nicht mit `require()`: Sie sind in Controllern, Schemas, Definitionen, Modulen und Plugins verfügbar. Die meisten befinden sich im Objekt `U` (der Datei `utils.js`), der Rest sind globale Funktionen und Objekte. Die vollständige Liste steht in der Referenz zu [Hilfsfunktionen](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` und `utils` sind dasselbe Objekt. `Total` ist ein Alias der Framework-Instanz `F`.\n\n## Bezeichner\n\n| Funktion | Ergebnis |\n| --- | --- |\n| `UID([type])` | Eine kurze zeitbasierte ID, zum Beispiel `24j0y001xn51d` |\n| `UID16([type])` | Dasselbe mit der Zeit zur Basis 16 |\n| `GUID()` | Ein UUID-ähnlicher String `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Zufällige Kleinbuchstaben und Ziffern |\n| `U.random_text(length)` | Zufällige Buchstaben und Ziffern |\n| `U.random_number(length)` | Zufällige Ziffern als String, nie mit `0` am Anfang |\n| `U.random([max], [min])` | Eine zufällige Ganzzahl (standardmäßig `0` bis `100000`) |\n\n`UID()` ist die übliche Wahl für Primärschlüssel: Sie ist kurz, innerhalb der laufenden Instanz eindeutig und nach Zeit sortierbar. Das Argument `type` führt für jede Collection einen eigenen Zähler. Ist `CONF.default_uid` auf `r` gesetzt, erzeugt `UID()` zufällige IDs.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nWenn eine ID an den Client geht und in einer URL zurückkommt, signiere sie mit `U.encrypt_uid()`. `U.decrypt_uid()` gibt `null` zurück, wenn jemand sie verändert hat. Der Wert ist nicht versteckt, nur geschützt.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Objekte\n\n| Funktion | Was sie tut |\n| --- | --- |\n| `CLONE(obj, [skip])` | Eine tiefe Kopie; `skip` ist `{ key: 1 }` mit Schlüsseln, die ausgelassen werden |\n| `COPY(source, [target])` | Kopiert alle Schlüssel von `source` nach `target` |\n| `U.copy(source, [target])` | Kopiert nur Schlüssel, die `target` bereits hat |\n| `U.extend(target, source, [rewrite])` | Fügt Schlüssel hinzu; mit `rewrite = false` füllt es nur fehlende Werte |\n| `U.reduce(obj, keys, [reverse])` | Behält die aufgeführten Schlüssel oder entfernt sie mit `reverse` |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Lesen und Schreiben über einen Pfad wie `address.city` |\n| `U.trim(obj, [clean])` | Kürzt alle Strings; `clean` macht leere Strings zu `undefined` |\n| `DIFFARR(key, db, form)` | Vergleicht zwei Listen: `{ add, upd, rem }` |\n\n`U.copy()` ist nützlich, wenn du einen gespeicherten Datensatz aus einem Formular aktualisierst: Nur die Felder, die der Datensatz bereits hat, werden geschrieben.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` sagt dir, was du einfügen, aktualisieren und entfernen musst, wenn ein Benutzer eine bearbeitete Liste speichert.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## Gemeinsamer Zustand\n\nDas Framework erstellt leere globale Objekte für deine App: `MAIN`, `REPO` und `FUNC`. Es schreibt nie hinein, daher sind sie ein sicherer Ort für gemeinsame Daten und Helfer. `TEMP` wird regelmäßig geleert (standardmäßig alle 10 Minuten). `NOW` ist ein `Date`, das das Framework etwa jede Minute aktualisiert; verwende es für Zeitstempel, bei denen eine Genauigkeit von einer Minute reicht. `EMPTYOBJECT` und `EMPTYARRAY` sind eingefrorene Standardwerte, und `NOOP` ist ein leerer Callback.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nGeladene Module befinden sich in `MODS`, und `MODULE(name)` gibt eines davon oder `null` zurück.\n\n## Pfade und Dateien\n\n`PATH` gibt Pfade zu den Verzeichnissen der App zurück. Jedes Verzeichnis stammt aus seiner Option `CONF.directory_*`. `PATH.temp()`, `PATH.databases()` und `PATH.logs()` erstellen das Verzeichnis außerdem, wenn es fehlt.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` verbindet Pfade relativ zum Stammverzeichnis der App, `U.join()` verbindet Teile eines URL-Pfads, und `U.path()` fügt einen abschließenden Schrägstrich hinzu. `U.getExtension()`, `U.getName()` und `U.getContentType()` arbeiten mit Dateinamen. `U.setContentType()` fügt eine neue Erweiterung zu der Tabelle hinzu, die das Framework für statische Dateien verwendet.\n\n`U.ls()` listet ein Verzeichnis mit allen Unterverzeichnissen auf. Ohne Callback gibt es eine Promise zurück. Das Argument `unified` liefert unter Windows Pfade mit `/`. `U.ls2()` fügt die `fs.Stats` jeder Datei hinzu.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` hängt eine Zeile mit Datum an `/logs/{name}.log` an.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Asynchrone Helfer\n\n`U.queue(name, max, fn)` führt höchstens `max` Funktionen einer Warteschlange gleichzeitig aus; jede Funktion ruft `next()` auf, wenn sie fertig ist. `WAIT(validator, callback, [timeout], [interval])` prüft eine Bedingung, bis sie wahr ist oder die Zeit abläuft. `PROMISIFY(fn, [a], [b], [c])` macht aus einer Funktion mit `callback(err, response)` eine Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Text und Daten\n\n| Funktion | Ergebnis |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | HTML-Entities |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | Ein numerischer Hash oder `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Eindeutige Wörter für einen Suchindex |\n| `U.parseXML(xml)` | Ein flaches Objekt mit Punkt-Pfaden als Schlüsseln |\n| `U.parseInt(value, [def])` | Eine Zahl aus einem beliebigen Wert (auch `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | Eine URL mit Query-String |\n| `U.sortcomparer('price_desc,name')` | Eine Vergleichsfunktion für `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | Kilometer zwischen zwei GPS-Punkten |\n| `U.minify_css/js/html(value)` | Code, der von den eingebauten Compilern minifiziert wurde |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nDie Methoden von `String`, `Number`, `Date` und `Array`, die das Framework hinzufügt, sind auf einer eigenen Seite beschrieben.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Utilidades","summary":"Helpers globales y el objeto U: identificadores, copias de objetos, rutas, archivos, colas y funciones de texto.","markdown":"---\ntitle: Utilidades\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilidades\n\n> Helpers globales y el objeto U: identificadores, copias de objetos, rutas, archivos, colas y funciones de texto.\n\nTotal.js pone un conjunto de helpers en el ámbito global. No les haces `require()`: están disponibles en controladores, esquemas, definiciones, módulos y plugins. La mayoría viven en el objeto `U` (el archivo `utils.js`); el resto son funciones y objetos globales. La lista completa está en la referencia de [Utilidades](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` y `utils` son el mismo objeto. `Total` es un alias de la instancia del framework `F`.\n\n## Identificadores\n\n| Función | Resultado |\n| --- | --- |\n| `UID([type])` | Un ID corto basado en el tiempo, por ejemplo `24j0y001xn51d` |\n| `UID16([type])` | Lo mismo con el tiempo en base 16 |\n| `GUID()` | Un string similar a un UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Letras minúsculas y dígitos aleatorios |\n| `U.random_text(length)` | Letras y dígitos aleatorios |\n| `U.random_number(length)` | Dígitos aleatorios como string, que nunca empiezan por `0` |\n| `U.random([max], [min])` | Un entero aleatorio (de `0` a `100000` por defecto) |\n\n`UID()` es la opción habitual para claves primarias: es corto, único dentro de la instancia en ejecución y se ordena por tiempo. El argumento `type` mantiene un contador separado para cada colección. `CONF.default_uid` con valor `r` cambia `UID()` a IDs aleatorios.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nCuando un ID va al cliente y vuelve en una URL, fírmalo con `U.encrypt_uid()`. `U.decrypt_uid()` devuelve `null` cuando alguien lo ha cambiado. El valor no se oculta, solo se protege.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Objetos\n\n| Función | Qué hace |\n| --- | --- |\n| `CLONE(obj, [skip])` | Una copia profunda; `skip` es `{ key: 1 }` con las claves que se omiten |\n| `COPY(source, [target])` | Copia todas las claves de `source` a `target` |\n| `U.copy(source, [target])` | Copia solo las claves que `target` ya tiene |\n| `U.extend(target, source, [rewrite])` | Añade claves; con `rewrite = false` solo rellena los valores que faltan |\n| `U.reduce(obj, keys, [reverse])` | Conserva las claves listadas, o las elimina con `reverse` |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Lee y escribe por una ruta como `address.city` |\n| `U.trim(obj, [clean])` | Recorta todos los strings; `clean` convierte los strings vacíos en `undefined` |\n| `DIFFARR(key, db, form)` | Compara dos listas: `{ add, upd, rem }` |\n\n`U.copy()` es útil cuando actualizas un registro guardado a partir de un formulario: solo se escriben los campos que el registro ya tiene.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` te dice qué insertar, actualizar y eliminar cuando un usuario guarda una lista editada.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## Estado compartido\n\nEl framework crea objetos globales vacíos para tu aplicación: `MAIN`, `REPO` y `FUNC`. Nunca escribe en ellos, así que son un lugar seguro para datos y helpers compartidos. `TEMP` se vacía periódicamente (cada 10 minutos por defecto). `NOW` es un `Date` que el framework actualiza aproximadamente cada minuto; úsalo para timestamps en los que basta con una precisión de un minuto. `EMPTYOBJECT` y `EMPTYARRAY` son valores por defecto congelados y `NOOP` es un callback vacío.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nLos módulos cargados están en `MODS`, y `MODULE(name)` devuelve uno de ellos o `null`.\n\n## Rutas y archivos\n\n`PATH` devuelve rutas a los directorios de la aplicación. Cada directorio procede de su opción `CONF.directory_*`. `PATH.temp()`, `PATH.databases()` y `PATH.logs()` además crean el directorio cuando falta.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` une rutas relativas a la raíz de la aplicación, `U.join()` une partes de una ruta de URL y `U.path()` añade una barra final. `U.getExtension()`, `U.getName()` y `U.getContentType()` trabajan con nombres de archivo. `U.setContentType()` añade una nueva extensión a la tabla que el framework usa para los archivos estáticos.\n\n`U.ls()` lista un directorio con todos sus subdirectorios. Sin callback devuelve una Promise. El argumento `unified` da rutas con `/` en Windows. `U.ls2()` añade el `fs.Stats` de cada archivo.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` añade una línea con fecha a `/logs/{name}.log`.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Helpers asíncronos\n\n`U.queue(name, max, fn)` ejecuta como máximo `max` funciones de una cola al mismo tiempo; cada función llama a `next()` cuando termina. `WAIT(validator, callback, [timeout], [interval])` comprueba una condición hasta que es verdadera o se acaba el tiempo. `PROMISIFY(fn, [a], [b], [c])` convierte una función con `callback(err, response)` en una Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Texto y datos\n\n| Función | Resultado |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | Entidades HTML |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | Un hash numérico, o `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Palabras únicas para un índice de búsqueda |\n| `U.parseXML(xml)` | Un objeto plano con rutas con puntos como claves |\n| `U.parseInt(value, [def])` | Un número a partir de cualquier valor (también `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | Una URL con query string |\n| `U.sortcomparer('price_desc,name')` | Una función de comparación para `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | Kilómetros entre dos puntos GPS |\n| `U.minify_css/js/html(value)` | Código minificado por los compiladores integrados |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nLos métodos de `String`, `Number`, `Date` y `Array` que añade el framework se describen en su propia página.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Utilitaires","summary":"Helpers globaux et objet U : identifiants, copies d'objets, chemins, fichiers, files d'attente et fonctions de texte.","markdown":"---\ntitle: Utilitaires\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilitaires\n\n> Helpers globaux et objet U : identifiants, copies d'objets, chemins, fichiers, files d'attente et fonctions de texte.\n\nTotal.js place un ensemble de helpers dans la portée globale. Tu ne fais pas de `require()` : ils sont disponibles dans les contrôleurs, les schémas, les définitions, les modules et les plugins. La plupart se trouvent dans l'objet `U` (le fichier `utils.js`), les autres sont des fonctions et des objets globaux. La liste complète se trouve dans la référence des [Utilitaires](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` et `utils` sont le même objet. `Total` est un alias de l'instance du framework `F`.\n\n## Identifiants\n\n| Fonction | Résultat |\n| --- | --- |\n| `UID([type])` | Un ID court basé sur le temps, par exemple `24j0y001xn51d` |\n| `UID16([type])` | Le même, avec le temps en base 16 |\n| `GUID()` | Une chaîne de type UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Des lettres minuscules et des chiffres aléatoires |\n| `U.random_text(length)` | Des lettres et des chiffres aléatoires |\n| `U.random_number(length)` | Des chiffres aléatoires sous forme de chaîne, ne commençant jamais par `0` |\n| `U.random([max], [min])` | Un entier aléatoire (de `0` à `100000` par défaut) |\n\n`UID()` est le choix habituel pour les clés primaires : il est court, unique au sein de l'instance en cours d'exécution et se trie par date. L'argument `type` conserve un compteur séparé pour chaque collection. `CONF.default_uid` défini à `r` fait passer `UID()` à des ID aléatoires.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nQuand un ID part vers le client et revient dans une URL, signe-le avec `U.encrypt_uid()`. `U.decrypt_uid()` renvoie `null` si quelqu'un l'a modifié. La valeur n'est pas cachée, seulement protégée.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Objets\n\n| Fonction | Ce qu'elle fait |\n| --- | --- |\n| `CLONE(obj, [skip])` | Une copie profonde ; `skip` est un `{ key: 1 }` des clés à exclure |\n| `COPY(source, [target])` | Copie toutes les clés de `source` vers `target` |\n| `U.copy(source, [target])` | Copie uniquement les clés que `target` possède déjà |\n| `U.extend(target, source, [rewrite])` | Ajoute des clés ; avec `rewrite = false`, ne remplit que les valeurs manquantes |\n| `U.reduce(obj, keys, [reverse])` | Conserve les clés listées, ou les supprime avec `reverse` |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Lecture et écriture par un chemin comme `address.city` |\n| `U.trim(obj, [clean])` | Supprime les espaces de toutes les chaînes ; `clean` transforme les chaînes vides en `undefined` |\n| `DIFFARR(key, db, form)` | Compare deux listes : `{ add, upd, rem }` |\n\n`U.copy()` est utile quand tu mets à jour un enregistrement stocké depuis un formulaire : seuls les champs que l'enregistrement possède déjà sont écrits.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` t'indique ce qu'il faut insérer, mettre à jour et supprimer quand un utilisateur enregistre une liste modifiée.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## État partagé\n\nLe framework crée des objets globaux vides pour ton application : `MAIN`, `REPO` et `FUNC`. Il n'y écrit jamais ; ce sont donc des emplacements sûrs pour les données et les helpers partagés. `TEMP` est vidé régulièrement (toutes les 10 minutes par défaut). `NOW` est une `Date` que le framework actualise environ chaque minute ; utilise-la pour les timestamps quand une précision à la minute suffit. `EMPTYOBJECT` et `EMPTYARRAY` sont des valeurs par défaut gelées et `NOOP` est un callback vide.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nLes modules chargés se trouvent dans `MODS`, et `MODULE(name)` renvoie l'un d'eux ou `null`.\n\n## Chemins et fichiers\n\n`PATH` renvoie les chemins des répertoires de l'application. Chaque répertoire provient de son option `CONF.directory_*`. `PATH.temp()`, `PATH.databases()` et `PATH.logs()` créent aussi le répertoire s'il n'existe pas.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` joint des chemins relatifs à la racine de l'application, `U.join()` joint des parties d'un chemin d'URL, et `U.path()` ajoute une barre oblique finale. `U.getExtension()`, `U.getName()` et `U.getContentType()` travaillent sur les noms de fichiers. `U.setContentType()` ajoute une nouvelle extension à la table que le framework utilise pour les fichiers statiques.\n\n`U.ls()` liste un répertoire avec tous ses sous-répertoires. Sans callback, il renvoie une Promise. L'argument `unified` donne des chemins avec `/` sous Windows. `U.ls2()` ajoute le `fs.Stats` de chaque fichier.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` ajoute une ligne datée à `/logs/{name}.log`.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Helpers asynchrones\n\n`U.queue(name, max, fn)` exécute au plus `max` fonctions d'une même file d'attente en même temps ; chaque fonction appelle `next()` quand elle a terminé. `WAIT(validator, callback, [timeout], [interval])` vérifie une condition jusqu'à ce qu'elle soit vraie ou que le temps soit écoulé. `PROMISIFY(fn, [a], [b], [c])` transforme une fonction avec un `callback(err, response)` en Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Texte et données\n\n| Fonction | Résultat |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | Entités HTML |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | Un hash numérique, ou `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Des mots uniques pour un index de recherche |\n| `U.parseXML(xml)` | Un objet plat avec des chemins à points comme clés |\n| `U.parseInt(value, [def])` | Un nombre à partir de n'importe quelle valeur (aussi `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | Une URL avec une query string |\n| `U.sortcomparer('price_desc,name')` | Une fonction de comparaison pour `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | La distance en kilomètres entre deux points GPS |\n| `U.minify_css/js/html(value)` | Du code minifié par les compilateurs intégrés |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nLes méthodes de `String`, `Number`, `Date` et `Array` que le framework ajoute sont décrites sur leur propre page.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Utilità","summary":"Helper globali e l'oggetto U: identificatori, copie di oggetti, percorsi, file, code e funzioni per il testo.","markdown":"---\ntitle: \"Utilità\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilità\n\n> Helper globali e l'oggetto U: identificatori, copie di oggetti, percorsi, file, code e funzioni per il testo.\n\nTotal.js mette un insieme di helper nello scope globale. Non devi farne il `require()`: sono disponibili in controller, schemi, definizioni, moduli e plugin. La maggior parte si trova nell'oggetto `U` (il file `utils.js`), il resto sono funzioni e oggetti globali. L'elenco completo è nel riferimento di [Utilità](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` e `utils` sono lo stesso oggetto. `Total` è un alias dell'istanza del framework `F`.\n\n## Identificatori\n\n| Funzione | Risultato |\n| --- | --- |\n| `UID([type])` | Un ID breve basato sul tempo, per esempio `24j0y001xn51d` |\n| `UID16([type])` | Lo stesso con il tempo in base 16 |\n| `GUID()` | Una stringa simile a un UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Lettere minuscole e cifre casuali |\n| `U.random_text(length)` | Lettere e cifre casuali |\n| `U.random_number(length)` | Cifre casuali come stringa, mai con `0` iniziale |\n| `U.random([max], [min])` | Un intero casuale (da `0` a `100000` per impostazione predefinita) |\n\n`UID()` è la scelta abituale per le chiavi primarie: è breve, unico all'interno dell'istanza in esecuzione e si ordina per tempo. L'argomento `type` mantiene un contatore separato per ogni collezione. `CONF.default_uid` impostato a `r` fa passare `UID()` a ID casuali.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nQuando un ID va al client e torna indietro in un URL, firmalo con `U.encrypt_uid()`. `U.decrypt_uid()` restituisce `null` quando qualcuno lo ha modificato. Il valore non è nascosto, solo protetto.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Oggetti\n\n| Funzione | Cosa fa |\n| --- | --- |\n| `CLONE(obj, [skip])` | Una copia profonda; `skip` è `{ key: 1 }` delle chiavi da escludere |\n| `COPY(source, [target])` | Copia tutte le chiavi di `source` in `target` |\n| `U.copy(source, [target])` | Copia solo le chiavi che `target` ha già |\n| `U.extend(target, source, [rewrite])` | Aggiunge chiavi; con `rewrite = false` riempie solo i valori mancanti |\n| `U.reduce(obj, keys, [reverse])` | Mantiene le chiavi elencate, oppure le rimuove con `reverse` |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Lettura e scrittura tramite un percorso come `address.city` |\n| `U.trim(obj, [clean])` | Applica il trim a tutte le stringhe; `clean` trasforma le stringhe vuote in `undefined` |\n| `DIFFARR(key, db, form)` | Confronta due elenchi: `{ add, upd, rem }` |\n\n`U.copy()` è utile quando aggiorni un record salvato a partire da un form: vengono scritti solo i campi che il record ha già.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` ti dice cosa inserire, aggiornare e rimuovere quando un utente salva un elenco modificato.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## Stato condiviso\n\nIl framework crea oggetti globali vuoti per la tua app: `MAIN`, `REPO` e `FUNC`. Non vi scrive mai, quindi sono un posto sicuro per dati e helper condivisi. `TEMP` viene svuotato regolarmente (ogni 10 minuti per impostazione predefinita). `NOW` è un `Date` che il framework aggiorna circa ogni minuto; usalo per i timestamp quando basta la precisione di un minuto. `EMPTYOBJECT` ed `EMPTYARRAY` sono valori predefiniti congelati e `NOOP` è una callback vuota.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nI moduli caricati sono in `MODS`, e `MODULE(name)` ne restituisce uno oppure `null`.\n\n## Percorsi e file\n\n`PATH` restituisce i percorsi delle directory dell'app. Ogni directory deriva dalla sua opzione `CONF.directory_*`. `PATH.temp()`, `PATH.databases()` e `PATH.logs()` creano anche la directory quando manca.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` unisce percorsi relativi alla root dell'app, `U.join()` unisce parti del percorso di un URL e `U.path()` aggiunge una barra finale. `U.getExtension()`, `U.getName()` e `U.getContentType()` lavorano con i nomi dei file. `U.setContentType()` aggiunge una nuova estensione alla tabella che il framework usa per i file statici.\n\n`U.ls()` elenca una directory con tutte le sue sottodirectory. Senza callback restituisce una Promise. L'argomento `unified` fornisce percorsi con `/` su Windows. `U.ls2()` aggiunge i `fs.Stats` di ogni file.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` accoda una riga con una data a `/logs/{name}.log`.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Helper asincroni\n\n`U.queue(name, max, fn)` esegue al massimo `max` funzioni di una coda contemporaneamente; ogni funzione chiama `next()` quando ha finito. `WAIT(validator, callback, [timeout], [interval])` controlla una condizione finché non è vera o finché non scade il tempo. `PROMISIFY(fn, [a], [b], [c])` trasforma una funzione con una `callback(err, response)` in una Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Testo e dati\n\n| Funzione | Risultato |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | Entità HTML |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | Un hash numerico, oppure `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Parole uniche per un indice di ricerca |\n| `U.parseXML(xml)` | Un oggetto piatto con percorsi puntati come chiavi |\n| `U.parseInt(value, [def])` | Un numero da qualsiasi valore (anche `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | Un URL con una query string |\n| `U.sortcomparer('price_desc,name')` | Una funzione di confronto per `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | Chilometri tra due punti GPS |\n| `U.minify_css/js/html(value)` | Codice minificato dai compilatori integrati |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nI metodi di `String`, `Number`, `Date` e `Array` che il framework aggiunge sono descritti nella loro pagina.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jablnn1jW60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/utilities/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Pomocné funkcie","summary":"Globálne pomocné funkcie a objekt U: identifikátory, kópie objektov, cesty, súbory, fronty a textové funkcie.","markdown":"---\ntitle: \"Pomocné funkcie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Pomocné funkcie\n\n> Globálne pomocné funkcie a objekt U: identifikátory, kópie objektov, cesty, súbory, fronty a textové funkcie.\n\nTotal.js vkladá do globálneho rozsahu sadu pomocných funkcií. Nevoláš na ne `require()`: sú dostupné v kontroléroch, schémach, definíciách, moduloch a pluginoch. Väčšina z nich je v objekte `U` (súbor `utils.js`), ostatné sú globálne funkcie a objekty. Úplný zoznam nájdeš v referencii [Pomocné funkcie](../../reference/utilities/).\n\n```js\nvar id = UID();\nvar ext = U.getExtension('Photo.JPG');   // 'jpg'\nvar copy = CLONE(model, { password: 1 });\n```\n\n`U`, `Utils` a `utils` sú ten istý objekt. `Total` je alias inštancie frameworku `F`.\n\n## Identifikátory\n\n| Funkcia | Výsledok |\n| --- | --- |\n| `UID([type])` | Krátke ID založené na čase, napríklad `24j0y001xn51d` |\n| `UID16([type])` | To isté s časom v sústave so základom 16 |\n| `GUID()` | Reťazec podobný UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` |\n| `GUID(length)` | Náhodné malé písmená a číslice |\n| `U.random_text(length)` | Náhodné písmená a číslice |\n| `U.random_number(length)` | Náhodné číslice ako reťazec, nikdy nezačína `0` |\n| `U.random([max], [min])` | Náhodné celé číslo (predvolene `0` až `100000`) |\n\n`UID()` je bežná voľba pre primárne kľúče: je krátke, jedinečné v rámci bežiacej inštancie a radí sa podľa času. Argument `type` vedie samostatné počítadlo pre každú kolekciu. `CONF.default_uid` nastavené na `r` prepne `UID()` na náhodné ID.\n\n```js\nfunction create(model) {\n\tmodel.id = UID('orders');\n\tmodel.dtcreated = NOW;\n\treturn model;\n}\n```\n\nKeď ID ide klientovi a vracia sa späť v URL, podpíš ho cez `U.encrypt_uid()`. `U.decrypt_uid()` vráti `null`, keď ho niekto zmenil. Hodnota nie je skrytá, len chránená.\n\n```js\nvar link = '/invoice/' + U.encrypt_uid(invoice.id) + '/';\n// later\nvar id = U.decrypt_uid(this.params.id);\n```\n\n## Objekty\n\n| Funkcia | Čo robí |\n| --- | --- |\n| `CLONE(obj, [skip])` | Hlboká kópia; `skip` je `{ key: 1 }` s kľúčmi, ktoré sa vynechajú |\n| `COPY(source, [target])` | Skopíruje všetky kľúče z `source` do `target` |\n| `U.copy(source, [target])` | Skopíruje len kľúče, ktoré `target` už má |\n| `U.extend(target, source, [rewrite])` | Pridá kľúče; s `rewrite = false` doplní len chýbajúce hodnoty |\n| `U.reduce(obj, keys, [reverse])` | Ponechá uvedené kľúče, alebo ich s `reverse` odstráni |\n| `U.get(obj, path)` / `U.set(obj, path, value)` | Čítanie a zápis podľa cesty ako `address.city` |\n| `U.trim(obj, [clean])` | Oreže všetky reťazce; `clean` zmení prázdne reťazce na `undefined` |\n| `DIFFARR(key, db, form)` | Porovná dva zoznamy: `{ add, upd, rem }` |\n\n`U.copy()` sa hodí, keď aktualizuješ uložený záznam z formulára: zapíšu sa len polia, ktoré záznam už má.\n\n```js\nvar user = { name: '', email: '' };\nU.copy(this.body, user);   // extra keys of the body are ignored\nvar output = U.reduce(user, ['password'], true);\n```\n\n`DIFFARR()` ti povie, čo vložiť, aktualizovať a odstrániť, keď používateľ uloží upravený zoznam.\n\n```js\nvar diff = DIFFARR('id', stored, model.items);\ndiff.add.forEach(insert);\ndiff.upd.forEach(function(item) {\n\tupdate(item.db, item.form);\n});\ndiff.rem.forEach(remove);\n```\n\n## Zdieľaný stav\n\nFramework vytvára pre tvoju aplikáciu prázdne globálne objekty: `MAIN`, `REPO` a `FUNC`. Nikdy do nich nezapisuje, takže sú bezpečným miestom pre zdieľané dáta a pomocné funkcie. `TEMP` sa pravidelne čistí (predvolene každých 10 minút). `NOW` je `Date`, ktorý framework obnovuje približne každú minútu; použi ho pre časové značky, kde stačí presnosť na minútu. `EMPTYOBJECT` a `EMPTYARRAY` sú zmrazené predvolené hodnoty a `NOOP` je prázdny callback.\n\n```js\n// definitions/init.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nMAIN.countries = ['SK', 'CZ', 'AT'];\n```\n\nNačítané moduly sú v `MODS` a `MODULE(name)` vráti jeden z nich alebo `null`.\n\n## Cesty a súbory\n\n`PATH` vracia cesty k adresárom aplikácie. Každý adresár pochádza z jeho voľby `CONF.directory_*`. `PATH.temp()`, `PATH.databases()` a `PATH.logs()` adresár aj vytvoria, keď chýba.\n\n```js\nPATH.root('data/countries.json');\nPATH.public('img/logo.png');\nPATH.temp('export.csv');\nPATH.databases('settings.json');\nPATH.mkdir(PATH.databases('uploads/2021/'), true);\n```\n\n`U.combine()` spája cesty relatívne ku koreňu aplikácie, `U.join()` spája časti cesty URL a `U.path()` pridá koncovú lomku. `U.getExtension()`, `U.getName()` a `U.getContentType()` pracujú s názvami súborov. `U.setContentType()` pridá novú príponu do tabuľky, ktorú framework používa pre statické súbory.\n\n`U.ls()` vypíše adresár so všetkými jeho podadresármi. Bez callbacku vráti Promise. Argument `unified` dáva na Windows cesty s `/`. `U.ls2()` pridá `fs.Stats` každého súboru.\n\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files);\n}, /\\.(jpg|png)$/);\n\nvar response = await U.ls2(PATH.temp());\nresponse.files.forEach(function(file) {\n\tconsole.log(file.filename, file.stats.size);\n});\n```\n\n`LOGGER(name, ...)` pripojí riadok s dátumom do `/logs/{name}.log`.\n\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n```\n\n## Asynchrónne pomocné funkcie\n\n`U.queue(name, max, fn)` spúšťa naraz najviac `max` funkcií jednej fronty; každá funkcia zavolá `next()`, keď skončí. `WAIT(validator, callback, [timeout], [interval])` kontroluje podmienku, kým nie je pravdivá alebo kým nevyprší čas. `PROMISIFY(fn, [a], [b], [c])` premení funkciu s `callback(err, response)` na Promise.\n\n```js\nfiles.forEach(function(filename) {\n\tU.queue('resize', 2, function(next) {\n\t\tresize(filename, next);\n\t});\n});\n\nvar text = await PROMISIFY(require('fs').readFile, PATH.root('readme.md'), 'utf8');\n```\n\n## Text a dáta\n\n| Funkcia | Výsledok |\n| --- | --- |\n| `U.encode(value)` / `U.decode(value)` | HTML entity |\n| `U.btoa(value)` / `U.atob(value)` | Base64 |\n| `HASH(value, [type])` | Číselný hash alebo `md5`, `sha1`, `sha256`, `sha512`, `crc32` |\n| `U.keywords(text)` | Jedinečné slová pre vyhľadávací index |\n| `U.parseXML(xml)` | Plochý objekt s bodkovými cestami ako kľúčmi |\n| `U.parseInt(value, [def])` | Číslo z ľubovoľnej hodnoty (aj `U.parseFloat`, `U.parseBoolean`) |\n| `QUERIFY([url], obj)` | URL s query stringom |\n| `U.sortcomparer('price_desc,name')` | Porovnávacia funkcia pre `Array.sort()` |\n| `U.distance(lat1, lon1, lat2, lon2)` | Kilometre medzi dvoma GPS bodmi |\n| `U.minify_css/js/html(value)` | Kód minifikovaný vstavanými kompilátormi |\n\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\nproducts.sort(U.sortcomparer('price_desc,name'));\nvar url = QUERIFY('/api/products/', { page: 2, q: 'book' });\n```\n\nMetódy `String`, `Number`, `Date` a `Array`, ktoré pridáva framework, sú opísané na vlastnej stránke.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Prototypes","summary":"Methods that Total.js 4 adds to strings, numbers, dates and arrays.","markdown":"---\ntitle: Prototypes\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypes\n\n> Methods that Total.js 4 adds to strings, numbers, dates and arrays.\n\nTotal.js 4 adds methods to the built-in prototypes of `String`, `Number`, `Date` and `Array`. They are available everywhere after the framework starts: in controllers, schemas, views, definitions and plugins. You call them on the value itself, so the code stays short.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nThe full list with every argument is in the reference of [Prototypes](../../reference/prototypes/).\n\n## Strings\n\n### Placeholders\n\n`String.format()` replaces indexed placeholders and `String.args()` named ones. `args()` can encode the values for HTML, URL or JSON.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Converting values\n\nValues from a query string or a form are strings. The `parse*` methods convert them and never throw:\n\n| Method | Result |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` or your default when the whole string is not a number) |\n| `'Size 12px'.parseInt2()` | `12` (the first number in the text) |\n| `'12,5'.parseFloat()` | `12.5` (a decimal comma is accepted) |\n| `'on'.parseBoolean()` | `true` for `true`, `1` and `on` |\n| `'2024-01-15'.parseDate()` | a `Date` |\n| `'{\"a\":1}'.parseJSON()` | an object, or `undefined` for invalid JSON |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validation\n\n`String.isEmail()`, `String.isPhone()` and `String.isURL()` use the regular expressions in `DEF.validators`, so you can change them in one place. `String.isUID()` checks the format and the checksum of an identifier created by `UID()`.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Text helpers\n\n- `String.slug()` makes a URL part from a title: `'Hello World'.slug()` gives `hello-world`.\n- `String.max(length)` shortens a text and adds `...`.\n- `String.capitalize()` upper-cases the first letter of each word.\n- `String.toASCII()` removes diacritics; `String.removeTags()` removes HTML tags.\n- `String.encode()` and `String.decode()` convert HTML special characters.\n- `String.padLeft()` and `String.padRight()` pad a string to a length.\n- `String.tslash()` removes trailing slashes from a URL.\n\n### Hashes and encryption\n\n`String.md5()`, `String.sha1()`, `String.sha256()` and `String.sha512()` return hex hashes; each accepts a salt. `String.hash()` selects the algorithm by name and without a name returns a fast number hash, good for cache keys.\n\n`String.encrypt(key)` and `String.decrypt(key)` protect small values such as tokens. Decryption returns `null` when the key, the secret (`CONF.secret`) or the string does not match.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Search\n\n`String.keywords()` returns the words of a text sorted by frequency and normalized for search. `String.toSearch()` normalizes a phrase in the same spirit. Store the keywords with the record and search by them.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown and JSON schemas\n\n`String.markdown()` converts Markdown to HTML and `String.toJSONSchema()` turns an inline definition such as `'*name:string(50), email:email'` into a JSON schema object.\n\n## Numbers\n\n`Number.format()` adds a thousands separator and decimals; `Number.round()` and `Number.floor()` work with decimals; `Number.padLeft()` adds leading zeros.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` picks a word form for 0, 1, 2-4 and other numbers, and replaces `#` with the number. The forms can also be one comma-separated string.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nPrices have their own helpers: `Number.VAT()` adds or removes VAT, `Number.discount()` subtracts a percentage, and `Number.add('+20%')` applies an operation written as a string. `Number.filesize()` formats bytes as `KB`, `MB` and so on. `Number.between()` maps ranges to values.\n\n## Dates\n\n`Date.add()` returns a new date moved by a period, and `Date.format()` writes the date with tokens such as `yyyy`, `MM`, `dd`, `HH` and `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` returns the difference in a unit, `Date.extend('12:00')` sets date or time parts, `Date.toUTC()` shifts the date by the timezone offset and `Date.setTimeZone()` converts it to an IANA timezone. `Date.add()` and `Date.extend()` never change the original date.\n\n## Arrays\n\n### Finding items\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` and `Array.remove()` accept either a function or a property name with a value:\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js replaces the native `findIndex()` to support this form. Some NPM modules replace it again, so the same method is also available as `Array.TfindIndex()`.\n\n### Paging, sorting and lookups\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` sorts in place by one or more properties. `Array.toObject()` makes a lookup object, which is faster than repeated searches.\n\n### Asynchronous processing\n\n`Array.wait()` calls an asynchronous function for each item, `Array.async()` runs a list of functions, and `Array.limit()` processes items in chunks. In each case you call `next()` to continue, and a final callback runs at the end.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` does the same for a number of runs.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Prototypen","summary":"Methoden, die Total.js 4 zu Strings, Zahlen, Datumswerten und Arrays hinzufügt.","markdown":"---\ntitle: Prototypen\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypen\n\n> Methoden, die Total.js 4 zu Strings, Zahlen, Datumswerten und Arrays hinzufügt.\n\nTotal.js 4 fügt den eingebauten Prototypen von `String`, `Number`, `Date` und `Array` Methoden hinzu. Sie sind nach dem Start des Frameworks überall verfügbar: in Controllern, Schemas, Views, Definitionen und Plugins. Du rufst sie direkt auf dem Wert auf, so bleibt der Code kurz.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nDie vollständige Liste mit jedem Argument steht in der Referenz zu [Prototypen](../../reference/prototypes/).\n\n## Strings\n\n### Platzhalter\n\n`String.format()` ersetzt indizierte Platzhalter und `String.args()` benannte. `args()` kann die Werte für HTML, URL oder JSON kodieren.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Werte umwandeln\n\nWerte aus einem Query-String oder einem Formular sind Strings. Die Methoden `parse*` wandeln sie um und werfen nie einen Fehler:\n\n| Methode | Ergebnis |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` oder dein Standardwert, wenn der ganze String keine Zahl ist) |\n| `'Size 12px'.parseInt2()` | `12` (die erste Zahl im Text) |\n| `'12,5'.parseFloat()` | `12.5` (ein Dezimalkomma wird akzeptiert) |\n| `'on'.parseBoolean()` | `true` für `true`, `1` und `on` |\n| `'2024-01-15'.parseDate()` | ein `Date` |\n| `'{\"a\":1}'.parseJSON()` | ein Objekt oder `undefined` bei ungültigem JSON |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validierung\n\n`String.isEmail()`, `String.isPhone()` und `String.isURL()` verwenden die regulären Ausdrücke in `DEF.validators`, sodass du sie an einer Stelle ändern kannst. `String.isUID()` prüft das Format und die Prüfsumme eines Bezeichners, der von `UID()` erstellt wurde.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Text-Helfer\n\n- `String.slug()` macht aus einem Titel einen URL-Teil: `'Hello World'.slug()` ergibt `hello-world`.\n- `String.max(length)` kürzt einen Text und fügt `...` hinzu.\n- `String.capitalize()` schreibt den ersten Buchstaben jedes Worts groß.\n- `String.toASCII()` entfernt diakritische Zeichen; `String.removeTags()` entfernt HTML-Tags.\n- `String.encode()` und `String.decode()` wandeln HTML-Sonderzeichen um.\n- `String.padLeft()` und `String.padRight()` füllen einen String auf eine Länge auf.\n- `String.tslash()` entfernt abschließende Schrägstriche aus einer URL.\n\n### Hashes und Verschlüsselung\n\n`String.md5()`, `String.sha1()`, `String.sha256()` und `String.sha512()` geben Hex-Hashes zurück; jede akzeptiert ein Salt. `String.hash()` wählt den Algorithmus nach Namen und gibt ohne Namen einen schnellen Zahlen-Hash zurück, gut für Cache-Schlüssel.\n\n`String.encrypt(key)` und `String.decrypt(key)` schützen kleine Werte wie Tokens. Die Entschlüsselung gibt `null` zurück, wenn der Schlüssel, das Secret (`CONF.secret`) oder der String nicht passt.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Suche\n\n`String.keywords()` gibt die Wörter eines Texts zurück, nach Häufigkeit sortiert und für die Suche normalisiert. `String.toSearch()` normalisiert eine Phrase auf dieselbe Weise. Speichere die Schlüsselwörter mit dem Datensatz und suche danach.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown und JSON-Schemas\n\n`String.markdown()` wandelt Markdown in HTML um, und `String.toJSONSchema()` macht aus einer Inline-Definition wie `'*name:string(50), email:email'` ein JSON-Schema-Objekt.\n\n## Zahlen\n\n`Number.format()` fügt ein Tausendertrennzeichen und Dezimalstellen hinzu; `Number.round()` und `Number.floor()` arbeiten mit Dezimalstellen; `Number.padLeft()` fügt führende Nullen hinzu.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` wählt eine Wortform für 0, 1, 2-4 und andere Zahlen und ersetzt `#` durch die Zahl. Die Formen können auch ein einziger kommagetrennter String sein.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nPreise haben eigene Helfer: `Number.VAT()` fügt die Mehrwertsteuer hinzu oder entfernt sie, `Number.discount()` zieht einen Prozentsatz ab, und `Number.add('+20%')` wendet eine als String geschriebene Operation an. `Number.filesize()` formatiert Bytes als `KB`, `MB` und so weiter. `Number.between()` ordnet Bereichen Werte zu.\n\n## Datumswerte\n\n`Date.add()` gibt ein neues, um einen Zeitraum verschobenes Datum zurück, und `Date.format()` schreibt das Datum mit Tokens wie `yyyy`, `MM`, `dd`, `HH` und `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` gibt die Differenz in einer Einheit zurück, `Date.extend('12:00')` setzt Teile von Datum oder Uhrzeit, `Date.toUTC()` verschiebt das Datum um den Zeitzonen-Offset, und `Date.setTimeZone()` wandelt es in eine IANA-Zeitzone um. `Date.add()` und `Date.extend()` ändern nie das ursprüngliche Datum.\n\n## Arrays\n\n### Elemente finden\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` und `Array.remove()` akzeptieren entweder eine Funktion oder einen Eigenschaftsnamen mit einem Wert:\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js ersetzt das native `findIndex()`, um diese Form zu unterstützen. Manche NPM-Module ersetzen es erneut, daher ist dieselbe Methode auch als `Array.TfindIndex()` verfügbar.\n\n### Blättern, Sortieren und Nachschlagen\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` sortiert direkt im Array nach einer oder mehreren Eigenschaften. `Array.toObject()` erstellt ein Nachschlage-Objekt, was schneller ist als wiederholte Suchen.\n\n### Asynchrone Verarbeitung\n\n`Array.wait()` ruft für jedes Element eine asynchrone Funktion auf, `Array.async()` führt eine Liste von Funktionen aus, und `Array.limit()` verarbeitet Elemente in Blöcken. In jedem Fall rufst du `next()` auf, um fortzufahren, und am Ende läuft ein abschließender Callback.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` tut dasselbe für eine Anzahl von Durchläufen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Prototipos","summary":"Métodos que Total.js 4 añade a strings, números, fechas y arrays.","markdown":"---\ntitle: Prototipos\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototipos\n\n> Métodos que Total.js 4 añade a strings, números, fechas y arrays.\n\nTotal.js 4 añade métodos a los prototipos integrados de `String`, `Number`, `Date` y `Array`. Están disponibles en todas partes una vez que el framework arranca: en controladores, esquemas, vistas, definiciones y plugins. Los llamas sobre el propio valor, así que el código queda corto.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nLa lista completa con cada argumento está en la referencia de [Prototipos](../../reference/prototypes/).\n\n## Strings\n\n### Marcadores\n\n`String.format()` reemplaza marcadores indexados y `String.args()` marcadores con nombre. `args()` puede codificar los valores para HTML, URL o JSON.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Convertir valores\n\nLos valores de una query string o de un formulario son strings. Los métodos `parse*` los convierten y nunca lanzan excepciones:\n\n| Método | Resultado |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` o tu valor por defecto cuando el string completo no es un número) |\n| `'Size 12px'.parseInt2()` | `12` (el primer número del texto) |\n| `'12,5'.parseFloat()` | `12.5` (se acepta la coma decimal) |\n| `'on'.parseBoolean()` | `true` para `true`, `1` y `on` |\n| `'2024-01-15'.parseDate()` | un `Date` |\n| `'{\"a\":1}'.parseJSON()` | un objeto, o `undefined` para JSON no válido |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validación\n\n`String.isEmail()`, `String.isPhone()` y `String.isURL()` usan las expresiones regulares de `DEF.validators`, así que puedes cambiarlas en un solo lugar. `String.isUID()` comprueba el formato y el checksum de un identificador creado por `UID()`.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Helpers de texto\n\n- `String.slug()` crea una parte de URL a partir de un título: `'Hello World'.slug()` da `hello-world`.\n- `String.max(length)` acorta un texto y añade `...`.\n- `String.capitalize()` pone en mayúscula la primera letra de cada palabra.\n- `String.toASCII()` elimina los diacríticos; `String.removeTags()` elimina las etiquetas HTML.\n- `String.encode()` y `String.decode()` convierten los caracteres especiales de HTML.\n- `String.padLeft()` y `String.padRight()` rellenan un string hasta una longitud.\n- `String.tslash()` elimina las barras finales de una URL.\n\n### Hashes y cifrado\n\n`String.md5()`, `String.sha1()`, `String.sha256()` y `String.sha512()` devuelven hashes en hexadecimal; cada uno acepta una sal. `String.hash()` elige el algoritmo por nombre y, sin nombre, devuelve un hash numérico rápido, bueno para claves de caché.\n\n`String.encrypt(key)` y `String.decrypt(key)` protegen valores pequeños como tokens. El descifrado devuelve `null` cuando la clave, el secreto (`CONF.secret`) o el string no coinciden.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Búsqueda\n\n`String.keywords()` devuelve las palabras de un texto ordenadas por frecuencia y normalizadas para la búsqueda. `String.toSearch()` normaliza una frase con el mismo criterio. Guarda las palabras clave con el registro y busca por ellas.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown y esquemas JSON\n\n`String.markdown()` convierte Markdown en HTML y `String.toJSONSchema()` convierte una definición en línea como `'*name:string(50), email:email'` en un objeto de esquema JSON.\n\n## Números\n\n`Number.format()` añade separador de miles y decimales; `Number.round()` y `Number.floor()` trabajan con decimales; `Number.padLeft()` añade ceros a la izquierda.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` elige una forma de la palabra para 0, 1, 2-4 y otros números, y reemplaza `#` por el número. Las formas también pueden ser un único string separado por comas.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nLos precios tienen sus propios helpers: `Number.VAT()` añade o quita el IVA, `Number.discount()` resta un porcentaje y `Number.add('+20%')` aplica una operación escrita como string. `Number.filesize()` formatea bytes como `KB`, `MB`, etc. `Number.between()` asocia rangos con valores.\n\n## Fechas\n\n`Date.add()` devuelve una nueva fecha desplazada un periodo, y `Date.format()` escribe la fecha con tokens como `yyyy`, `MM`, `dd`, `HH` y `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` devuelve la diferencia en una unidad, `Date.extend('12:00')` define partes de la fecha o de la hora, `Date.toUTC()` desplaza la fecha según el offset de la zona horaria y `Date.setTimeZone()` la convierte a una zona horaria IANA. `Date.add()` y `Date.extend()` nunca modifican la fecha original.\n\n## Arrays\n\n### Buscar elementos\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` y `Array.remove()` aceptan una función o un nombre de propiedad con un valor:\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js reemplaza el `findIndex()` nativo para admitir esta forma. Algunos módulos NPM lo vuelven a reemplazar, así que el mismo método también está disponible como `Array.TfindIndex()`.\n\n### Paginación, ordenación y búsquedas\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` ordena en el sitio por una o varias propiedades. `Array.toObject()` crea un objeto de búsqueda, más rápido que buscar repetidamente.\n\n### Procesamiento asíncrono\n\n`Array.wait()` llama a una función asíncrona para cada elemento, `Array.async()` ejecuta una lista de funciones y `Array.limit()` procesa los elementos por bloques. En cada caso llamas a `next()` para continuar, y un callback final se ejecuta al terminar.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` hace lo mismo para un número de ejecuciones.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Prototypes","summary":"Méthodes que Total.js 4 ajoute aux chaînes, aux nombres, aux dates et aux tableaux.","markdown":"---\ntitle: Prototypes\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypes\n\n> Méthodes que Total.js 4 ajoute aux chaînes, aux nombres, aux dates et aux tableaux.\n\nTotal.js 4 ajoute des méthodes aux prototypes intégrés de `String`, `Number`, `Date` et `Array`. Elles sont disponibles partout après le démarrage du framework : dans les contrôleurs, les schémas, les vues, les définitions et les plugins. Tu les appelles sur la valeur elle-même, ce qui garde le code court.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nLa liste complète, avec chaque argument, se trouve dans la référence des [Prototypes](../../reference/prototypes/).\n\n## Chaînes\n\n### Placeholders\n\n`String.format()` remplace des placeholders indexés et `String.args()` des placeholders nommés. `args()` peut encoder les valeurs pour HTML, URL ou JSON.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Conversion des valeurs\n\nLes valeurs issues d'une query string ou d'un formulaire sont des chaînes. Les méthodes `parse*` les convertissent et ne lèvent jamais d'exception :\n\n| Méthode | Résultat |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` ou ta valeur par défaut quand la chaîne entière n'est pas un nombre) |\n| `'Size 12px'.parseInt2()` | `12` (le premier nombre du texte) |\n| `'12,5'.parseFloat()` | `12.5` (une virgule décimale est acceptée) |\n| `'on'.parseBoolean()` | `true` pour `true`, `1` et `on` |\n| `'2024-01-15'.parseDate()` | une `Date` |\n| `'{\"a\":1}'.parseJSON()` | un objet, ou `undefined` pour un JSON invalide |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validation\n\n`String.isEmail()`, `String.isPhone()` et `String.isURL()` utilisent les expressions régulières de `DEF.validators` ; tu peux donc les modifier en un seul endroit. `String.isUID()` vérifie le format et la somme de contrôle d'un identifiant créé par `UID()`.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Helpers de texte\n\n- `String.slug()` crée une partie d'URL à partir d'un titre : `'Hello World'.slug()` donne `hello-world`.\n- `String.max(length)` raccourcit un texte et ajoute `...`.\n- `String.capitalize()` met en majuscule la première lettre de chaque mot.\n- `String.toASCII()` supprime les signes diacritiques ; `String.removeTags()` supprime les balises HTML.\n- `String.encode()` et `String.decode()` convertissent les caractères spéciaux HTML.\n- `String.padLeft()` et `String.padRight()` complètent une chaîne jusqu'à une longueur donnée.\n- `String.tslash()` supprime les barres obliques finales d'une URL.\n\n### Hashes et chiffrement\n\n`String.md5()`, `String.sha1()`, `String.sha256()` et `String.sha512()` renvoient des hashes hexadécimaux ; chacune accepte un sel. `String.hash()` choisit l'algorithme par son nom et, sans nom, renvoie un hash numérique rapide, adapté aux clés de cache.\n\n`String.encrypt(key)` et `String.decrypt(key)` protègent de petites valeurs comme des tokens. Le déchiffrement renvoie `null` quand la clé, le secret (`CONF.secret`) ou la chaîne ne correspondent pas.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Recherche\n\n`String.keywords()` renvoie les mots d'un texte triés par fréquence et normalisés pour la recherche. `String.toSearch()` normalise une phrase dans le même esprit. Stocke les mots-clés avec l'enregistrement et recherche par ceux-ci.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown et schémas JSON\n\n`String.markdown()` convertit du Markdown en HTML et `String.toJSONSchema()` transforme une définition en ligne comme `'*name:string(50), email:email'` en objet de schéma JSON.\n\n## Nombres\n\n`Number.format()` ajoute un séparateur de milliers et des décimales ; `Number.round()` et `Number.floor()` travaillent avec des décimales ; `Number.padLeft()` ajoute des zéros en tête.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` choisit une forme de mot pour 0, 1, 2-4 et les autres nombres, et remplace `#` par le nombre. Les formes peuvent aussi être une seule chaîne séparée par des virgules.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nLes prix ont leurs propres helpers : `Number.VAT()` ajoute ou retire la TVA, `Number.discount()` soustrait un pourcentage, et `Number.add('+20%')` applique une opération écrite sous forme de chaîne. `Number.filesize()` formate des octets en `KB`, `MB`, etc. `Number.between()` associe des plages à des valeurs.\n\n## Dates\n\n`Date.add()` renvoie une nouvelle date décalée d'une période, et `Date.format()` écrit la date avec des tokens comme `yyyy`, `MM`, `dd`, `HH` et `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` renvoie la différence dans une unité, `Date.extend('12:00')` définit des parties de la date ou de l'heure, `Date.toUTC()` décale la date du décalage du fuseau horaire et `Date.setTimeZone()` la convertit vers un fuseau horaire IANA. `Date.add()` et `Date.extend()` ne modifient jamais la date d'origine.\n\n## Tableaux\n\n### Trouver des éléments\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` et `Array.remove()` acceptent soit une fonction, soit un nom de propriété avec une valeur :\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js remplace la méthode native `findIndex()` pour prendre en charge cette forme. Certains modules NPM la remplacent à nouveau ; la même méthode est donc aussi disponible sous le nom `Array.TfindIndex()`.\n\n### Pagination, tri et recherches\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` trie sur place selon une ou plusieurs propriétés. `Array.toObject()` crée un objet de recherche, plus rapide que des recherches répétées.\n\n### Traitement asynchrone\n\n`Array.wait()` appelle une fonction asynchrone pour chaque élément, `Array.async()` exécute une liste de fonctions, et `Array.limit()` traite les éléments par lots. Dans chaque cas, tu appelles `next()` pour continuer, et un callback final s'exécute à la fin.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` fait de même pour un nombre d'exécutions.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Prototipi","summary":"Metodi che Total.js 4 aggiunge a stringhe, numeri, date e array.","markdown":"---\ntitle: Prototipi\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototipi\n\n> Metodi che Total.js 4 aggiunge a stringhe, numeri, date e array.\n\nTotal.js 4 aggiunge metodi ai prototipi integrati di `String`, `Number`, `Date` e `Array`. Sono disponibili ovunque dopo l'avvio del framework: in controller, schemi, viste, definizioni e plugin. Li chiami sul valore stesso, così il codice resta breve.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nL'elenco completo con ogni argomento è nel riferimento di [Prototipi](../../reference/prototypes/).\n\n## Stringhe\n\n### Segnaposto\n\n`String.format()` sostituisce i segnaposto indicizzati e `String.args()` quelli con nome. `args()` può codificare i valori per HTML, URL o JSON.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Convertire i valori\n\nI valori di una query string o di un form sono stringhe. I metodi `parse*` li convertono e non lanciano mai eccezioni:\n\n| Metodo | Risultato |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` o il tuo valore predefinito quando l'intera stringa non è un numero) |\n| `'Size 12px'.parseInt2()` | `12` (il primo numero nel testo) |\n| `'12,5'.parseFloat()` | `12.5` (è accettata la virgola decimale) |\n| `'on'.parseBoolean()` | `true` per `true`, `1` e `on` |\n| `'2024-01-15'.parseDate()` | un `Date` |\n| `'{\"a\":1}'.parseJSON()` | un oggetto, oppure `undefined` per un JSON non valido |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validazione\n\n`String.isEmail()`, `String.isPhone()` e `String.isURL()` usano le espressioni regolari in `DEF.validators`, così puoi modificarle in un unico punto. `String.isUID()` controlla il formato e il checksum di un identificatore creato da `UID()`.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Helper per il testo\n\n- `String.slug()` crea una parte di URL da un titolo: `'Hello World'.slug()` restituisce `hello-world`.\n- `String.max(length)` accorcia un testo e aggiunge `...`.\n- `String.capitalize()` mette in maiuscolo la prima lettera di ogni parola.\n- `String.toASCII()` rimuove i segni diacritici; `String.removeTags()` rimuove i tag HTML.\n- `String.encode()` e `String.decode()` convertono i caratteri speciali HTML.\n- `String.padLeft()` e `String.padRight()` riempiono una stringa fino a una lunghezza.\n- `String.tslash()` rimuove le barre finali da un URL.\n\n### Hash e cifratura\n\n`String.md5()`, `String.sha1()`, `String.sha256()` e `String.sha512()` restituiscono hash esadecimali; ognuno accetta un salt. `String.hash()` seleziona l'algoritmo per nome e, senza nome, restituisce un hash numerico veloce, adatto per le chiavi di cache.\n\n`String.encrypt(key)` e `String.decrypt(key)` proteggono valori piccoli come i token. La decifratura restituisce `null` quando la chiave, il segreto (`CONF.secret`) o la stringa non corrispondono.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Ricerca\n\n`String.keywords()` restituisce le parole di un testo ordinate per frequenza e normalizzate per la ricerca. `String.toSearch()` normalizza una frase con lo stesso criterio. Salva le parole chiave insieme al record e cerca in base a esse.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown e schemi JSON\n\n`String.markdown()` converte Markdown in HTML e `String.toJSONSchema()` trasforma una definizione inline come `'*name:string(50), email:email'` in un oggetto schema JSON.\n\n## Numeri\n\n`Number.format()` aggiunge un separatore delle migliaia e i decimali; `Number.round()` e `Number.floor()` lavorano con i decimali; `Number.padLeft()` aggiunge zeri iniziali.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` sceglie una forma della parola per 0, 1, 2-4 e gli altri numeri, e sostituisce `#` con il numero. Le forme possono anche essere un'unica stringa separata da virgole.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nI prezzi hanno i propri helper: `Number.VAT()` aggiunge o toglie l'IVA, `Number.discount()` sottrae una percentuale e `Number.add('+20%')` applica un'operazione scritta come stringa. `Number.filesize()` formatta i byte come `KB`, `MB` e così via. `Number.between()` associa intervalli a valori.\n\n## Date\n\n`Date.add()` restituisce una nuova data spostata di un periodo, e `Date.format()` scrive la data con token come `yyyy`, `MM`, `dd`, `HH` e `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` restituisce la differenza in un'unità, `Date.extend('12:00')` imposta parti della data o dell'ora, `Date.toUTC()` sposta la data dell'offset del fuso orario e `Date.setTimeZone()` la converte in un fuso orario IANA. `Date.add()` e `Date.extend()` non modificano mai la data originale.\n\n## Array\n\n### Trovare elementi\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` e `Array.remove()` accettano una funzione oppure il nome di una proprietà con un valore:\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js sostituisce il `findIndex()` nativo per supportare questa forma. Alcuni moduli NPM lo sostituiscono di nuovo, quindi lo stesso metodo è disponibile anche come `Array.TfindIndex()`.\n\n### Paginazione, ordinamento e lookup\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` ordina sul posto in base a una o più proprietà. `Array.toObject()` crea un oggetto di lookup, più veloce delle ricerche ripetute.\n\n### Elaborazione asincrona\n\n`Array.wait()` chiama una funzione asincrona per ogni elemento, `Array.async()` esegue un elenco di funzioni e `Array.limit()` elabora gli elementi a blocchi. In ogni caso chiami `next()` per continuare, e alla fine viene eseguita una callback finale.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` fa lo stesso per un numero di esecuzioni.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpE1rW60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/prototypes/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Prototypy","summary":"Metódy, ktoré Total.js 4 pridáva reťazcom, číslam, dátumom a poliam.","markdown":"---\ntitle: Prototypy\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypy\n\n> Metódy, ktoré Total.js 4 pridáva reťazcom, číslam, dátumom a poliam.\n\nTotal.js 4 pridáva metódy do vstavaných prototypov `String`, `Number`, `Date` a `Array`. Po štarte frameworku sú dostupné všade: v kontroléroch, schémach, pohľadoch, definíciách a pluginoch. Voláš ich priamo na hodnote, takže kód zostáva krátky.\n\n```js\nvar slug = model.name.slug();\nvar price = (model.price || 0).format(2);\nvar expire = NOW.add('1 month');\nvar user = users.findItem('id', id);\n```\n\nÚplný zoznam so všetkými argumentmi nájdeš v referencii [Prototypy](../../reference/prototypes/).\n\n## Reťazce\n\n### Zástupné symboly\n\n`String.format()` nahrádza indexované zástupné symboly a `String.args()` pomenované. `args()` vie hodnoty zakódovať pre HTML, URL alebo JSON.\n\n```js\n'{0} of {1}'.format(3, 10);                       // 3 of 10\n'Hello {name}'.args({ name: 'Peter' });           // Hello Peter\n'<a>{name}</a>'.args({ name: '<x>' }, 'html');    // <a>&lt;x&gt;</a>\n```\n\n### Prevod hodnôt\n\nHodnoty z query stringu alebo z formulára sú reťazce. Metódy `parse*` ich prevádzajú a nikdy nevyhodia výnimku:\n\n| Metóda | Výsledok |\n| --- | --- |\n| `'12'.parseInt()` | `12` (`0` alebo tvoja predvolená hodnota, keď celý reťazec nie je číslo) |\n| `'Size 12px'.parseInt2()` | `12` (prvé číslo v texte) |\n| `'12,5'.parseFloat()` | `12.5` (desatinná čiarka sa akceptuje) |\n| `'on'.parseBoolean()` | `true` pre `true`, `1` a `on` |\n| `'2024-01-15'.parseDate()` | `Date` |\n| `'{\"a\":1}'.parseJSON()` | objekt, alebo `undefined` pre neplatný JSON |\n\n```js\nfunction list() {\n\tvar page = (this.query.page || '').parseInt(1);\n\tvar limit = (this.query.limit || '').parseInt(20);\n\tthis.json({ page: page, limit: limit });\n}\n```\n\n### Validácia\n\n`String.isEmail()`, `String.isPhone()` a `String.isURL()` používajú regulárne výrazy v `DEF.validators`, takže ich môžeš zmeniť na jednom mieste. `String.isUID()` kontroluje formát a kontrolný súčet identifikátora vytvoreného cez `UID()`.\n\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### Textové pomocné funkcie\n\n- `String.slug()` vytvorí časť URL z nadpisu: `'Hello World'.slug()` dá `hello-world`.\n- `String.max(length)` skráti text a pridá `...`.\n- `String.capitalize()` zmení prvé písmeno každého slova na veľké.\n- `String.toASCII()` odstráni diakritiku; `String.removeTags()` odstráni HTML tagy.\n- `String.encode()` a `String.decode()` prevádzajú špeciálne znaky HTML.\n- `String.padLeft()` a `String.padRight()` doplnia reťazec na dĺžku.\n- `String.tslash()` odstráni koncové lomky z URL.\n\n### Hashe a šifrovanie\n\n`String.md5()`, `String.sha1()`, `String.sha256()` a `String.sha512()` vracajú hexadecimálne hashe; každá akceptuje soľ. `String.hash()` vyberie algoritmus podľa názvu a bez názvu vráti rýchly číselný hash, vhodný pre kľúče cache.\n\n`String.encrypt(key)` a `String.decrypt(key)` chránia malé hodnoty, napríklad tokeny. Dešifrovanie vráti `null`, keď kľúč, tajomstvo (`CONF.secret`) alebo reťazec nesedí.\n\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('reset', true);\n\n// later\nvar data = (this.query.token || '').decrypt('reset');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### Vyhľadávanie\n\n`String.keywords()` vráti slová textu zoradené podľa frekvencie a normalizované pre vyhľadávanie. `String.toSearch()` normalizuje frázu v rovnakom duchu. Kľúčové slová ulož spolu so záznamom a vyhľadávaj podľa nich.\n\n```js\nitem.search = (item.name + ' ' + item.description).keywords().join(' ');\nvar q = (this.query.q || '').toSearch();\n```\n\n### Markdown a JSON schémy\n\n`String.markdown()` prevedie Markdown na HTML a `String.toJSONSchema()` premení inline definíciu ako `'*name:string(50), email:email'` na objekt JSON schémy.\n\n## Čísla\n\n`Number.format()` pridá oddeľovač tisícov a desatinné miesta; `Number.round()` a `Number.floor()` pracujú s desatinnými miestami; `Number.padLeft()` pridá úvodné nuly.\n\n```js\n(1234567.891).format(2);   // 1 234 567.89\n(1234.5).format(2, '.');   // 1.234,50\n(3.14159).round(2);        // 3.14\n(42).padLeft(6);           // 000042\n```\n\n`Number.pluralize()` vyberie tvar slova pre 0, 1, 2-4 a ostatné čísla a nahradí `#` číslom. Tvary môžu byť aj jeden reťazec oddelený čiarkami.\n\n```js\ncount.pluralize('no comments', '# comment', '# comments', '# comments');\ncount.pluralize('no comments,# comment,# comments,# comments');\n```\n\nCeny majú vlastné pomocné funkcie: `Number.VAT()` pridá alebo odoberie DPH, `Number.discount()` odpočíta percentá a `Number.add('+20%')` použije operáciu zapísanú ako reťazec. `Number.filesize()` formátuje bajty ako `KB`, `MB` a podobne. `Number.between()` mapuje rozsahy na hodnoty.\n\n## Dátumy\n\n`Date.add()` vráti nový dátum posunutý o obdobie a `Date.format()` vypíše dátum s tokenmi ako `yyyy`, `MM`, `dd`, `HH` a `mm`.\n\n```js\nvar expire = NOW.add('7 days');\nvar label = NOW.format('dd.MM.yyyy HH:mm');\nvar left = expire.diff('hours');\n```\n\n`Date.diff()` vráti rozdiel v jednotke, `Date.extend('12:00')` nastaví časti dátumu alebo času, `Date.toUTC()` posunie dátum o posun časového pásma a `Date.setTimeZone()` ho prevedie do časového pásma IANA. `Date.add()` a `Date.extend()` nikdy nemenia pôvodný dátum.\n\n## Polia\n\n### Hľadanie položiek\n\n`Array.findItem()`, `Array.findAll()`, `Array.findIndex()` a `Array.remove()` akceptujú buď funkciu, alebo názov vlastnosti s hodnotou:\n\n```js\nvar user = users.findItem('id', id);\nvar active = users.findAll('active', true);\nvar index = users.findIndex(item => item.email === email);\nusers = users.remove('id', id);\n```\n\nTotal.js nahrádza natívne `findIndex()`, aby podporoval tento tvar. Niektoré NPM moduly ho opäť nahradia, preto je tá istá metóda dostupná aj ako `Array.TfindIndex()`.\n\n### Stránkovanie, radenie a vyhľadávacie objekty\n\n```js\nvar items = all.skip((page - 1) * limit).take(limit);\nproducts.quicksort('price_desc');\nvar byid = users.toObject('id');\n```\n\n`Array.quicksort()` radí na mieste podľa jednej alebo viacerých vlastností. `Array.toObject()` vytvorí vyhľadávací objekt, čo je rýchlejšie ako opakované hľadanie.\n\n### Asynchrónne spracovanie\n\n`Array.wait()` zavolá asynchrónnu funkciu pre každú položku, `Array.async()` spustí zoznam funkcií a `Array.limit()` spracúva položky po dávkach. V každom prípade zavoláš `next()` na pokračovanie a na konci sa spustí záverečný callback.\n\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n`Number.async()` robí to isté pre daný počet spustení.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm0c1kr61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"FlowStream","summary":"Run graphs of components from .flow files in /flowstreams/, write components and work with messages and FlowStream instances.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Run graphs of components from .flow files in /flowstreams/, write components and work with messages and FlowStream instances.\n\nA **FlowStream** is a graph of components connected through inputs and outputs. Data flows through it as **messages**. The Flow module is part of Total.js 4: put `.flow` files in `/flowstreams/` and the app loads them when it starts. The Flow designer edits a running FlowStream through a WebSocket. The exact list of methods is in the reference of [FlowStream](../../reference/flowstream/).\n\n## The /flowstreams/ directory\n\nEach `.flow` file is a JSON schema. When the app starts, the files of `/flowstreams/` (and `plugins/{name}/flowstreams/`) are passed to `Flow.load()`. Names that contain `-bk` or `_bk` are skipped, so backups can stay in the same folder. In debug mode, a changed `.flow` file restarts the app.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` maps a component id to the source of the component.\n- `design` maps an instance id to the component it uses, its `config` and its `connections`. A connection goes from an output id to `{ id: instance, index: input }`.\n- `variables` are values that components read with `instance.replace()` or `$.variables()`.\n- `worker: 'worker'` runs the FlowStream in a worker thread and another truthy value (for example `'fork'`) in a child process. The worker restarts itself when it crashes.\n\nYou can also call `Flow.load(schema, callback)` from code. A schema with an `id` that is already loaded updates the running FlowStream.\n\n## Components\n\nA component is an HTML file. Its `<script total>` block runs on the server; the other blocks (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) are for the designer.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` and `exports.outputs` declare the ports. Connections to an input that the component does not declare are removed.\n- `exports.config` is the default configuration, merged with the `config` of each instance.\n- `exports.make(instance, config)` runs once for each instance in the design.\n- `exports.npm` lists NPM packages that are installed before the component is registered.\n\nInside `make` you assign handlers to the instance:\n\n| Handler | When it runs |\n| --- | --- |\n| `instance.message($)` | A message arrived; `instance.message_INPUTID($)` for one input |\n| `instance.configure(config)` | The configuration changed |\n| `instance.trigger(data)` | `flowstream.trigger()` or the designer button |\n| `instance.close(removed)` | The instance stops; clear timers here |\n| `instance.init()`, `instance.refresh()` | After the design was created, and after each change |\n| `instance.variables(variables)` | The variables changed |\n\nAnd you call its methods: `instance.send(output, data)`, `instance.status(data, [delay])` and `instance.dashboard(data)` for the designer, `instance.throw(err)` for errors, `instance.replace(str)` for variables and `instance.save()` to store changed configuration.\n\n## Messages\n\n`$` is the message. `$.data` is its data. `$.send(output)` passes it to the next instances and `$.destroy()` ends it. Every message must end in one of these two ways; a message sent from an output with no connection ends by itself.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nWhen a message goes to several connections, each one gets its own copy of `$.data`, objects and Buffers alike (set `cloning: false` in the schema to turn it off). `$.repo` is one object shared by all copies, useful to carry values along the chain. `$.on('end', fn)` runs when the last copy ends; `$.timeout()` and `$.totaltimeout()` end slow messages with `$.error = 408`.\n\nA component without inputs starts messages itself:\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Using a FlowStream from the app\n\n`Flow.instances` holds the loaded FlowStreams by `id`. `send()` starts a message in one instance and calls back when the message ends:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nThe target can be an instance id, `@componentid` or `#name` (the component name). The target must define `instance.message`. Other methods:\n\n- `exec({ id, data, repo, timeout }, callback)` sends to all matching instances, with a timeout.\n- `trigger(id, data)` calls `instance.trigger(data)`.\n- `reconfigure(id, config)` and `variables(variables)` change settings at runtime.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` and `remove()`.\n- `stats` holds the counts of messages, pending messages and errors.\n\n## Saving changes\n\nThe framework reads `.flow` files but does not write them. When the designer or your code changes a FlowStream, `Flow` emits `save` with the whole schema about five seconds later. Store it yourself:\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nA schema with `readonly: true` never emits `save`. `Flow.on('load', fn)` runs when a FlowStream is ready, and `Flow.onerror` receives the errors of all FlowStreams.\n\n## The designer\n\nConnect a WebSocket route to a FlowStream with `Flow.socket(id, websocket, [check])`. Protect it, because the designer can change code:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## A local engine\n\n`FLOWSTREAM(name)` returns the engine without files, workers or the designer. Register components with `add()`, create instances with `use(design)` and send data with `trigger('instanceid__inputid', data)`. Most apps use `/flowstreams/` and `Flow` instead.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0c1kr61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"FlowStream","summary":"Führe Graphen von Komponenten aus .flow-Dateien in /flowstreams/ aus, schreibe Komponenten und arbeite mit Nachrichten und FlowStream-Instanzen.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Führe Graphen von Komponenten aus .flow-Dateien in /flowstreams/ aus, schreibe Komponenten und arbeite mit Nachrichten und FlowStream-Instanzen.\n\nEin **FlowStream** ist ein Graph aus Komponenten, die über Eingänge und Ausgänge verbunden sind. Daten fließen als **Nachrichten** hindurch. Das Flow-Modul ist Teil von Total.js 4: Lege `.flow`-Dateien in `/flowstreams/` ab, und die App lädt sie beim Start. Der Flow-Designer bearbeitet einen laufenden FlowStream über einen WebSocket. Die genaue Liste der Methoden steht in der Referenz zu [FlowStream](../../reference/flowstream/).\n\n## Das Verzeichnis /flowstreams/\n\nJede `.flow`-Datei ist ein JSON-Schema. Beim Start der App werden die Dateien aus `/flowstreams/` (und `plugins/{name}/flowstreams/`) an `Flow.load()` übergeben. Namen, die `-bk` oder `_bk` enthalten, werden übersprungen, damit Backups im selben Ordner bleiben können. Im Debug-Modus startet eine geänderte `.flow`-Datei die App neu.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` ordnet einer Komponenten-ID den Quelltext der Komponente zu.\n- `design` ordnet einer Instanz-ID die verwendete Komponente, ihre `config` und ihre `connections` zu. Eine Verbindung führt von einer Ausgangs-ID zu `{ id: instance, index: input }`.\n- `variables` sind Werte, die Komponenten mit `instance.replace()` oder `$.variables()` lesen.\n- `worker: 'worker'` führt den FlowStream in einem Worker-Thread aus, ein anderer truthy Wert (zum Beispiel `'fork'`) in einem Kindprozess. Der Worker startet sich selbst neu, wenn er abstürzt.\n\nDu kannst `Flow.load(schema, callback)` auch aus dem Code aufrufen. Ein Schema mit einer `id`, die bereits geladen ist, aktualisiert den laufenden FlowStream.\n\n## Komponenten\n\nEine Komponente ist eine HTML-Datei. Ihr Block `<script total>` läuft auf dem Server; die anderen Blöcke (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) sind für den Designer.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` und `exports.outputs` deklarieren die Ports. Verbindungen zu einem Eingang, den die Komponente nicht deklariert, werden entfernt.\n- `exports.config` ist die Standardkonfiguration, die mit der `config` jeder Instanz zusammengeführt wird.\n- `exports.make(instance, config)` läuft einmal für jede Instanz im Design.\n- `exports.npm` listet NPM-Pakete auf, die installiert werden, bevor die Komponente registriert wird.\n\nInnerhalb von `make` weist du der Instanz Handler zu:\n\n| Handler | Wann er läuft |\n| --- | --- |\n| `instance.message($)` | Eine Nachricht ist angekommen; `instance.message_INPUTID($)` für einen einzelnen Eingang |\n| `instance.configure(config)` | Die Konfiguration hat sich geändert |\n| `instance.trigger(data)` | `flowstream.trigger()` oder die Schaltfläche im Designer |\n| `instance.close(removed)` | Die Instanz stoppt; räume hier Timer auf |\n| `instance.init()`, `instance.refresh()` | Nachdem das Design erstellt wurde und nach jeder Änderung |\n| `instance.variables(variables)` | Die Variablen haben sich geändert |\n\nUnd du rufst ihre Methoden auf: `instance.send(output, data)`, `instance.status(data, [delay])` und `instance.dashboard(data)` für den Designer, `instance.throw(err)` für Fehler, `instance.replace(str)` für Variablen und `instance.save()`, um eine geänderte Konfiguration zu speichern.\n\n## Nachrichten\n\n`$` ist die Nachricht. `$.data` sind ihre Daten. `$.send(output)` gibt sie an die nächsten Instanzen weiter, und `$.destroy()` beendet sie. Jede Nachricht muss auf eine dieser beiden Arten enden; eine Nachricht, die von einem Ausgang ohne Verbindung gesendet wird, endet von selbst.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nWenn eine Nachricht an mehrere Verbindungen geht, bekommt jede ihre eigene Kopie von `$.data`, Objekte wie Buffer gleichermaßen (setze `cloning: false` im Schema, um das abzuschalten). `$.repo` ist ein Objekt, das alle Kopien teilen, nützlich, um Werte entlang der Kette mitzunehmen. `$.on('end', fn)` läuft, wenn die letzte Kopie endet; `$.timeout()` und `$.totaltimeout()` beenden langsame Nachrichten mit `$.error = 408`.\n\nEine Komponente ohne Eingänge startet Nachrichten selbst:\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Einen FlowStream aus der App verwenden\n\n`Flow.instances` enthält die geladenen FlowStreams nach `id`. `send()` startet eine Nachricht in einer Instanz und ruft zurück, wenn die Nachricht endet:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nDas Ziel kann eine Instanz-ID, `@componentid` oder `#name` (der Name der Komponente) sein. Das Ziel muss `instance.message` definieren. Weitere Methoden:\n\n- `exec({ id, data, repo, timeout }, callback)` sendet an alle passenden Instanzen, mit einem Timeout.\n- `trigger(id, data)` ruft `instance.trigger(data)` auf.\n- `reconfigure(id, config)` und `variables(variables)` ändern Einstellungen zur Laufzeit.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` und `remove()`.\n- `stats` enthält die Anzahl der Nachrichten, der ausstehenden Nachrichten und der Fehler.\n\n## Änderungen speichern\n\nDas Framework liest `.flow`-Dateien, schreibt sie aber nicht. Wenn der Designer oder dein Code einen FlowStream ändert, gibt `Flow` etwa fünf Sekunden später `save` mit dem ganzen Schema aus. Speichere es selbst:\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nEin Schema mit `readonly: true` gibt nie `save` aus. `Flow.on('load', fn)` läuft, wenn ein FlowStream bereit ist, und `Flow.onerror` empfängt die Fehler aller FlowStreams.\n\n## Der Designer\n\nVerbinde eine WebSocket-Route mit einem FlowStream über `Flow.socket(id, websocket, [check])`. Schütze sie, denn der Designer kann Code ändern:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## Eine lokale Engine\n\n`FLOWSTREAM(name)` gibt die Engine ohne Dateien, Worker oder Designer zurück. Registriere Komponenten mit `add()`, erstelle Instanzen mit `use(design)` und sende Daten mit `trigger('instanceid__inputid', data)`. Die meisten Apps verwenden stattdessen `/flowstreams/` und `Flow`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0c1kr61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"FlowStream","summary":"Ejecuta grafos de componentes desde archivos .flow en /flowstreams/, escribe componentes y trabaja con mensajes e instancias de FlowStream.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Ejecuta grafos de componentes desde archivos .flow en /flowstreams/, escribe componentes y trabaja con mensajes e instancias de FlowStream.\n\nUn **FlowStream** es un grafo de componentes conectados mediante entradas y salidas. Los datos fluyen por él como **mensajes**. El módulo Flow forma parte de Total.js 4: pon archivos `.flow` en `/flowstreams/` y la aplicación los carga al arrancar. El diseñador de Flow edita un FlowStream en ejecución a través de un WebSocket. La lista exacta de métodos está en la referencia de [FlowStream](../../reference/flowstream/).\n\n## El directorio /flowstreams/\n\nCada archivo `.flow` es un esquema JSON. Cuando la aplicación arranca, los archivos de `/flowstreams/` (y de `plugins/{name}/flowstreams/`) se pasan a `Flow.load()`. Los nombres que contienen `-bk` o `_bk` se omiten, así que las copias de seguridad pueden quedarse en la misma carpeta. En modo debug, un archivo `.flow` modificado reinicia la aplicación.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` asocia un id de componente con el código fuente del componente.\n- `design` asocia un id de instancia con el componente que usa, su `config` y sus `connections`. Una conexión va de un id de salida a `{ id: instance, index: input }`.\n- `variables` son valores que los componentes leen con `instance.replace()` o `$.variables()`.\n- `worker: 'worker'` ejecuta el FlowStream en un hilo worker, y otro valor verdadero (por ejemplo `'fork'`) en un proceso hijo. El worker se reinicia solo cuando falla.\n\nTambién puedes llamar a `Flow.load(schema, callback)` desde el código. Un esquema con un `id` que ya está cargado actualiza el FlowStream en ejecución.\n\n## Componentes\n\nUn componente es un archivo HTML. Su bloque `<script total>` se ejecuta en el servidor; los demás bloques (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) son para el diseñador.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` y `exports.outputs` declaran los puertos. Las conexiones a una entrada que el componente no declara se eliminan.\n- `exports.config` es la configuración por defecto, que se combina con la `config` de cada instancia.\n- `exports.make(instance, config)` se ejecuta una vez por cada instancia del diseño.\n- `exports.npm` enumera paquetes NPM que se instalan antes de registrar el componente.\n\nDentro de `make` asignas handlers a la instancia:\n\n| Handler | Cuándo se ejecuta |\n| --- | --- |\n| `instance.message($)` | Llegó un mensaje; `instance.message_INPUTID($)` para una sola entrada |\n| `instance.configure(config)` | La configuración cambió |\n| `instance.trigger(data)` | `flowstream.trigger()` o el botón del diseñador |\n| `instance.close(removed)` | La instancia se detiene; limpia aquí los temporizadores |\n| `instance.init()`, `instance.refresh()` | Después de crear el diseño, y después de cada cambio |\n| `instance.variables(variables)` | Las variables cambiaron |\n\nY llamas a sus métodos: `instance.send(output, data)`, `instance.status(data, [delay])` e `instance.dashboard(data)` para el diseñador, `instance.throw(err)` para errores, `instance.replace(str)` para variables e `instance.save()` para guardar la configuración modificada.\n\n## Mensajes\n\n`$` es el mensaje. `$.data` son sus datos. `$.send(output)` lo pasa a las siguientes instancias y `$.destroy()` lo termina. Todo mensaje debe terminar de una de estas dos formas; un mensaje enviado desde una salida sin conexión termina por sí solo.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nCuando un mensaje va a varias conexiones, cada una recibe su propia copia de `$.data`, tanto objetos como Buffers (pon `cloning: false` en el esquema para desactivarlo). `$.repo` es un objeto compartido por todas las copias, útil para llevar valores a lo largo de la cadena. `$.on('end', fn)` se ejecuta cuando termina la última copia; `$.timeout()` y `$.totaltimeout()` terminan los mensajes lentos con `$.error = 408`.\n\nUn componente sin entradas inicia los mensajes él mismo:\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Usar un FlowStream desde la aplicación\n\n`Flow.instances` contiene los FlowStreams cargados por `id`. `send()` inicia un mensaje en una instancia y llama al callback cuando el mensaje termina:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nEl destino puede ser un id de instancia, `@componentid` o `#name` (el nombre del componente). El destino debe definir `instance.message`. Otros métodos:\n\n- `exec({ id, data, repo, timeout }, callback)` envía a todas las instancias que coinciden, con un tiempo límite.\n- `trigger(id, data)` llama a `instance.trigger(data)`.\n- `reconfigure(id, config)` y `variables(variables)` cambian la configuración en tiempo de ejecución.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` y `remove()`.\n- `stats` contiene los contadores de mensajes, mensajes pendientes y errores.\n\n## Guardar los cambios\n\nEl framework lee los archivos `.flow` pero no los escribe. Cuando el diseñador o tu código cambian un FlowStream, `Flow` emite `save` con el esquema completo unos cinco segundos después. Guárdalo tú mismo:\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nUn esquema con `readonly: true` nunca emite `save`. `Flow.on('load', fn)` se ejecuta cuando un FlowStream está listo, y `Flow.onerror` recibe los errores de todos los FlowStreams.\n\n## El diseñador\n\nConecta una ruta WebSocket a un FlowStream con `Flow.socket(id, websocket, [check])`. Protégela, porque el diseñador puede cambiar código:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## Un motor local\n\n`FLOWSTREAM(name)` devuelve el motor sin archivos, workers ni diseñador. Registra componentes con `add()`, crea instancias con `use(design)` y envía datos con `trigger('instanceid__inputid', data)`. La mayoría de las aplicaciones usan `/flowstreams/` y `Flow` en su lugar.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0c1kr61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"FlowStream","summary":"Exécute des graphes de composants à partir de fichiers .flow dans /flowstreams/, écris des composants et travaille avec les messages et les instances FlowStream.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Exécute des graphes de composants à partir de fichiers .flow dans /flowstreams/, écris des composants et travaille avec les messages et les instances FlowStream.\n\nUn **FlowStream** est un graphe de composants reliés par des entrées et des sorties. Les données y circulent sous forme de **messages**. Le module Flow fait partie de Total.js 4 : place des fichiers `.flow` dans `/flowstreams/` et l'application les charge au démarrage. Le designer Flow modifie un FlowStream en cours d'exécution via un WebSocket. La liste exacte des méthodes se trouve dans la référence de [FlowStream](../../reference/flowstream/).\n\n## Le répertoire /flowstreams/\n\nChaque fichier `.flow` est un schéma JSON. Au démarrage de l'application, les fichiers de `/flowstreams/` (et de `plugins/{name}/flowstreams/`) sont transmis à `Flow.load()`. Les noms qui contiennent `-bk` ou `_bk` sont ignorés, ce qui permet de garder des sauvegardes dans le même dossier. En mode debug, un fichier `.flow` modifié redémarre l'application.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` associe un id de composant au code source du composant.\n- `design` associe un id d'instance au composant qu'elle utilise, à sa `config` et à ses `connections`. Une connexion va d'un id de sortie vers `{ id: instance, index: input }`.\n- `variables` sont des valeurs que les composants lisent avec `instance.replace()` ou `$.variables()`.\n- `worker: 'worker'` exécute le FlowStream dans un worker thread, et toute autre valeur vraie (par exemple `'fork'`) dans un processus enfant. Le worker redémarre de lui-même en cas de plantage.\n\nTu peux aussi appeler `Flow.load(schema, callback)` depuis le code. Un schéma avec un `id` déjà chargé met à jour le FlowStream en cours d'exécution.\n\n## Composants\n\nUn composant est un fichier HTML. Son bloc `<script total>` s'exécute sur le serveur ; les autres blocs (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) servent au designer.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` et `exports.outputs` déclarent les ports. Les connexions vers une entrée que le composant ne déclare pas sont supprimées.\n- `exports.config` est la configuration par défaut, fusionnée avec la `config` de chaque instance.\n- `exports.make(instance, config)` s'exécute une fois pour chaque instance du design.\n- `exports.npm` liste les paquets NPM installés avant l'enregistrement du composant.\n\nDans `make`, tu assignes des handlers à l'instance :\n\n| Handler | Quand il s'exécute |\n| --- | --- |\n| `instance.message($)` | Un message est arrivé ; `instance.message_INPUTID($)` pour une seule entrée |\n| `instance.configure(config)` | La configuration a changé |\n| `instance.trigger(data)` | `flowstream.trigger()` ou le bouton du designer |\n| `instance.close(removed)` | L'instance s'arrête ; supprime les timers ici |\n| `instance.init()`, `instance.refresh()` | Après la création du design, et après chaque modification |\n| `instance.variables(variables)` | Les variables ont changé |\n\nEt tu appelles ses méthodes : `instance.send(output, data)`, `instance.status(data, [delay])` et `instance.dashboard(data)` pour le designer, `instance.throw(err)` pour les erreurs, `instance.replace(str)` pour les variables et `instance.save()` pour enregistrer une configuration modifiée.\n\n## Messages\n\n`$` est le message. `$.data` contient ses données. `$.send(output)` le transmet aux instances suivantes et `$.destroy()` le termine. Chaque message doit se terminer de l'une de ces deux façons ; un message envoyé depuis une sortie sans connexion se termine de lui-même.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nQuand un message part vers plusieurs connexions, chacune reçoit sa propre copie de `$.data`, qu'il s'agisse d'objets ou de Buffers (définis `cloning: false` dans le schéma pour désactiver ce comportement). `$.repo` est un objet unique partagé par toutes les copies, utile pour transporter des valeurs le long de la chaîne. `$.on('end', fn)` s'exécute quand la dernière copie se termine ; `$.timeout()` et `$.totaltimeout()` terminent les messages lents avec `$.error = 408`.\n\nUn composant sans entrées démarre lui-même des messages :\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Utiliser un FlowStream depuis l'application\n\n`Flow.instances` contient les FlowStreams chargés, par `id`. `send()` démarre un message dans une instance et appelle le callback quand le message se termine :\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nLa cible peut être un id d'instance, `@componentid` ou `#name` (le nom du composant). La cible doit définir `instance.message`. Autres méthodes :\n\n- `exec({ id, data, repo, timeout }, callback)` envoie à toutes les instances correspondantes, avec un délai d'expiration.\n- `trigger(id, data)` appelle `instance.trigger(data)`.\n- `reconfigure(id, config)` et `variables(variables)` modifient les paramètres à l'exécution.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` et `remove()`.\n- `stats` contient le nombre de messages, de messages en attente et d'erreurs.\n\n## Enregistrer les modifications\n\nLe framework lit les fichiers `.flow` mais ne les écrit pas. Quand le designer ou ton code modifie un FlowStream, `Flow` émet `save` avec le schéma complet environ cinq secondes plus tard. Enregistre-le toi-même :\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nUn schéma avec `readonly: true` n'émet jamais `save`. `Flow.on('load', fn)` s'exécute quand un FlowStream est prêt, et `Flow.onerror` reçoit les erreurs de tous les FlowStreams.\n\n## Le designer\n\nRelie une route WebSocket à un FlowStream avec `Flow.socket(id, websocket, [check])`. Protège-la, car le designer peut modifier du code :\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## Un moteur local\n\n`FLOWSTREAM(name)` renvoie le moteur sans fichiers, sans workers et sans designer. Enregistre des composants avec `add()`, crée des instances avec `use(design)` et envoie des données avec `trigger('instanceid__inputid', data)`. La plupart des applications utilisent plutôt `/flowstreams/` et `Flow`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0c1kr61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"FlowStream","summary":"Esegui grafi di componenti dai file .flow in /flowstreams/, scrivi componenti e lavora con i messaggi e le istanze di FlowStream.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Esegui grafi di componenti dai file .flow in /flowstreams/, scrivi componenti e lavora con i messaggi e le istanze di FlowStream.\n\nUn **FlowStream** è un grafo di componenti collegati tramite input e output. I dati lo attraversano come **messaggi**. Il modulo Flow fa parte di Total.js 4: metti i file `.flow` in `/flowstreams/` e l'app li carica all'avvio. Il designer di Flow modifica un FlowStream in esecuzione tramite un WebSocket. L'elenco esatto dei metodi è nel riferimento di [FlowStream](../../reference/flowstream/).\n\n## La directory /flowstreams/\n\nOgni file `.flow` è uno schema JSON. All'avvio dell'app, i file di `/flowstreams/` (e di `plugins/{name}/flowstreams/`) vengono passati a `Flow.load()`. I nomi che contengono `-bk` o `_bk` vengono ignorati, così i backup possono restare nella stessa cartella. In modalità debug, un file `.flow` modificato riavvia l'app.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` associa l'id di un componente al sorgente del componente.\n- `design` associa l'id di un'istanza al componente che usa, alla sua `config` e alle sue `connections`. Una connessione va dall'id di un output a `{ id: instance, index: input }`.\n- `variables` sono valori che i componenti leggono con `instance.replace()` o `$.variables()`.\n- `worker: 'worker'` esegue il FlowStream in un worker thread e un altro valore truthy (per esempio `'fork'`) in un processo figlio. Il worker si riavvia da solo quando va in crash.\n\nPuoi anche chiamare `Flow.load(schema, callback)` dal codice. Uno schema con un `id` già caricato aggiorna il FlowStream in esecuzione.\n\n## Componenti\n\nUn componente è un file HTML. Il suo blocco `<script total>` viene eseguito sul server; gli altri blocchi (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) servono al designer.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` e `exports.outputs` dichiarano le porte. Le connessioni verso un input che il componente non dichiara vengono rimosse.\n- `exports.config` è la configurazione predefinita, unita alla `config` di ogni istanza.\n- `exports.make(instance, config)` viene eseguito una volta per ogni istanza nel design.\n- `exports.npm` elenca i pacchetti NPM che vengono installati prima che il componente sia registrato.\n\nDentro `make` assegni gli handler all'istanza:\n\n| Handler | Quando viene eseguito |\n| --- | --- |\n| `instance.message($)` | È arrivato un messaggio; `instance.message_INPUTID($)` per un singolo input |\n| `instance.configure(config)` | La configurazione è cambiata |\n| `instance.trigger(data)` | `flowstream.trigger()` o il pulsante del designer |\n| `instance.close(removed)` | L'istanza si ferma; qui cancelli i timer |\n| `instance.init()`, `instance.refresh()` | Dopo la creazione del design e dopo ogni modifica |\n| `instance.variables(variables)` | Le variabili sono cambiate |\n\nE chiami i suoi metodi: `instance.send(output, data)`, `instance.status(data, [delay])` e `instance.dashboard(data)` per il designer, `instance.throw(err)` per gli errori, `instance.replace(str)` per le variabili e `instance.save()` per salvare la configurazione modificata.\n\n## Messaggi\n\n`$` è il messaggio. `$.data` sono i suoi dati. `$.send(output)` lo passa alle istanze successive e `$.destroy()` lo termina. Ogni messaggio deve terminare in uno di questi due modi; un messaggio inviato da un output senza connessioni termina da solo.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nQuando un messaggio va a più connessioni, ognuna riceve la propria copia di `$.data`, sia per gli oggetti sia per i Buffer (imposta `cloning: false` nello schema per disattivarlo). `$.repo` è un unico oggetto condiviso da tutte le copie, utile per portare valori lungo la catena. `$.on('end', fn)` viene eseguito quando termina l'ultima copia; `$.timeout()` e `$.totaltimeout()` terminano i messaggi lenti con `$.error = 408`.\n\nUn componente senza input avvia i messaggi da solo:\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Usare un FlowStream dall'app\n\n`Flow.instances` contiene i FlowStream caricati, per `id`. `send()` avvia un messaggio in un'istanza e richiama la callback quando il messaggio termina:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nLa destinazione può essere l'id di un'istanza, `@componentid` o `#name` (il nome del componente). La destinazione deve definire `instance.message`. Altri metodi:\n\n- `exec({ id, data, repo, timeout }, callback)` invia a tutte le istanze corrispondenti, con un timeout.\n- `trigger(id, data)` chiama `instance.trigger(data)`.\n- `reconfigure(id, config)` e `variables(variables)` cambiano le impostazioni a runtime.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` e `remove()`.\n- `stats` contiene i conteggi dei messaggi, dei messaggi in attesa e degli errori.\n\n## Salvare le modifiche\n\nIl framework legge i file `.flow` ma non li scrive. Quando il designer o il tuo codice modificano un FlowStream, `Flow` emette `save` con lo schema completo circa cinque secondi dopo. Salvalo tu:\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nUno schema con `readonly: true` non emette mai `save`. `Flow.on('load', fn)` viene eseguito quando un FlowStream è pronto, e `Flow.onerror` riceve gli errori di tutti i FlowStream.\n\n## Il designer\n\nCollega una route WebSocket a un FlowStream con `Flow.socket(id, websocket, [check])`. Proteggila, perché il designer può modificare il codice:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## Un motore locale\n\n`FLOWSTREAM(name)` restituisce il motore senza file, worker né designer. Registra i componenti con `add()`, crea le istanze con `use(design)` e invia dati con `trigger('instanceid__inputid', data)`. La maggior parte delle app usa invece `/flowstreams/` e `Flow`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0c1kr61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/flowstream/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"FlowStream","summary":"Spúšťaj grafy komponentov zo súborov .flow v /flowstreams/, píš komponenty a pracuj so správami a inštanciami FlowStream.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Spúšťaj grafy komponentov zo súborov .flow v /flowstreams/, píš komponenty a pracuj so správami a inštanciami FlowStream.\n\n**FlowStream** je graf komponentov prepojených cez vstupy a výstupy. Dáta ním prúdia ako **správy**. Modul Flow je súčasťou Total.js 4: daj súbory `.flow` do `/flowstreams/` a aplikácia ich načíta pri štarte. Dizajnér Flow upravuje bežiaci FlowStream cez WebSocket. Presný zoznam metód nájdeš v referencii [FlowStream](../../reference/flowstream/).\n\n## Adresár /flowstreams/\n\nKaždý súbor `.flow` je JSON schéma. Pri štarte aplikácie sa súbory z `/flowstreams/` (a `plugins/{name}/flowstreams/`) odovzdajú do `Flow.load()`. Názvy, ktoré obsahujú `-bk` alebo `_bk`, sa preskočia, takže zálohy môžu zostať v tom istom priečinku. V režime debug zmena súboru `.flow` reštartuje aplikáciu.\n\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n- `components` mapuje id komponentu na zdrojový kód komponentu.\n- `design` mapuje id inštancie na komponent, ktorý používa, jeho `config` a jeho `connections`. Spojenie vedie z id výstupu do `{ id: instance, index: input }`.\n- `variables` sú hodnoty, ktoré komponenty čítajú cez `instance.replace()` alebo `$.variables()`.\n- `worker: 'worker'` spustí FlowStream vo worker vlákne a iná pravdivá hodnota (napríklad `'fork'`) v podradenom procese. Worker sa po páde sám reštartuje.\n\n`Flow.load(schema, callback)` môžeš zavolať aj z kódu. Schéma s `id`, ktoré je už načítané, aktualizuje bežiaci FlowStream.\n\n## Komponenty\n\nKomponent je HTML súbor. Jeho blok `<script total>` beží na serveri; ostatné bloky (`<readme>`, `<settings>`, `<style>`, `<script>`, `<body>`) sú pre dizajnér.\n\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n- `exports.inputs` a `exports.outputs` deklarujú porty. Spojenia na vstup, ktorý komponent nedeklaruje, sa odstránia.\n- `exports.config` je predvolená konfigurácia, zlúčená s `config` každej inštancie.\n- `exports.make(instance, config)` sa spustí raz pre každú inštanciu v dizajne.\n- `exports.npm` uvádza NPM balíky, ktoré sa nainštalujú pred registráciou komponentu.\n\nVnútri `make` priraďuješ inštancii handlery:\n\n| Handler | Kedy sa spustí |\n| --- | --- |\n| `instance.message($)` | Prišla správa; `instance.message_INPUTID($)` pre jeden vstup |\n| `instance.configure(config)` | Zmenila sa konfigurácia |\n| `instance.trigger(data)` | `flowstream.trigger()` alebo tlačidlo v dizajnéri |\n| `instance.close(removed)` | Inštancia sa zastavuje; tu vyčisti časovače |\n| `instance.init()`, `instance.refresh()` | Po vytvorení dizajnu a po každej zmene |\n| `instance.variables(variables)` | Zmenili sa premenné |\n\nA voláš jej metódy: `instance.send(output, data)`, `instance.status(data, [delay])` a `instance.dashboard(data)` pre dizajnér, `instance.throw(err)` pre chyby, `instance.replace(str)` pre premenné a `instance.save()` na uloženie zmenenej konfigurácie.\n\n## Správy\n\n`$` je správa. `$.data` sú jej dáta. `$.send(output)` ju odovzdá ďalším inštanciám a `$.destroy()` ju ukončí. Každá správa musí skončiť jedným z týchto dvoch spôsobov; správa odoslaná z výstupu bez spojenia skončí sama.\n\n```js\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tconsole.log($.data);\n\t\t$.destroy();\n\t};\n};\n```\n\nKeď správa ide do viacerých spojení, každé dostane vlastnú kópiu `$.data`, objekty aj buffery rovnako (vypneš to nastavením `cloning: false` v schéme). `$.repo` je jeden objekt zdieľaný všetkými kópiami, užitočný na prenášanie hodnôt pozdĺž reťazca. `$.on('end', fn)` sa spustí, keď skončí posledná kópia; `$.timeout()` a `$.totaltimeout()` ukončia pomalé správy s `$.error = 408`.\n\nKomponent bez vstupov spúšťa správy sám:\n\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(() => instance.send('output', { ts: new Date() }), config.interval || 5000);\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n## Použitie FlowStream z aplikácie\n\n`Flow.instances` drží načítané FlowStreamy podľa `id`. `send()` spustí správu v jednej inštancii a zavolá callback, keď správa skončí:\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tFlow.instances.orders.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\nCieľom môže byť id inštancie, `@componentid` alebo `#name` (názov komponentu). Cieľ musí definovať `instance.message`. Ďalšie metódy:\n\n- `exec({ id, data, repo, timeout }, callback)` posiela všetkým zodpovedajúcim inštanciám, s časovým limitom.\n- `trigger(id, data)` zavolá `instance.trigger(data)`.\n- `reconfigure(id, config)` a `variables(variables)` menia nastavenia za behu.\n- `pause([is])`, `export(callback)`, `components(callback)`, `add(id, html)` a `remove()`.\n- `stats` drží počty správ, čakajúcich správ a chýb.\n\n## Ukladanie zmien\n\nFramework súbory `.flow` číta, ale nezapisuje. Keď dizajnér alebo tvoj kód zmení FlowStream, `Flow` asi o päť sekúnd neskôr vyšle `save` s celou schémou. Ulož ju sám:\n\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\nSchéma s `readonly: true` nikdy nevyšle `save`. `Flow.on('load', fn)` sa spustí, keď je FlowStream pripravený, a `Flow.onerror` prijíma chyby všetkých FlowStreamov.\n\n## Dizajnér\n\nPripoj WebSocket trasu k FlowStreamu cez `Flow.socket(id, websocket, [check])`. Chráň ju, pretože dizajnér môže meniť kód:\n\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tclient.user.sa && next();\n\t});\n}\n```\n\n## Lokálny engine\n\n`FLOWSTREAM(name)` vráti engine bez súborov, workerov a dizajnéra. Komponenty registruj cez `add()`, inštancie vytváraj cez `use(design)` a dáta posielaj cez `trigger('instanceid__inputid', data)`. Väčšina aplikácií namiesto toho používa `/flowstreams/` a `Flow`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm8m6Fr60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"QueryBuilder","summary":"Query SQL databases with DATA, DB() and the QueryBuilder, and connect your database with an adapter registered by NEWDB().","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Query SQL databases with DATA, DB() and the QueryBuilder, and connect your database with an adapter registered by NEWDB().\n\nTotal.js 4 has a small, database-neutral **QueryBuilder** for SQL databases. You describe a query with chained methods (`find`, `where`, `sort`, `take`...) and the framework hands a plain description of it to an **adapter** that you register with `NEWDB()`. The adapter turns the description into SQL for your database and returns the rows. The framework itself does not ship an SQL driver: it ships the builder and the contract between the builder and the adapter.\n\n## Register an adapter\n\n`NEWDB([name], fn)` registers the adapter for a connection name. Without a name it is `default`. The name `*` is the fallback for every name that has no adapter of its own.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nThe adapter calls `callback(err, response)` once. The shape of `response` depends on `filter.exec`:\n\n| `exec` | What the adapter returns |\n| --- | --- |\n| `find` | An array of rows |\n| `read`, `check` | An array (the framework keeps the first item, or `null`) or one row |\n| `list` | `{ items: [...], count: Number }`. The framework adds `page`, `limit` and `pages` |\n| `count`, `scalar` | A number or the aggregated value |\n| `insert`, `update`, `remove` | The number of affected rows, or the rows of `returning` |\n| `query`, `command` | Whatever the database returns |\n\nAll fields of `filter` are listed under *Adapter options* in the [reference](../../reference/querybuilder/). Register more databases with names, and pick them with a `name/` prefix in the table name:\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA and DB()\n\nThere are two ways to start a query:\n\n- `DATA` is one global object. Each query you start on it runs on its own, at once. It is the fastest way for single queries.\n- `DB()` (alias `DATABASE()`) creates a new controller. Its queries run **one after another**, and one final callback receives the result. When one query fails, the rest do not run.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nOn a `DB()` controller, `builder.set(name)` stores a response under a key of the final response instead of replacing it:\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nEvery method of `DB()` or `DATA` returns the builder of that query, so chain the filters on it. To add another query, call the controller again.\n\n## Filters\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nEach filter adds an object to `filter.filter`; the adapter decides how to write it in SQL. `where()` accepts the comparers `=`, `<>`, `>`, `<`, `>=` and `<=` (`==` becomes `=`, `!=` becomes `<>`). `sort(name, true)` sorts in descending order; the adapter receives `name_desc`.\n\n## Inserting, updating and removing\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nThe third argument of `update(table, data, true)` is **upsert**. When the update finds nothing, the framework calls the function from `builder.insert(fn)` (for example to add `dtcreated`) and runs the same data again as `insert`.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nHow keys such as `+count` are written in SQL is up to the adapter.\n\n## Raw SQL\n\n`query([conn], sql, [params])` sends your own SQL to the adapter in `filter.query` and the arguments in `filter.params`. `DATA.query(sql, params)` uses the `default` connection when the second argument is an array or an object.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Errors, callbacks and promises\n\n`builder.error(err)` turns an empty result (no row, or an empty array) into an error, a typical way to answer `404`. With `reverse` set to `true` it is the other way round: a found row is the error, which is useful for checks of duplicates.\n\nIn schemas and operations pass `$`: `callback($)` passes the error and the response to `$.callback`, `promise($)` sends an error to `$.invalid()`, and `done($, fn)` calls `fn(response)` only when there is no error.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Lists for grids\n\n`list()` returns one page of rows and the counts that a grid or a pager needs. `paginate(page, limit, maxlimit)` reads the values from the query string, and `autoquery()` builds the fields, filters, sort and paging from the query string by a list of allowed fields:\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` explains how one value of the query string becomes a filter: `10 - 50` is a range, `a,b` is a list, `>10` and `<10` compare, `!text` is an exact match and other text is a search.\n\n## Schema shortcuts\n\n`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` and `$ACTION` do not talk to a database. They run the operations of a schema by its name, and the schema usually calls `DATA` inside. They belong to [Schemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabm8m6Fr60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"QueryBuilder","summary":"Frage SQL-Datenbanken mit DATA, DB() und dem QueryBuilder ab und verbinde deine Datenbank über einen Adapter, der mit NEWDB() registriert wird.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Frage SQL-Datenbanken mit DATA, DB() und dem QueryBuilder ab und verbinde deine Datenbank über einen Adapter, der mit NEWDB() registriert wird.\n\nTotal.js 4 hat einen kleinen, datenbankneutralen **QueryBuilder** für SQL-Datenbanken. Du beschreibst eine Abfrage mit verketteten Methoden (`find`, `where`, `sort`, `take`...), und das Framework übergibt eine einfache Beschreibung davon an einen **Adapter**, den du mit `NEWDB()` registrierst. Der Adapter macht aus der Beschreibung SQL für deine Datenbank und gibt die Zeilen zurück. Das Framework selbst liefert keinen SQL-Treiber: Es liefert den Builder und den Vertrag zwischen Builder und Adapter.\n\n## Einen Adapter registrieren\n\n`NEWDB([name], fn)` registriert den Adapter für einen Verbindungsnamen. Ohne Namen ist es `default`. Der Name `*` ist der Fallback für jeden Namen, der keinen eigenen Adapter hat.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nDer Adapter ruft `callback(err, response)` einmal auf. Die Form von `response` hängt von `filter.exec` ab:\n\n| `exec` | Was der Adapter zurückgibt |\n| --- | --- |\n| `find` | Ein Array von Zeilen |\n| `read`, `check` | Ein Array (das Framework behält das erste Element oder `null`) oder eine Zeile |\n| `list` | `{ items: [...], count: Number }`. Das Framework fügt `page`, `limit` und `pages` hinzu |\n| `count`, `scalar` | Eine Zahl oder der aggregierte Wert |\n| `insert`, `update`, `remove` | Die Anzahl der betroffenen Zeilen oder die Zeilen von `returning` |\n| `query`, `command` | Was auch immer die Datenbank zurückgibt |\n\nAlle Felder von `filter` sind unter *Adapter-Optionen* in der [Referenz](../../reference/querybuilder/) aufgeführt. Registriere weitere Datenbanken mit Namen und wähle sie mit einem Präfix `name/` im Tabellennamen:\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA und DB()\n\nEs gibt zwei Wege, eine Abfrage zu starten:\n\n- `DATA` ist ein globales Objekt. Jede Abfrage, die du darauf startest, läuft für sich, sofort. Das ist der schnellste Weg für einzelne Abfragen.\n- `DB()` (Alias `DATABASE()`) erstellt einen neuen Controller. Seine Abfragen laufen **nacheinander**, und ein abschließender Callback erhält das Ergebnis. Schlägt eine Abfrage fehl, laufen die übrigen nicht.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nAuf einem `DB()`-Controller speichert `builder.set(name)` eine Antwort unter einem Schlüssel der finalen Antwort, statt sie zu ersetzen:\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nJede Methode von `DB()` oder `DATA` gibt den Builder dieser Abfrage zurück, verkette also die Filter darauf. Um eine weitere Abfrage hinzuzufügen, rufe den Controller erneut auf.\n\n## Filter\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nJeder Filter fügt ein Objekt zu `filter.filter` hinzu; der Adapter entscheidet, wie er ihn in SQL schreibt. `where()` akzeptiert die Vergleichsoperatoren `=`, `<>`, `>`, `<`, `>=` und `<=` (`==` wird zu `=`, `!=` wird zu `<>`). `sort(name, true)` sortiert absteigend; der Adapter erhält `name_desc`.\n\n## Einfügen, Aktualisieren und Entfernen\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nDas dritte Argument von `update(table, data, true)` ist **Upsert**. Findet das Update nichts, ruft das Framework die Funktion aus `builder.insert(fn)` auf (zum Beispiel um `dtcreated` hinzuzufügen) und führt dieselben Daten erneut als `insert` aus.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nWie Schlüssel wie `+count` in SQL geschrieben werden, entscheidet der Adapter.\n\n## Rohes SQL\n\n`query([conn], sql, [params])` sendet dein eigenes SQL in `filter.query` und die Argumente in `filter.params` an den Adapter. `DATA.query(sql, params)` verwendet die Verbindung `default`, wenn das zweite Argument ein Array oder ein Objekt ist.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Fehler, Callbacks und Promises\n\n`builder.error(err)` macht aus einem leeren Ergebnis (keine Zeile oder ein leeres Array) einen Fehler, ein typischer Weg, mit `404` zu antworten. Ist `reverse` auf `true` gesetzt, ist es umgekehrt: Eine gefundene Zeile ist der Fehler, was für Prüfungen auf Duplikate nützlich ist.\n\nIn Schemas und Operations übergibst du `$`: `callback($)` übergibt den Fehler und die Antwort an `$.callback`, `promise($)` sendet einen Fehler an `$.invalid()`, und `done($, fn)` ruft `fn(response)` nur auf, wenn es keinen Fehler gibt.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Listen für Grids\n\n`list()` gibt eine Seite von Zeilen und die Zählwerte zurück, die ein Grid oder ein Pager braucht. `paginate(page, limit, maxlimit)` liest die Werte aus dem Query-String, und `autoquery()` baut die Felder, Filter, Sortierung und Seitenaufteilung aus dem Query-String anhand einer Liste erlaubter Felder:\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` erklärt, wie ein Wert des Query-Strings zu einem Filter wird: `10 - 50` ist ein Bereich, `a,b` ist eine Liste, `>10` und `<10` vergleichen, `!text` ist eine exakte Übereinstimmung, und anderer Text ist eine Suche.\n\n## Schema-Kurzformen\n\n`$QUERY`, `$GET` (Alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` und `$ACTION` sprechen nicht mit einer Datenbank. Sie führen die Operations eines Schemas über seinen Namen aus, und das Schema ruft darin meist `DATA` auf. Sie gehören zu [Schemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabm8m6Fr60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"QueryBuilder","summary":"Consulta bases de datos SQL con DATA, DB() y el QueryBuilder, y conecta tu base de datos con un adaptador registrado mediante NEWDB().","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Consulta bases de datos SQL con DATA, DB() y el QueryBuilder, y conecta tu base de datos con un adaptador registrado mediante NEWDB().\n\nTotal.js 4 tiene un **QueryBuilder** pequeño e independiente de la base de datos para bases de datos SQL. Describes una consulta con métodos encadenados (`find`, `where`, `sort`, `take`...) y el framework entrega una descripción simple de ella a un **adaptador** que registras con `NEWDB()`. El adaptador convierte la descripción en SQL para tu base de datos y devuelve las filas. El framework no incluye ningún driver SQL: incluye el builder y el contrato entre el builder y el adaptador.\n\n## Registrar un adaptador\n\n`NEWDB([name], fn)` registra el adaptador para un nombre de conexión. Sin nombre, es `default`. El nombre `*` es el adaptador de reserva para todo nombre que no tenga uno propio.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nEl adaptador llama a `callback(err, response)` una vez. La forma de `response` depende de `filter.exec`:\n\n| `exec` | Qué devuelve el adaptador |\n| --- | --- |\n| `find` | Un array de filas |\n| `read`, `check` | Un array (el framework conserva el primer elemento, o `null`) o una fila |\n| `list` | `{ items: [...], count: Number }`. El framework añade `page`, `limit` y `pages` |\n| `count`, `scalar` | Un número o el valor agregado |\n| `insert`, `update`, `remove` | El número de filas afectadas, o las filas de `returning` |\n| `query`, `command` | Lo que devuelva la base de datos |\n\nTodos los campos de `filter` se enumeran en *Opciones del adaptador* en la [referencia](../../reference/querybuilder/). Registra más bases de datos con nombres y elígelas con un prefijo `name/` en el nombre de la tabla:\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA y DB()\n\nHay dos formas de iniciar una consulta:\n\n- `DATA` es un objeto global. Cada consulta que inicias sobre él se ejecuta por su cuenta, de inmediato. Es la forma más rápida para consultas individuales.\n- `DB()` (alias `DATABASE()`) crea un nuevo controlador. Sus consultas se ejecutan **una tras otra**, y un callback final recibe el resultado. Cuando una consulta falla, las demás no se ejecutan.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nEn un controlador `DB()`, `builder.set(name)` guarda una respuesta bajo una clave de la respuesta final en lugar de reemplazarla:\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nCada método de `DB()` o de `DATA` devuelve el builder de esa consulta, así que encadena los filtros sobre él. Para añadir otra consulta, vuelve a llamar al controlador.\n\n## Filtros\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nCada filtro añade un objeto a `filter.filter`; el adaptador decide cómo escribirlo en SQL. `where()` acepta los comparadores `=`, `<>`, `>`, `<`, `>=` y `<=` (`==` se convierte en `=`, `!=` en `<>`). `sort(name, true)` ordena de forma descendente; el adaptador recibe `name_desc`.\n\n## Insertar, actualizar y eliminar\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nEl tercer argumento de `update(table, data, true)` es **upsert**. Cuando la actualización no encuentra nada, el framework llama a la función de `builder.insert(fn)` (por ejemplo, para añadir `dtcreated`) y vuelve a ejecutar los mismos datos como `insert`.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nCómo se escriben en SQL claves como `+count` depende del adaptador.\n\n## SQL sin procesar\n\n`query([conn], sql, [params])` envía tu propio SQL al adaptador en `filter.query` y los argumentos en `filter.params`. `DATA.query(sql, params)` usa la conexión `default` cuando el segundo argumento es un array o un objeto.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Errores, callbacks y promesas\n\n`builder.error(err)` convierte un resultado vacío (ninguna fila, o un array vacío) en un error, una forma típica de responder `404`. Con `reverse` a `true` es al revés: una fila encontrada es el error, lo cual es útil para comprobar duplicados.\n\nEn esquemas y operaciones pasa `$`: `callback($)` pasa el error y la respuesta a `$.callback`, `promise($)` envía un error a `$.invalid()` y `done($, fn)` llama a `fn(response)` solo cuando no hay error.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Listas para grids\n\n`list()` devuelve una página de filas y los contadores que necesita un grid o un paginador. `paginate(page, limit, maxlimit)` lee los valores de la query string, y `autoquery()` construye los campos, filtros, ordenación y paginación a partir de la query string según una lista de campos permitidos:\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` explica cómo un valor de la query string se convierte en un filtro: `10 - 50` es un rango, `a,b` es una lista, `>10` y `<10` comparan, `!text` es una coincidencia exacta y cualquier otro texto es una búsqueda.\n\n## Atajos de esquema\n\n`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` y `$ACTION` no hablan con una base de datos. Ejecutan las operaciones de un esquema por su nombre, y normalmente el esquema llama a `DATA` dentro. Pertenecen a [Esquemas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabm8m6Fr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"QueryBuilder","summary":"Interroge des bases de données SQL avec DATA, DB() et le QueryBuilder, et connecte ta base de données avec un adaptateur enregistré par NEWDB().","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Interroge des bases de données SQL avec DATA, DB() et le QueryBuilder, et connecte ta base de données avec un adaptateur enregistré par NEWDB().\n\nTotal.js 4 dispose d'un petit **QueryBuilder** pour les bases de données SQL, indépendant de la base utilisée. Tu décris une requête avec des méthodes chaînées (`find`, `where`, `sort`, `take`...) et le framework transmet une simple description de celle-ci à un **adaptateur** que tu enregistres avec `NEWDB()`. L'adaptateur transforme la description en SQL pour ta base de données et renvoie les lignes. Le framework lui-même ne fournit pas de driver SQL : il fournit le builder et le contrat entre le builder et l'adaptateur.\n\n## Enregistrer un adaptateur\n\n`NEWDB([name], fn)` enregistre l'adaptateur pour un nom de connexion. Sans nom, il s'agit de `default`. Le nom `*` sert de solution de repli pour tout nom qui n'a pas son propre adaptateur.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nL'adaptateur appelle `callback(err, response)` une seule fois. La forme de `response` dépend de `filter.exec` :\n\n| `exec` | Ce que renvoie l'adaptateur |\n| --- | --- |\n| `find` | Un tableau de lignes |\n| `read`, `check` | Un tableau (le framework garde le premier élément, ou `null`) ou une ligne |\n| `list` | `{ items: [...], count: Number }`. Le framework ajoute `page`, `limit` et `pages` |\n| `count`, `scalar` | Un nombre ou la valeur agrégée |\n| `insert`, `update`, `remove` | Le nombre de lignes concernées, ou les lignes de `returning` |\n| `query`, `command` | Ce que renvoie la base de données |\n\nTous les champs de `filter` sont listés sous *Options de l'adaptateur* dans la [référence](../../reference/querybuilder/). Enregistre d'autres bases de données avec des noms, et choisis-les avec un préfixe `name/` dans le nom de la table :\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA et DB()\n\nIl existe deux façons de démarrer une requête :\n\n- `DATA` est un objet global unique. Chaque requête que tu y démarres s'exécute seule, immédiatement. C'est le moyen le plus rapide pour des requêtes isolées.\n- `DB()` (alias `DATABASE()`) crée un nouveau contrôleur. Ses requêtes s'exécutent **l'une après l'autre**, et un callback final reçoit le résultat. Quand une requête échoue, les suivantes ne s'exécutent pas.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nSur un contrôleur `DB()`, `builder.set(name)` stocke une réponse sous une clé de la réponse finale au lieu de la remplacer :\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nChaque méthode de `DB()` ou de `DATA` renvoie le builder de cette requête ; enchaîne donc les filtres sur celui-ci. Pour ajouter une autre requête, appelle à nouveau le contrôleur.\n\n## Filtres\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nChaque filtre ajoute un objet à `filter.filter` ; l'adaptateur décide comment l'écrire en SQL. `where()` accepte les comparateurs `=`, `<>`, `>`, `<`, `>=` et `<=` (`==` devient `=`, `!=` devient `<>`). `sort(name, true)` trie par ordre décroissant ; l'adaptateur reçoit `name_desc`.\n\n## Insérer, mettre à jour et supprimer\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nLe troisième argument de `update(table, data, true)` est l'**upsert**. Quand la mise à jour ne trouve rien, le framework appelle la fonction de `builder.insert(fn)` (par exemple pour ajouter `dtcreated`) et exécute à nouveau les mêmes données en tant que `insert`.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nLa façon dont les clés comme `+count` sont écrites en SQL dépend de l'adaptateur.\n\n## SQL brut\n\n`query([conn], sql, [params])` envoie ton propre SQL à l'adaptateur dans `filter.query` et les arguments dans `filter.params`. `DATA.query(sql, params)` utilise la connexion `default` quand le deuxième argument est un tableau ou un objet.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Erreurs, callbacks et promesses\n\n`builder.error(err)` transforme un résultat vide (aucune ligne, ou un tableau vide) en erreur, une façon courante de répondre `404`. Avec `reverse` défini à `true`, c'est l'inverse : une ligne trouvée est l'erreur, ce qui est utile pour vérifier les doublons.\n\nDans les schémas et les opérations, passe `$` : `callback($)` transmet l'erreur et la réponse à `$.callback`, `promise($)` envoie une erreur à `$.invalid()`, et `done($, fn)` n'appelle `fn(response)` que s'il n'y a pas d'erreur.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Listes pour les grilles\n\n`list()` renvoie une page de lignes et les décomptes dont une grille ou un pager a besoin. `paginate(page, limit, maxlimit)` lit les valeurs depuis la query string, et `autoquery()` construit les champs, les filtres, le tri et la pagination à partir de la query string selon une liste de champs autorisés :\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` explique comment une valeur de la query string devient un filtre : `10 - 50` est une plage, `a,b` est une liste, `>10` et `<10` comparent, `!text` est une correspondance exacte et tout autre texte est une recherche.\n\n## Raccourcis de schéma\n\n`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` et `$ACTION` ne communiquent pas avec une base de données. Ils exécutent les opérations d'un schéma par son nom, et le schéma appelle généralement `DATA` en interne. Ils relèvent des [Schémas](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabm8m6Fr60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"QueryBuilder","summary":"Interroga database SQL con DATA, DB() e il QueryBuilder, e collega il tuo database con un adapter registrato da NEWDB().","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Interroga database SQL con DATA, DB() e il QueryBuilder, e collega il tuo database con un adapter registrato da NEWDB().\n\nTotal.js 4 ha un piccolo **QueryBuilder** indipendente dal database per i database SQL. Descrivi una query con metodi concatenati (`find`, `where`, `sort`, `take`...) e il framework ne passa una descrizione semplice a un **adapter** che registri con `NEWDB()`. L'adapter trasforma la descrizione in SQL per il tuo database e restituisce le righe. Il framework in sé non include un driver SQL: include il builder e il contratto tra il builder e l'adapter.\n\n## Registrare un adapter\n\n`NEWDB([name], fn)` registra l'adapter per un nome di connessione. Senza nome è `default`. Il nome `*` è il fallback per ogni nome che non ha un proprio adapter.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nL'adapter chiama `callback(err, response)` una sola volta. La forma di `response` dipende da `filter.exec`:\n\n| `exec` | Cosa restituisce l'adapter |\n| --- | --- |\n| `find` | Un array di righe |\n| `read`, `check` | Un array (il framework tiene il primo elemento, oppure `null`) o una riga |\n| `list` | `{ items: [...], count: Number }`. Il framework aggiunge `page`, `limit` e `pages` |\n| `count`, `scalar` | Un numero o il valore aggregato |\n| `insert`, `update`, `remove` | Il numero di righe interessate, oppure le righe di `returning` |\n| `query`, `command` | Quello che restituisce il database |\n\nTutti i campi di `filter` sono elencati sotto *Opzioni dell'adapter* nel [riferimento](../../reference/querybuilder/). Registra altri database con dei nomi e sceglili con un prefisso `name/` nel nome della tabella:\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA e DB()\n\nCi sono due modi per avviare una query:\n\n- `DATA` è un unico oggetto globale. Ogni query che avvii su di esso viene eseguita da sola, subito. È il modo più veloce per le query singole.\n- `DB()` (alias `DATABASE()`) crea un nuovo controller. Le sue query vengono eseguite **una dopo l'altra**, e un'unica callback finale riceve il risultato. Quando una query fallisce, le altre non vengono eseguite.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nSu un controller `DB()`, `builder.set(name)` salva una risposta sotto una chiave della risposta finale invece di sostituirla:\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nOgni metodo di `DB()` o `DATA` restituisce il builder di quella query, quindi concatena i filtri su di esso. Per aggiungere un'altra query, chiama di nuovo il controller.\n\n## Filtri\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nOgni filtro aggiunge un oggetto a `filter.filter`; è l'adapter a decidere come scriverlo in SQL. `where()` accetta gli operatori di confronto `=`, `<>`, `>`, `<`, `>=` e `<=` (`==` diventa `=`, `!=` diventa `<>`). `sort(name, true)` ordina in modo decrescente; l'adapter riceve `name_desc`.\n\n## Inserire, aggiornare e rimuovere\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nIl terzo argomento di `update(table, data, true)` è l'**upsert**. Quando l'aggiornamento non trova nulla, il framework chiama la funzione di `builder.insert(fn)` (per esempio per aggiungere `dtcreated`) ed esegue di nuovo gli stessi dati come `insert`.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nCome vengono scritte in SQL chiavi come `+count` dipende dall'adapter.\n\n## SQL grezzo\n\n`query([conn], sql, [params])` invia il tuo SQL all'adapter in `filter.query` e gli argomenti in `filter.params`. `DATA.query(sql, params)` usa la connessione `default` quando il secondo argomento è un array o un oggetto.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Errori, callback e promise\n\n`builder.error(err)` trasforma un risultato vuoto (nessuna riga, o un array vuoto) in un errore, un modo tipico per rispondere `404`. Con `reverse` impostato a `true` è il contrario: una riga trovata è l'errore, il che è utile per i controlli dei duplicati.\n\nIn schemi e operazioni passa `$`: `callback($)` passa l'errore e la risposta a `$.callback`, `promise($)` invia un errore a `$.invalid()` e `done($, fn)` chiama `fn(response)` solo quando non c'è alcun errore.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Elenchi per le griglie\n\n`list()` restituisce una pagina di righe e i conteggi di cui ha bisogno una griglia o un paginatore. `paginate(page, limit, maxlimit)` legge i valori dalla query string, e `autoquery()` costruisce i campi, i filtri, l'ordinamento e la paginazione dalla query string in base a un elenco di campi consentiti:\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` spiega come un valore della query string diventa un filtro: `10 - 50` è un intervallo, `a,b` è un elenco, `>10` e `<10` confrontano, `!text` è una corrispondenza esatta e l'altro testo è una ricerca.\n\n## Scorciatoie degli schemi\n\n`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` e `$ACTION` non comunicano con un database. Eseguono le operazioni di uno schema tramite il suo nome, e lo schema di solito chiama `DATA` al suo interno. Fanno parte di [Schemi](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabm8m6Fr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"QueryBuilder","summary":"Dotazuj SQL databázy cez DATA, DB() a QueryBuilder a pripoj svoju databázu cez adaptér zaregistrovaný pomocou NEWDB().","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/querybuilder/\nupdated: 2026-11-19T20:13:36.295Z\n---\n\n# QueryBuilder\n\n> Dotazuj SQL databázy cez DATA, DB() a QueryBuilder a pripoj svoju databázu cez adaptér zaregistrovaný pomocou NEWDB().\n\nTotal.js 4 má malý, na databáze nezávislý **QueryBuilder** pre SQL databázy. Dotaz opíšeš reťazenými metódami (`find`, `where`, `sort`, `take`...) a framework jeho jednoduchý popis odovzdá **adaptéru**, ktorý zaregistruješ cez `NEWDB()`. Adaptér popis premení na SQL pre tvoju databázu a vráti riadky. Samotný framework nedodáva SQL ovládač: dodáva builder a kontrakt medzi builderom a adaptérom.\n\n## Registrácia adaptéra\n\n`NEWDB([name], fn)` zaregistruje adaptér pre názov spojenia. Bez názvu je to `default`. Názov `*` je záloha pre každý názov, ktorý nemá vlastný adaptér.\n\n```js\n// definitions/db.js\nNEWDB(function(filter, callback) {\n\t// filter.exec   'find', 'list', 'read', 'check', 'count', 'scalar', 'insert', 'update', 'remove', 'query', 'command', 'truncate' or 'drop'\n\t// filter.table  the table name\n\t// filter.filter the conditions: [{ type: 'where', name: 'id', comparer: '=', value: 1 }, ...]\n\t// filter.fields, filter.sort, filter.take, filter.skip, filter.payload...\n\tmysqlbuilder(filter, function(err, rows) {\n\t\tcallback(err, rows);\n\t});\n});\n```\n\nAdaptér zavolá `callback(err, response)` raz. Tvar `response` závisí od `filter.exec`:\n\n| `exec` | Čo adaptér vráti |\n| --- | --- |\n| `find` | Pole riadkov |\n| `read`, `check` | Pole (framework si ponechá prvú položku alebo `null`) alebo jeden riadok |\n| `list` | `{ items: [...], count: Number }`. Framework pridá `page`, `limit` a `pages` |\n| `count`, `scalar` | Číslo alebo agregovaná hodnota |\n| `insert`, `update`, `remove` | Počet ovplyvnených riadkov alebo riadky z `returning` |\n| `query`, `command` | Čokoľvek databáza vráti |\n\nVšetky polia `filter` sú uvedené v časti *Voľby adaptéra* v [referencii](../../reference/querybuilder/). Ďalšie databázy zaregistruj s názvami a vyber ich predponou `name/` v názve tabuľky:\n\n```js\nNEWDB('logs', function(filter, callback) { ... });\n\nDATA.find('logs/requests').where('status', 500).callback(console.log);\n```\n\n## DATA a DB()\n\nDotaz môžeš začať dvoma spôsobmi:\n\n- `DATA` je jeden globálny objekt. Každý dotaz, ktorý na ňom začneš, beží samostatne a okamžite. Je to najrýchlejší spôsob pre jednotlivé dotazy.\n- `DB()` (alias `DATABASE()`) vytvorí nový kontrolér. Jeho dotazy bežia **jeden po druhom** a jeden záverečný callback dostane výsledok. Keď jeden dotaz zlyhá, ostatné sa nespustia.\n\n```js\nDATA.read('tbl_user').id(1).callback(function(err, user) {\n\tconsole.log(err, user);\n});\n\nvar db = DB();\ndb.insert('tbl_order', { id: UID(), userid: 1, price: 50 });\ndb.update('tbl_user', { '+orders': 1 }).id(1);\ndb.callback(function(err, response) {\n\t// response is the response of the last query\n});\n```\n\nNa kontroléri `DB()` uloží `builder.set(name)` odpoveď pod kľúč záverečnej odpovede, namiesto toho, aby ju nahradil:\n\n```js\nvar db = DB();\ndb.read('tbl_user').id(1).set('user');\ndb.find('tbl_order').where('userid', 1).set('orders');\ndb.callback(function(err, response) {\n\t// response.user, response.orders\n});\n```\n\nKaždá metóda `DB()` alebo `DATA` vráti builder daného dotazu, takže na ňom reťaz filtre. Ak chceš pridať ďalší dotaz, zavolaj kontrolér znova.\n\n## Filtre\n\n```js\nDATA.find('tbl_product')\n\t.fields('id,name,price')\n\t.where('isremoved', false)\n\t.where('price', '>', 10)\n\t.in('category', ['phones', 'tablets'])\n\t.search('name', 'iphone')\n\t.or(function(builder) {\n\t\tbuilder.where('stock', '>', 0);\n\t\tbuilder.where('ispreorder', true);\n\t})\n\t.sort('price', true)\n\t.take(20)\n\t.callback(console.log);\n```\n\nKaždý filter pridá objekt do `filter.filter`; adaptér rozhodne, ako ho zapísať v SQL. `where()` akceptuje porovnávače `=`, `<>`, `>`, `<`, `>=` a `<=` (`==` sa zmení na `=`, `!=` na `<>`). `sort(name, true)` radí zostupne; adaptér dostane `name_desc`.\n\n## Vkladanie, aktualizácia a odstraňovanie\n\n```js\nDATA.insert('tbl_user', { id: UID(), name: 'Peter', dtcreated: NOW });\n\nDATA.update('tbl_user', { name: 'Lucia', dtupdated: NOW }).id(id).error('404');\n\nDATA.remove('tbl_user').id(id).callback(console.log);\n```\n\nTretí argument `update(table, data, true)` je **upsert**. Keď aktualizácia nič nenájde, framework zavolá funkciu z `builder.insert(fn)` (napríklad na pridanie `dtcreated`) a tie isté dáta spustí znova ako `insert`.\n\n```js\nDATA.update('tbl_counter', { id: 'visits', '+count': 1 }, true).id('visits').insert(function(model) {\n\tmodel.count = 1;\n\tmodel.dtcreated = NOW;\n});\n```\n\nAko sa kľúče ako `+count` zapíšu v SQL, je na adaptéri.\n\n## Surové SQL\n\n`query([conn], sql, [params])` pošle tvoje vlastné SQL adaptéru vo `filter.query` a argumenty vo `filter.params`. `DATA.query(sql, params)` použije spojenie `default`, keď je druhý argument pole alebo objekt.\n\n```js\nDATA.query('SELECT COUNT(1) AS count FROM tbl_user WHERE isremoved=$1', [false]).callback(console.log);\nDATA.query('logs', 'DELETE FROM tbl_request WHERE dtcreated<NOW()').callback(console.log);\n```\n\n## Chyby, callbacky a promises\n\n`builder.error(err)` zmení prázdny výsledok (žiadny riadok alebo prázdne pole) na chybu, čo je typický spôsob, ako odpovedať `404`. S `reverse` nastaveným na `true` je to naopak: nájdený riadok je chyba, čo sa hodí pri kontrolách duplicít.\n\nV schémach a operáciách odovzdaj `$`: `callback($)` odovzdá chybu a odpoveď do `$.callback`, `promise($)` pošle chybu do `$.invalid()` a `done($, fn)` zavolá `fn(response)` len vtedy, keď nenastala chyba.\n\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.setRead(function($) {\n\t\tDATA.read('tbl_user').fields('id,name,email').id($.id).error('404').callback($.callback);\n\t});\n\tschema.setRemove(async function($) {\n\t\tawait DATA.check('tbl_user').id($.id).error('404').promise($);\n\t\tDATA.remove('tbl_user').id($.id).done($, () => $.success());\n\t});\n});\n```\n\n## Zoznamy pre gridy\n\n`list()` vráti jednu stránku riadkov a počty, ktoré potrebuje grid alebo stránkovač. `paginate(page, limit, maxlimit)` číta hodnoty z query stringu a `autoquery()` zostaví polia, filtre, radenie a stránkovanie z query stringu podľa zoznamu povolených polí:\n\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,price:number,dtcreated:date', 'dtcreated_desc', 100).where('isremoved', false).callback($.callback);\n});\n// GET /api/products/?name=phone&price=10 - 50&sort=price_asc&page=2&limit=20\n```\n\n`gridfilter()` vysvetľuje, ako sa jedna hodnota query stringu stane filtrom: `10 - 50` je rozsah, `a,b` je zoznam, `>10` a `<10` porovnávajú, `!text` je presná zhoda a iný text je vyhľadávanie.\n\n## Skratky schém\n\n`$QUERY`, `$GET` (alias `$READ`), `$INSERT`, `$UPDATE`, `$PATCH`, `$SAVE`, `$REMOVE`, `$WORKFLOW`, `$CREATE`, `$MAKE` a `$ACTION` nekomunikujú s databázou. Spúšťajú operácie schémy podľa jej názvu a schéma vnútri zvyčajne volá `DATA`. Patria do [Schém](../../guides/schemas/).\n","entries":[],"license":"MIT","updated":"2026-11-19T20:13:36.295Z"}
{"id":"Jabdgw2sT61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"JSON schemas","summary":"Validate and convert data with JSON schemas: files in jsonschemas/, inline declarations and actions.","markdown":"---\ntitle: JSON schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# JSON schemas\n\n> Validate and convert data with JSON schemas: files in jsonschemas/, inline declarations and actions.\n\nA **JSON schema** describes the shape of a JSON object: its properties, their types and the rules they must follow. Total.js 4 uses JSON schemas to **validate and convert** data: it reads a value, converts each property to its type, drops the properties that the schema does not know, and returns the errors.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nA schema can come from three places: a `.json` file, a `.txt` file with the inline syntax, or code (`NEWJSONSCHEMA()` and `String.toJSONSchema()`). All of them are kept in `F.jsonschemas` under their name.\n\n## The `jsonschemas/` directory\n\nAt start the framework reads the `/jsonschemas/` directory (the `directory_jsonschemas` option), with its subdirectories:\n\n| File | How it is read |\n| --- | --- |\n| `jsonschemas/*.json` | A standard JSON schema object, parsed as JSON |\n| `jsonschemas/*.txt` | The inline syntax (see below), converted with `String.toJSONSchema()` |\n\nThe name of a schema is the file name without the extension (`jsonschemas/users/address.json` gives `users/address`). A `.json` schema with an `$id` is also registered under its `$id`. Files whose names start with `.` or end with `-bk`/`_bk` are skipped. Packages read their own `jsonschemas/` directory.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nA similar schema as `jsonschemas/product.txt`, one property per line (or separated by commas):\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## The inline syntax\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, `.txt` files and the `input`, `output`, `params` and `query` options of actions share one syntax: `name:Type` pairs separated by commas or new lines.\n\n| Syntax | Result |\n| --- | --- |\n| `name` | A string (the default type) |\n| `*name` or `!name` | A required property |\n| `name:String(50)` | A string with `maxLength: 50` |\n| `tags:[String]` | An array of strings; works with any simple type |\n| `role:{admin\\|user}` | A string enum; `;` also separates the values |\n| `address:{street:String, city:String}` | A nested object |\n| `items:[{name:String, qty:Number}]` | An array of nested objects |\n| `owner:@User` | Another schema: a Total.js schema, a JSON schema or the input of an action, looked up in this order |\n\nType names are not case-sensitive. The string types are `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` and `Base64`; each becomes `type: 'string'` with a `subtype`. The number types are `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` and `TinyInt`; each becomes `type: 'number'` with a `subtype`. The other types are `Boolean` (or `Bool`), `Date` and `Object`. An unknown type gives a string.\n\n## Validating data\n\n`JSONSCHEMA(name, value, [callback], [error])` validates a value against a registered schema. Without a callback it returns a promise. An unknown schema gives the error `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nEvery schema object that the framework creates (files and `String.toJSONSchema()`) also has a `transform(value, [partial], [error])` method. It returns `{ error, response }` synchronously, where `error` is an `ErrorBuilder` or `null`:\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nWith `partial` set to `true`, only the properties present in the value are validated, so a missing required property is not an error. Use it for updates.\n\n## What validation does\n\n- **Strings**: other values are converted to strings. `email` and `phone` remove spaces (and `email` is lower-cased) and check the format; `url`, `zip`, `guid`, `uid`, `base64`, `color` and `icon` check the format; `name` normalizes a person's name; `lower`, `upper`, `capitalize` and `capitalize2` change the case. An empty `uid` or `guid` becomes `null`.\n- **Numbers**: a string with digits is parsed with `String.parseFloat()`. `smallint` must be between -32767 and 32767, `tinyint` between 0 and 255.\n- **Booleans**: strings are parsed with `String.parseBoolean()`.\n- **Dates**: other values are parsed with `String.parseDate()`; an invalid date becomes `null`.\n- **Objects**: only the declared `properties` are copied. An object without `properties` is copied as it is.\n- **Arrays**: each item is checked by `items`; invalid items are left out and reported.\n\nAn empty or invalid value of a required property is an error named after the property. Validation does not stop at the first error: all errors are collected.\n\n## JSON schemas in actions\n\nThe `input`, `output`, `params` and `query` options of `schema.action()` and `NEWACTION()` take an inline declaration (any string with `,`, `:` or `*`) or the name of a registered JSON schema (a `.json` suffix is removed). See [Schemas](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` validates the model. It is validated as partial for `PATCH` requests and for actions marked with `#` in a route.\n- `query` and `params` validate `$.query` and `$.params`; their error names get the `query.` and `params.` prefix.\n- `output` converts the response of the action: properties that the schema does not declare are removed. Its errors are ignored.\n\n## Total.js schemas and JSON schemas\n\nA Total.js schema (`NEWSCHEMA()`) can be converted to a JSON schema with `schema.toJSONSchema()`. The result is registered under the schema name, so actions, `JSONSCHEMA()` and `@Name` in inline declarations can use it. `schema.jsonschema_define()` adds fields that exist only in the converted JSON schema.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` and `$MAKE()` work with the Total.js schema itself: `$CREATE()` returns a model with default values and `$MAKE()` makes and validates a model synchronously.\n\nThe Total.js Message Service functions `NEWPUBLISH()`, `NEWSUBSCRIBE()` and `NEWCALL()` take the same forms: an inline declaration, a schema name or a schema object.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdgw2sT61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"JSON-Schemas","summary":"Daten mit JSON-Schemas validieren und konvertieren: Dateien in jsonschemas/, Inline-Deklarationen und Aktionen.","markdown":"---\ntitle: JSON-Schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# JSON-Schemas\n\n> Daten mit JSON-Schemas validieren und konvertieren: Dateien in jsonschemas/, Inline-Deklarationen und Aktionen.\n\nEin **JSON-Schema** beschreibt die Form eines JSON-Objekts: seine Eigenschaften, ihre Typen und die Regeln, denen sie folgen müssen. Total.js 4 nutzt JSON-Schemas, um Daten zu **validieren und zu konvertieren**: Es liest einen Wert, konvertiert jede Eigenschaft in ihren Typ, entfernt die Eigenschaften, die das Schema nicht kennt, und gibt die Fehler zurück.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nEin Schema kann aus drei Quellen stammen: aus einer `.json`-Datei, aus einer `.txt`-Datei mit der Inline-Syntax oder aus Code (`NEWJSONSCHEMA()` und `String.toJSONSchema()`). Alle werden unter ihrem Namen in `F.jsonschemas` abgelegt.\n\n## Das Verzeichnis `jsonschemas/`\n\nBeim Start liest das Framework das Verzeichnis `/jsonschemas/` (die Option `directory_jsonschemas`) samt seinen Unterverzeichnissen:\n\n| Datei | Wie sie gelesen wird |\n| --- | --- |\n| `jsonschemas/*.json` | Ein Standard-JSON-Schema-Objekt, als JSON geparst |\n| `jsonschemas/*.txt` | Die Inline-Syntax (siehe unten), konvertiert mit `String.toJSONSchema()` |\n\nDer Name eines Schemas ist der Dateiname ohne Endung (`jsonschemas/users/address.json` ergibt `users/address`). Ein `.json`-Schema mit `$id` wird zusätzlich unter seiner `$id` registriert. Dateien, deren Name mit `.` beginnt oder auf `-bk`/`_bk` endet, werden übersprungen. Pakete lesen ihr eigenes Verzeichnis `jsonschemas/`.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nEin ähnliches Schema als `jsonschemas/product.txt`, eine Eigenschaft pro Zeile (oder durch Kommas getrennt):\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## Die Inline-Syntax\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, `.txt`-Dateien und die Optionen `input`, `output`, `params` und `query` von Aktionen teilen sich eine Syntax: `name:Type`-Paare, getrennt durch Kommas oder Zeilenumbrüche.\n\n| Syntax | Ergebnis |\n| --- | --- |\n| `name` | Ein String (der Standardtyp) |\n| `*name` oder `!name` | Eine Pflichteigenschaft |\n| `name:String(50)` | Ein String mit `maxLength: 50` |\n| `tags:[String]` | Ein Array von Strings; funktioniert mit jedem einfachen Typ |\n| `role:{admin\\|user}` | Ein String-Enum; `;` trennt die Werte ebenfalls |\n| `address:{street:String, city:String}` | Ein verschachteltes Objekt |\n| `items:[{name:String, qty:Number}]` | Ein Array verschachtelter Objekte |\n| `owner:@User` | Ein anderes Schema: ein Total.js-Schema, ein JSON-Schema oder der Input einer Aktion, in dieser Reihenfolge gesucht |\n\nBei Typnamen wird Groß- und Kleinschreibung nicht unterschieden. Die String-Typen sind `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` und `Base64`; jeder wird zu `type: 'string'` mit einem `subtype`. Die Zahlentypen sind `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` und `TinyInt`; jeder wird zu `type: 'number'` mit einem `subtype`. Die übrigen Typen sind `Boolean` (oder `Bool`), `Date` und `Object`. Ein unbekannter Typ ergibt einen String.\n\n## Daten validieren\n\n`JSONSCHEMA(name, value, [callback], [error])` validiert einen Wert gegen ein registriertes Schema. Ohne Callback gibt es eine Promise zurück. Ein unbekanntes Schema ergibt den Fehler `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nJedes Schema-Objekt, das das Framework erzeugt (aus Dateien und mit `String.toJSONSchema()`), hat außerdem eine Methode `transform(value, [partial], [error])`. Sie gibt synchron `{ error, response }` zurück, wobei `error` ein `ErrorBuilder` oder `null` ist:\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nIst `partial` auf `true` gesetzt, werden nur die im Wert vorhandenen Eigenschaften validiert, sodass eine fehlende Pflichteigenschaft kein Fehler ist. Nutze das für Updates.\n\n## Was die Validierung macht\n\n- **Strings**: Andere Werte werden in Strings konvertiert. `email` und `phone` entfernen Leerzeichen (und `email` wird in Kleinbuchstaben umgewandelt) und prüfen das Format; `url`, `zip`, `guid`, `uid`, `base64`, `color` und `icon` prüfen das Format; `name` normalisiert den Namen einer Person; `lower`, `upper`, `capitalize` und `capitalize2` ändern die Schreibweise. Eine leere `uid` oder `guid` wird zu `null`.\n- **Zahlen**: Ein String mit Ziffern wird mit `String.parseFloat()` geparst. `smallint` muss zwischen -32767 und 32767 liegen, `tinyint` zwischen 0 und 255.\n- **Booleans**: Strings werden mit `String.parseBoolean()` geparst.\n- **Datumswerte**: Andere Werte werden mit `String.parseDate()` geparst; ein ungültiges Datum wird zu `null`.\n- **Objekte**: Nur die deklarierten `properties` werden kopiert. Ein Objekt ohne `properties` wird unverändert kopiert.\n- **Arrays**: Jedes Element wird durch `items` geprüft; ungültige Elemente werden weggelassen und gemeldet.\n\nEin leerer oder ungültiger Wert einer Pflichteigenschaft ist ein Fehler, der nach der Eigenschaft benannt ist. Die Validierung stoppt nicht beim ersten Fehler: Alle Fehler werden gesammelt.\n\n## JSON-Schemas in Aktionen\n\nDie Optionen `input`, `output`, `params` und `query` von `schema.action()` und `NEWACTION()` nehmen eine Inline-Deklaration (jeder String mit `,`, `:` oder `*`) oder den Namen eines registrierten JSON-Schemas (eine Endung `.json` wird entfernt). Siehe [Schemas](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` validiert das Modell. Bei `PATCH`-Requests und bei Aktionen, die in einer Route mit `#` markiert sind, wird es partiell validiert.\n- `query` und `params` validieren `$.query` und `$.params`; ihre Fehlernamen erhalten das Präfix `query.` bzw. `params.`.\n- `output` konvertiert die Antwort der Aktion: Eigenschaften, die das Schema nicht deklariert, werden entfernt. Seine Fehler werden ignoriert.\n\n## Total.js-Schemas und JSON-Schemas\n\nEin Total.js-Schema (`NEWSCHEMA()`) lässt sich mit `schema.toJSONSchema()` in ein JSON-Schema konvertieren. Das Ergebnis wird unter dem Schemanamen registriert, sodass Aktionen, `JSONSCHEMA()` und `@Name` in Inline-Deklarationen es nutzen können. `schema.jsonschema_define()` fügt Felder hinzu, die nur im konvertierten JSON-Schema existieren.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` und `$MAKE()` arbeiten mit dem Total.js-Schema selbst: `$CREATE()` gibt ein Modell mit Standardwerten zurück und `$MAKE()` erstellt und validiert ein Modell synchron.\n\nDie Funktionen des Total.js Message Service `NEWPUBLISH()`, `NEWSUBSCRIBE()` und `NEWCALL()` akzeptieren dieselben Formen: eine Inline-Deklaration, einen Schemanamen oder ein Schema-Objekt.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdgw2sT61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Esquemas JSON","summary":"Valida y convierte datos con esquemas JSON: archivos en jsonschemas/, declaraciones inline y acciones.","markdown":"---\ntitle: Esquemas JSON\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Esquemas JSON\n\n> Valida y convierte datos con esquemas JSON: archivos en jsonschemas/, declaraciones inline y acciones.\n\nUn **esquema JSON** describe la forma de un objeto JSON: sus propiedades, sus tipos y las reglas que deben cumplir. Total.js 4 usa esquemas JSON para **validar y convertir** datos: lee un valor, convierte cada propiedad a su tipo, descarta las propiedades que el esquema no conoce y devuelve los errores.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nUn esquema puede venir de tres sitios: un archivo `.json`, un archivo `.txt` con la sintaxis inline, o código (`NEWJSONSCHEMA()` y `String.toJSONSchema()`). Todos se guardan en `F.jsonschemas` con su nombre.\n\n## El directorio `jsonschemas/`\n\nAl arrancar, el framework lee el directorio `/jsonschemas/` (la opción `directory_jsonschemas`), con sus subdirectorios:\n\n| Archivo | Cómo se lee |\n| --- | --- |\n| `jsonschemas/*.json` | Un objeto de esquema JSON estándar, parseado como JSON |\n| `jsonschemas/*.txt` | La sintaxis inline (ver abajo), convertida con `String.toJSONSchema()` |\n\nEl nombre de un esquema es el nombre del archivo sin la extensión (`jsonschemas/users/address.json` da `users/address`). Un esquema `.json` con `$id` también se registra con su `$id`. Los archivos cuyo nombre empieza por `.` o termina en `-bk`/`_bk` se omiten. Los paquetes leen su propio directorio `jsonschemas/`.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nUn esquema similar como `jsonschemas/product.txt`, una propiedad por línea (o separadas por comas):\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## La sintaxis inline\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, los archivos `.txt` y las opciones `input`, `output`, `params` y `query` de las acciones comparten una sintaxis: pares `name:Type` separados por comas o saltos de línea.\n\n| Sintaxis | Resultado |\n| --- | --- |\n| `name` | Un string (el tipo por defecto) |\n| `*name` o `!name` | Una propiedad obligatoria |\n| `name:String(50)` | Un string con `maxLength: 50` |\n| `tags:[String]` | Un array de strings; funciona con cualquier tipo simple |\n| `role:{admin\\|user}` | Un enum de strings; `;` también separa los valores |\n| `address:{street:String, city:String}` | Un objeto anidado |\n| `items:[{name:String, qty:Number}]` | Un array de objetos anidados |\n| `owner:@User` | Otro esquema: un esquema de Total.js, un esquema JSON o el input de una acción, buscados en este orden |\n\nLos nombres de tipo no distinguen mayúsculas de minúsculas. Los tipos de string son `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` y `Base64`; cada uno se convierte en `type: 'string'` con un `subtype`. Los tipos numéricos son `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` y `TinyInt`; cada uno se convierte en `type: 'number'` con un `subtype`. Los otros tipos son `Boolean` (o `Bool`), `Date` y `Object`. Un tipo desconocido da un string.\n\n## Validar datos\n\n`JSONSCHEMA(name, value, [callback], [error])` valida un valor contra un esquema registrado. Sin callback devuelve una promesa. Un esquema desconocido da el error `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nCada objeto de esquema que crea el framework (archivos y `String.toJSONSchema()`) también tiene un método `transform(value, [partial], [error])`. Devuelve `{ error, response }` de forma síncrona, donde `error` es un `ErrorBuilder` o `null`:\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nCon `partial` en `true`, solo se validan las propiedades presentes en el valor, así que una propiedad obligatoria que falta no es un error. Úsalo para actualizaciones.\n\n## Qué hace la validación\n\n- **Strings**: los otros valores se convierten a string. `email` y `phone` eliminan los espacios (y `email` se pasa a minúsculas) y comprueban el formato; `url`, `zip`, `guid`, `uid`, `base64`, `color` e `icon` comprueban el formato; `name` normaliza el nombre de una persona; `lower`, `upper`, `capitalize` y `capitalize2` cambian las mayúsculas. Un `uid` o `guid` vacío se convierte en `null`.\n- **Números**: un string con dígitos se parsea con `String.parseFloat()`. `smallint` debe estar entre -32767 y 32767, `tinyint` entre 0 y 255.\n- **Booleanos**: los strings se parsean con `String.parseBoolean()`.\n- **Fechas**: los otros valores se parsean con `String.parseDate()`; una fecha no válida se convierte en `null`.\n- **Objetos**: solo se copian las `properties` declaradas. Un objeto sin `properties` se copia tal cual.\n- **Arrays**: cada elemento se comprueba con `items`; los elementos no válidos se descartan y se notifican.\n\nUn valor vacío o no válido de una propiedad obligatoria es un error con el nombre de la propiedad. La validación no se detiene en el primer error: se recogen todos los errores.\n\n## Esquemas JSON en acciones\n\nLas opciones `input`, `output`, `params` y `query` de `schema.action()` y `NEWACTION()` aceptan una declaración inline (cualquier string con `,`, `:` o `*`) o el nombre de un esquema JSON registrado (se elimina el sufijo `.json`). Consulta [Esquemas](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` valida el modelo. Se valida como parcial en las peticiones `PATCH` y en las acciones marcadas con `#` en una ruta.\n- `query` y `params` validan `$.query` y `$.params`; los nombres de sus errores reciben el prefijo `query.` y `params.`.\n- `output` convierte la respuesta de la acción: se eliminan las propiedades que el esquema no declara. Sus errores se ignoran.\n\n## Esquemas de Total.js y esquemas JSON\n\nUn esquema de Total.js (`NEWSCHEMA()`) se puede convertir en un esquema JSON con `schema.toJSONSchema()`. El resultado se registra con el nombre del esquema, así que las acciones, `JSONSCHEMA()` y `@Name` en las declaraciones inline pueden usarlo. `schema.jsonschema_define()` añade campos que solo existen en el esquema JSON convertido.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` y `$MAKE()` trabajan con el propio esquema de Total.js: `$CREATE()` devuelve un modelo con valores por defecto y `$MAKE()` crea y valida un modelo de forma síncrona.\n\nLas funciones de Total.js Message Service `NEWPUBLISH()`, `NEWSUBSCRIBE()` y `NEWCALL()` aceptan las mismas formas: una declaración inline, un nombre de esquema o un objeto de esquema.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdgw2sT61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Schémas JSON","summary":"Valide et convertis des données avec des schémas JSON : fichiers dans jsonschemas/, déclarations inline et actions.","markdown":"---\ntitle: \"Schémas JSON\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Schémas JSON\n\n> Valide et convertis des données avec des schémas JSON : fichiers dans jsonschemas/, déclarations inline et actions.\n\nUn **schéma JSON** décrit la forme d'un objet JSON : ses propriétés, leurs types et les règles qu'elles doivent respecter. Total.js 4 utilise les schémas JSON pour **valider et convertir** des données : il lit une valeur, convertit chaque propriété dans son type, supprime les propriétés que le schéma ne connaît pas et renvoie les erreurs.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nUn schéma peut provenir de trois sources : un fichier `.json`, un fichier `.txt` avec la syntaxe inline, ou du code (`NEWJSONSCHEMA()` et `String.toJSONSchema()`). Tous sont conservés dans `F.jsonschemas` sous leur nom.\n\n## Le répertoire `jsonschemas/`\n\nAu démarrage, le framework lit le répertoire `/jsonschemas/` (l'option `directory_jsonschemas`), avec ses sous-répertoires :\n\n| Fichier | Mode de lecture |\n| --- | --- |\n| `jsonschemas/*.json` | Un objet de schéma JSON standard, analysé comme du JSON |\n| `jsonschemas/*.txt` | La syntaxe inline (voir ci-dessous), convertie avec `String.toJSONSchema()` |\n\nLe nom d'un schéma est le nom du fichier sans l'extension (`jsonschemas/users/address.json` donne `users/address`). Un schéma `.json` doté d'un `$id` est aussi enregistré sous son `$id`. Les fichiers dont le nom commence par `.` ou se termine par `-bk`/`_bk` sont ignorés. Les paquets lisent leur propre répertoire `jsonschemas/`.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nUn schéma similaire sous forme de `jsonschemas/product.txt`, une propriété par ligne (ou séparées par des virgules) :\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## La syntaxe inline\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, les fichiers `.txt` et les options `input`, `output`, `params` et `query` des actions partagent une même syntaxe : des paires `name:Type` séparées par des virgules ou des retours à la ligne.\n\n| Syntaxe | Résultat |\n| --- | --- |\n| `name` | Une chaîne (le type par défaut) |\n| `*name` ou `!name` | Une propriété obligatoire |\n| `name:String(50)` | Une chaîne avec `maxLength: 50` |\n| `tags:[String]` | Un tableau de chaînes ; fonctionne avec n'importe quel type simple |\n| `role:{admin\\|user}` | Une énumération de chaînes ; `;` sépare aussi les valeurs |\n| `address:{street:String, city:String}` | Un objet imbriqué |\n| `items:[{name:String, qty:Number}]` | Un tableau d'objets imbriqués |\n| `owner:@User` | Un autre schéma : un schéma Total.js, un schéma JSON ou l'input d'une action, recherchés dans cet ordre |\n\nLes noms de types ne sont pas sensibles à la casse. Les types chaîne sont `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` et `Base64` ; chacun devient `type: 'string'` avec un `subtype`. Les types numériques sont `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` et `TinyInt` ; chacun devient `type: 'number'` avec un `subtype`. Les autres types sont `Boolean` (ou `Bool`), `Date` et `Object`. Un type inconnu donne une chaîne.\n\n## Valider des données\n\n`JSONSCHEMA(name, value, [callback], [error])` valide une valeur selon un schéma enregistré. Sans callback, elle renvoie une promesse. Un schéma inconnu donne l'erreur `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nChaque objet de schéma créé par le framework (fichiers et `String.toJSONSchema()`) possède aussi une méthode `transform(value, [partial], [error])`. Elle renvoie `{ error, response }` de manière synchrone, où `error` est un `ErrorBuilder` ou `null` :\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nAvec `partial` défini à `true`, seules les propriétés présentes dans la valeur sont validées ; une propriété obligatoire manquante n'est donc pas une erreur. Utilise-le pour les mises à jour.\n\n## Ce que fait la validation\n\n- **Chaînes** : les autres valeurs sont converties en chaînes. `email` et `phone` suppriment les espaces (et `email` est mis en minuscules) et vérifient le format ; `url`, `zip`, `guid`, `uid`, `base64`, `color` et `icon` vérifient le format ; `name` normalise le nom d'une personne ; `lower`, `upper`, `capitalize` et `capitalize2` changent la casse. Un `uid` ou `guid` vide devient `null`.\n- **Nombres** : une chaîne contenant des chiffres est analysée avec `String.parseFloat()`. `smallint` doit être compris entre -32767 et 32767, `tinyint` entre 0 et 255.\n- **Booléens** : les chaînes sont analysées avec `String.parseBoolean()`.\n- **Dates** : les autres valeurs sont analysées avec `String.parseDate()` ; une date invalide devient `null`.\n- **Objets** : seules les `properties` déclarées sont copiées. Un objet sans `properties` est copié tel quel.\n- **Tableaux** : chaque élément est vérifié par `items` ; les éléments invalides sont écartés et signalés.\n\nUne valeur vide ou invalide d'une propriété obligatoire est une erreur portant le nom de la propriété. La validation ne s'arrête pas à la première erreur : toutes les erreurs sont collectées.\n\n## Les schémas JSON dans les actions\n\nLes options `input`, `output`, `params` et `query` de `schema.action()` et `NEWACTION()` acceptent une déclaration inline (toute chaîne contenant `,`, `:` ou `*`) ou le nom d'un schéma JSON enregistré (un suffixe `.json` est supprimé). Voir [Schémas](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` valide le modèle. Il est validé partiellement pour les requêtes `PATCH` et pour les actions marquées avec `#` dans une route.\n- `query` et `params` valident `$.query` et `$.params` ; les noms de leurs erreurs reçoivent le préfixe `query.` et `params.`.\n- `output` convertit la réponse de l'action : les propriétés que le schéma ne déclare pas sont supprimées. Ses erreurs sont ignorées.\n\n## Schémas Total.js et schémas JSON\n\nUn schéma Total.js (`NEWSCHEMA()`) peut être converti en schéma JSON avec `schema.toJSONSchema()`. Le résultat est enregistré sous le nom du schéma ; les actions, `JSONSCHEMA()` et `@Name` dans les déclarations inline peuvent donc l'utiliser. `schema.jsonschema_define()` ajoute des champs qui n'existent que dans le schéma JSON converti.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` et `$MAKE()` travaillent avec le schéma Total.js lui-même : `$CREATE()` renvoie un modèle avec les valeurs par défaut et `$MAKE()` construit et valide un modèle de manière synchrone.\n\nLes fonctions du Total.js Message Service `NEWPUBLISH()`, `NEWSUBSCRIBE()` et `NEWCALL()` acceptent les mêmes formes : une déclaration inline, un nom de schéma ou un objet de schéma.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdgw2sT61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Schemi JSON","summary":"Valida e converti i dati con gli schemi JSON: file in jsonschemas/, dichiarazioni inline e azioni.","markdown":"---\ntitle: Schemi JSON\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Schemi JSON\n\n> Valida e converti i dati con gli schemi JSON: file in jsonschemas/, dichiarazioni inline e azioni.\n\nUno **schema JSON** descrive la forma di un oggetto JSON: le sue proprietà, i loro tipi e le regole che devono rispettare. Total.js 4 usa gli schemi JSON per **validare e convertire** i dati: legge un valore, converte ogni proprietà nel suo tipo, scarta le proprietà che lo schema non conosce e restituisce gli errori.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nUno schema può provenire da tre fonti: un file `.json`, un file `.txt` con la sintassi inline, oppure il codice (`NEWJSONSCHEMA()` e `String.toJSONSchema()`). Tutti vengono conservati in `F.jsonschemas` con il loro nome.\n\n## La directory `jsonschemas/`\n\nAll'avvio il framework legge la directory `/jsonschemas/` (l'opzione `directory_jsonschemas`) con le sue sottodirectory:\n\n| File | Come viene letto |\n| --- | --- |\n| `jsonschemas/*.json` | Un oggetto schema JSON standard, interpretato come JSON |\n| `jsonschemas/*.txt` | La sintassi inline (vedi sotto), convertita con `String.toJSONSchema()` |\n\nIl nome di uno schema è il nome del file senza estensione (`jsonschemas/users/address.json` dà `users/address`). Uno schema `.json` con un `$id` viene registrato anche con il suo `$id`. I file il cui nome inizia con `.` o termina con `-bk`/`_bk` vengono ignorati. I pacchetti leggono la propria directory `jsonschemas/`.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nUno schema simile come `jsonschemas/product.txt`, una proprietà per riga (o separate da virgole):\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## La sintassi inline\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, i file `.txt` e le opzioni `input`, `output`, `params` e `query` delle azioni condividono un'unica sintassi: coppie `name:Type` separate da virgole o da a capo.\n\n| Sintassi | Risultato |\n| --- | --- |\n| `name` | Una stringa (il tipo predefinito) |\n| `*name` o `!name` | Una proprietà obbligatoria |\n| `name:String(50)` | Una stringa con `maxLength: 50` |\n| `tags:[String]` | Un array di stringhe; funziona con qualsiasi tipo semplice |\n| `role:{admin\\|user}` | Un enum di stringhe; anche `;` separa i valori |\n| `address:{street:String, city:String}` | Un oggetto annidato |\n| `items:[{name:String, qty:Number}]` | Un array di oggetti annidati |\n| `owner:@User` | Un altro schema: uno schema Total.js, uno schema JSON o l'input di un'azione, cercati in quest'ordine |\n\nI nomi dei tipi non distinguono tra maiuscole e minuscole. I tipi stringa sono `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` e `Base64`; ognuno diventa `type: 'string'` con un `subtype`. I tipi numerici sono `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` e `TinyInt`; ognuno diventa `type: 'number'` con un `subtype`. Gli altri tipi sono `Boolean` (o `Bool`), `Date` e `Object`. Un tipo sconosciuto dà una stringa.\n\n## Validare i dati\n\n`JSONSCHEMA(name, value, [callback], [error])` valida un valore rispetto a uno schema registrato. Senza callback restituisce una promise. Uno schema sconosciuto dà l'errore `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nOgni oggetto schema creato dal framework (file e `String.toJSONSchema()`) ha anche un metodo `transform(value, [partial], [error])`. Restituisce `{ error, response }` in modo sincrono, dove `error` è un `ErrorBuilder` o `null`:\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nCon `partial` impostato a `true` vengono validate solo le proprietà presenti nel valore, quindi una proprietà obbligatoria mancante non è un errore. Usalo per gli aggiornamenti.\n\n## Cosa fa la validazione\n\n- **Stringhe**: gli altri valori vengono convertiti in stringhe. `email` e `phone` rimuovono gli spazi (e `email` viene convertito in minuscolo) e controllano il formato; `url`, `zip`, `guid`, `uid`, `base64`, `color` e `icon` controllano il formato; `name` normalizza il nome di una persona; `lower`, `upper`, `capitalize` e `capitalize2` cambiano maiuscole e minuscole. Un `uid` o `guid` vuoto diventa `null`.\n- **Numeri**: una stringa con cifre viene interpretata con `String.parseFloat()`. `smallint` deve essere compreso tra -32767 e 32767, `tinyint` tra 0 e 255.\n- **Booleani**: le stringhe vengono interpretate con `String.parseBoolean()`.\n- **Date**: gli altri valori vengono interpretati con `String.parseDate()`; una data non valida diventa `null`.\n- **Oggetti**: vengono copiate solo le `properties` dichiarate. Un oggetto senza `properties` viene copiato così com'è.\n- **Array**: ogni elemento viene controllato da `items`; gli elementi non validi vengono esclusi e segnalati.\n\nUn valore vuoto o non valido di una proprietà obbligatoria è un errore con il nome della proprietà. La validazione non si ferma al primo errore: tutti gli errori vengono raccolti.\n\n## Schemi JSON nelle azioni\n\nLe opzioni `input`, `output`, `params` e `query` di `schema.action()` e `NEWACTION()` accettano una dichiarazione inline (qualsiasi stringa con `,`, `:` o `*`) o il nome di uno schema JSON registrato (il suffisso `.json` viene rimosso). Vedi [Schemi](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` valida il modello. Viene validato come parziale per le richieste `PATCH` e per le azioni contrassegnate con `#` in una route.\n- `query` e `params` validano `$.query` e `$.params`; i nomi dei loro errori ricevono il prefisso `query.` e `params.`.\n- `output` converte la risposta dell'azione: le proprietà che lo schema non dichiara vengono rimosse. I suoi errori vengono ignorati.\n\n## Schemi Total.js e schemi JSON\n\nUno schema Total.js (`NEWSCHEMA()`) può essere convertito in uno schema JSON con `schema.toJSONSchema()`. Il risultato viene registrato con il nome dello schema, così le azioni, `JSONSCHEMA()` e `@Name` nelle dichiarazioni inline possono usarlo. `schema.jsonschema_define()` aggiunge campi che esistono solo nello schema JSON convertito.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` e `$MAKE()` lavorano con lo schema Total.js stesso: `$CREATE()` restituisce un modello con i valori predefiniti e `$MAKE()` crea e valida un modello in modo sincrono.\n\nLe funzioni di Total.js Message Service `NEWPUBLISH()`, `NEWSUBSCRIBE()` e `NEWCALL()` accettano le stesse forme: una dichiarazione inline, il nome di uno schema o un oggetto schema.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdgw2sT61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"JSON schémy","summary":"Validuj a konvertuj dáta pomocou JSON schém: súbory v jsonschemas/, inline deklarácie a akcie.","markdown":"---\ntitle: \"JSON schémy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/json-schemas/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# JSON schémy\n\n> Validuj a konvertuj dáta pomocou JSON schém: súbory v jsonschemas/, inline deklarácie a akcie.\n\n**JSON schéma** opisuje tvar JSON objektu: jeho vlastnosti, ich typy a pravidlá, ktoré musia spĺňať. Total.js 4 používa JSON schémy na **validáciu a konverziu** dát: načíta hodnotu, prevedie každú vlastnosť na jej typ, zahodí vlastnosti, ktoré schéma nepozná, a vráti chyby.\n\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, age:Number');\n\nJSONSCHEMA('Contact', { name: 'Peter', email: ' PETER@example.com', age: '33', admin: true }, function(err, response) {\n\t// err === null\n\t// response === { name: 'Peter', email: 'peter@example.com', age: 33 }\n});\n```\n\nSchéma môže pochádzať z troch miest: zo súboru `.json`, zo súboru `.txt` s inline syntaxou alebo z kódu (`NEWJSONSCHEMA()` a `String.toJSONSchema()`). Všetky sa uchovávajú v `F.jsonschemas` pod svojím názvom.\n\n## Adresár `jsonschemas/`\n\nPri štarte framework načíta adresár `/jsonschemas/` (voľba `directory_jsonschemas`) aj s jeho podadresármi:\n\n| Súbor | Ako sa načíta |\n| --- | --- |\n| `jsonschemas/*.json` | Štandardný objekt JSON schémy, parsovaný ako JSON |\n| `jsonschemas/*.txt` | Inline syntax (pozri nižšie), konvertovaná cez `String.toJSONSchema()` |\n\nNázov schémy je názov súboru bez prípony (`jsonschemas/users/address.json` dá `users/address`). Schéma `.json` s `$id` sa registruje aj pod svojím `$id`. Súbory, ktorých názvy začínajú na `.` alebo končia na `-bk`/`_bk`, sa preskakujú. Balíky načítavajú vlastný adresár `jsonschemas/`.\n\n```json\n{\n\t\"$id\": \"https://example.com/product.json\",\n\t\"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"maxLength\": 100 },\n\t\t\"price\": { \"type\": \"number\", \"minimum\": 0.01 },\n\t\t\"tags\": { \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n\t},\n\t\"required\": [\"name\", \"price\"]\n}\n```\n\nPodobná schéma ako `jsonschemas/product.txt`, jedna vlastnosť na riadok (alebo oddelené čiarkami):\n\n```\n*name:String(100)\n*price:Number\ntags:[String]\n```\n\n## Inline syntax\n\n`String.toJSONSchema()`, `NEWJSONSCHEMA(name, string)`, súbory `.txt` a voľby `input`, `output`, `params` a `query` akcií zdieľajú jednu syntax: dvojice `name:Type` oddelené čiarkami alebo novými riadkami.\n\n| Syntax | Výsledok |\n| --- | --- |\n| `name` | Reťazec (predvolený typ) |\n| `*name` alebo `!name` | Povinná vlastnosť |\n| `name:String(50)` | Reťazec s `maxLength: 50` |\n| `tags:[String]` | Pole reťazcov; funguje s ľubovoľným jednoduchým typom |\n| `role:{admin\\|user}` | Reťazcový enum; hodnoty oddeľuje aj `;` |\n| `address:{street:String, city:String}` | Vnorený objekt |\n| `items:[{name:String, qty:Number}]` | Pole vnorených objektov |\n| `owner:@User` | Iná schéma: Total.js schéma, JSON schéma alebo vstup akcie, hľadané v tomto poradí |\n\nV názvoch typov sa nerozlišujú veľké a malé písmená. Reťazcové typy sú `String`, `UID`, `GUID`, `Email`, `Phone`, `Name`, `URL`, `ZIP`, `Lower`/`Lowercase`, `Upper`/`Uppercase`, `Capitalize`, `Capitalize2`, `Color`, `Icon` a `Base64`; každý sa stane `type: 'string'` so `subtype`. Číselné typy sú `Number`, `Number2`, `Float`, `Decimal`, `Int`/`Integer`, `SmallInt` a `TinyInt`; každý sa stane `type: 'number'` so `subtype`. Ostatné typy sú `Boolean` (alebo `Bool`), `Date` a `Object`. Neznámy typ dá reťazec.\n\n## Validácia dát\n\n`JSONSCHEMA(name, value, [callback], [error])` validuje hodnotu voči registrovanej schéme. Bez callbacku vráti promise. Neznáma schéma dá chybu `404`.\n\n```js\nasync function create() {\n\tvar $ = this;\n\ttry {\n\t\tvar model = await JSONSCHEMA('product', $.body);\n\t\t// model is clean\n\t\t$.success();\n\t} catch (err) {\n\t\t$.invalid(err);\n\t}\n}\n```\n\nKaždý objekt schémy, ktorý framework vytvorí (súbory a `String.toJSONSchema()`), má aj metódu `transform(value, [partial], [error])`. Synchrónne vráti `{ error, response }`, kde `error` je `ErrorBuilder` alebo `null`:\n\n```js\nvar schema = 'name:String, *email:Email'.toJSONSchema('newsletter');\nvar res = schema.transform({ email: 'info@example.com' });\n// res.error === null, res.response.email === 'info@example.com'\n```\n\nKeď je `partial` nastavené na `true`, validujú sa iba vlastnosti prítomné v hodnote, takže chýbajúca povinná vlastnosť nie je chyba. Použi to pri aktualizáciách.\n\n## Čo validácia robí\n\n- **Reťazce**: ostatné hodnoty sa prevedú na reťazce. `email` a `phone` odstránia medzery (a `email` sa prevedie na malé písmená) a skontrolujú formát; `url`, `zip`, `guid`, `uid`, `base64`, `color` a `icon` kontrolujú formát; `name` normalizuje meno osoby; `lower`, `upper`, `capitalize` a `capitalize2` menia veľkosť písmen. Prázdne `uid` alebo `guid` sa stane `null`.\n- **Čísla**: reťazec s číslicami sa parsuje cez `String.parseFloat()`. `smallint` musí byť medzi -32767 a 32767, `tinyint` medzi 0 a 255.\n- **Booleany**: reťazce sa parsujú cez `String.parseBoolean()`.\n- **Dátumy**: ostatné hodnoty sa parsujú cez `String.parseDate()`; neplatný dátum sa stane `null`.\n- **Objekty**: kopírujú sa iba deklarované `properties`. Objekt bez `properties` sa skopíruje tak, ako je.\n- **Polia**: každú položku kontroluje `items`; neplatné položky sa vynechajú a nahlásia.\n\nPrázdna alebo neplatná hodnota povinnej vlastnosti je chyba pomenovaná podľa vlastnosti. Validácia sa nezastaví pri prvej chybe: zbierajú sa všetky chyby.\n\n## JSON schémy v akciách\n\nVoľby `input`, `output`, `params` a `query` v `schema.action()` a `NEWACTION()` prijímajú inline deklaráciu (ľubovoľný reťazec s `,`, `:` alebo `*`) alebo názov registrovanej JSON schémy (prípona `.json` sa odstráni). Pozri [Schémy](../schemas/).\n\n```js\nNEWACTION('Products/create', {\n\tname: 'Create a product',\n\tinput: '*name:String(100), *price:Number, tags:[String]',\n\taction: function($, model) {\n\t\t// model is validated and converted\n\t\t$.success();\n\t}\n});\n\nNEWACTION('Products/update', {\n\tinput: 'product', // jsonschemas/product.json\n\taction: function($, model) {\n\t\t$.success();\n\t}\n});\n```\n\n- `input` validuje model. Pri požiadavkách `PATCH` a pri akciách označených v route znakom `#` sa validuje čiastočne.\n- `query` a `params` validujú `$.query` a `$.params`; názvy ich chýb dostanú prefix `query.` a `params.`.\n- `output` konvertuje odpoveď akcie: vlastnosti, ktoré schéma nedeklaruje, sa odstránia. Jeho chyby sa ignorujú.\n\n## Total.js schémy a JSON schémy\n\nTotal.js schému (`NEWSCHEMA()`) môžeš previesť na JSON schému cez `schema.toJSONSchema()`. Výsledok sa zaregistruje pod názvom schémy, takže ho môžu použiť akcie, `JSONSCHEMA()` aj `@Name` v inline deklaráciách. `schema.jsonschema_define()` pridáva polia, ktoré existujú iba v prevedenej JSON schéme.\n\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID, true);\n\tschema.define('total', Number);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Order').toJSONSchema();\n\tJSONSCHEMA('Order', { id: UID(), total: '25' }).then(console.log);\n});\n```\n\n`$CREATE()` a `$MAKE()` pracujú priamo s Total.js schémou: `$CREATE()` vráti model s predvolenými hodnotami a `$MAKE()` synchrónne vytvorí a zvaliduje model.\n\nFunkcie Total.js Message Service `NEWPUBLISH()`, `NEWSUBSCRIBE()` a `NEWCALL()` prijímajú rovnaké formy: inline deklaráciu, názov schémy alebo objekt schémy.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabdvZ6GR61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Workers, threads and cluster","summary":"Run code in worker threads and child processes, run shell commands, and run the app as a cluster or as separate threads.","markdown":"---\ntitle: Workers, threads and cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Workers, threads and cluster\n\n> Run code in worker threads and child processes, run shell commands, and run the app as a cluster or as separate threads.\n\nA Total.js 4 application runs in one Node.js process by default. When work is too heavy for that process, or when you want to use more CPU cores, the framework gives you four tools:\n\n| Tool | What it starts | Typical use |\n| --- | --- | --- |\n| `NEWTHREAD()` | A `worker_threads` thread from `/workers/` | CPU-heavy code that shares the process |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | A child process from `/workers/` | Isolated jobs, scripts that may crash |\n| `SHELL()` | A shell command | Running system tools (`convert`, `git`, `tar`) |\n| Cluster (`options.cluster`) | Several instances of the whole app | Serving HTTP on more cores |\n\nThe `/threads/` directory is a different feature: it splits one project into several separate apps that run behind the main one (see the last part of this guide).\n\n## The /workers/ directory\n\nWorker scripts live in `/workers/` (the config key `directory_workers`, default `/workers/`). `PATH.workers('resize.js')` returns the full path of a file in it. You pass the name without `.js`. A name that starts with `@` points to a package (`PATH.package()`), and for `NEWTHREAD()` and `NEWFORK()` a name that starts with `~` is an absolute path to the script.\n\n## NEWTHREAD() and NEWFORK()\n\n`NEWTHREAD(name, [data])` runs `/workers/{name}.js` as a Node.js `worker_threads` thread and returns the `Worker`. `data` reaches the thread as `workerData`. `NEWFORK(name)` runs the same kind of file as a child process and returns the `ChildProcess`. Both objects get the same methods, so the calling code does not change when you switch:\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nOn a thread, `kill()` and `exit()` call `terminate()`. On a fork, `postMessage()` is `send()` and `terminate()` sends `SIGTERM`.\n\n## The worker side\n\nInside the worker file, require the framework and call `NEWTHREAD()` (or `NEWFORK()`) **without a name**. It returns a small helper object that works the same in a thread and in a fork:\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Member | What it does |\n| --- | --- |\n| `worker.data` | The `data` of `NEWTHREAD(name, data)`; an empty object in a fork |\n| `worker.message` | Assign a function; it receives every message from the parent |\n| `worker.send(msg)` | Sends a message to the parent (alias `postMessage`) |\n| `worker.exit([code])` | Ends the worker (aliases `kill`, `close`) |\n| `worker.setTimeout(ms)` | Ends the worker with code `1` after `ms` milliseconds |\n\nIf the worker needs your schemas, modules or config, call `LOAD()` in it. `LOAD()` loads parts of the app without starting the HTTP server and sets `isWORKER` to `true`:\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Thread pools\n\n`NEWTHREADPOOL(name, count, [isfork])` starts `count` workers of the same file and lends one to each job. `pool.exec(fn)` calls `fn(worker, release)` when a worker is free. Call `release()` when the job is done, or the worker stays busy:\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nThe pool removes the `message` listeners of a worker before it gives it to the next job.\n\n## WORKER() and WORKER2()\n\n`WORKER(name, [timeout], [args])` is the older way to fork `/workers/{name}.js`. It returns the `ChildProcess`, stores it in `F.workers` while it runs, and kills it with `SIGKILL` when `timeout` (milliseconds) passes. The worker uses `process.on('message')` and `process.send()`, or the helper of `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` runs the script silently, collects its standard output, and calls `callback(err, buffer)` when the process ends. Use it for scripts that print a result.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` runs a command with `child_process.exec()` in the app directory (or `cwd`). The callback gets `(err, stdout, stderr)`. Without a callback it returns a promise of the standard output. The config key `default_shell` chooses the shell:\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nNever put user input into the command without escaping it.\n\n## Cluster\n\nSet `options.cluster` in the start script to run several instances of the whole app behind one port. The value is a number of instances or `'auto'`:\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nThe main (master) process starts the instances one after the other. Each instance gets `F.id` (`'0'`, `'1'`, ...) and `F.isCluster === true`. An instance that exits is started again after one second. With `'auto'`, the master starts one instance, measures their response time every five seconds, adds an instance when the average is over 70 ms (up to `cluster_limit`) and removes the last one when there is free capacity.\n\nIn cluster mode the master sets the time zone of all instances to `options.tz`, or to `'utc'` when you do not set it. Sessions are shared between instances automatically; the cache (`CACHE()`, `F.cache`) only when `allow_cache_cluster` is `true`.\n\nThe master writes its state to `index.js.json` (the start script name plus `.json`) about every 50 seconds. To restart all instances without stopping the app, create an empty file named `restart` in the app directory; the master restarts the instances two seconds apart and deletes the file.\n\n## Messages between instances\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` raises the event `name` in **every** instance, the sender included. Listen with `ON()`:\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\n`EMIT2()` also reaches the other instances (see [Scheduling and events](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` sends an event to the master process only, where `F.cluster.on(name, fn)` registers the listener. The arguments travel as IPC messages, so send only plain, serialisable values.\n\n## The /threads/ directory\n\nSet `options.threads` in the start script, and each subdirectory of `/threads/` becomes its own app in its own process:\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nFor `/threads/users/` the main app forwards every request under `/api/users/` to that thread and removes the prefix, so the thread declares `ROUTE('GET /')` for `/api/users/`. With `options.threads = true` the prefix is only the thread name (`/users/`). The global `THREAD` holds the name inside the thread.\n\nA thread loads every `.js` file of its directory (also in subdirectories) the way it loads controllers, with `exports.install`. It skips the root `/controllers/` and `/middleware/` but loads the other shared directories (schemas, modules, definitions...). It reads its own `config`, `config-debug`, `config-release` and `.env` files from its directory, its views from `views/` and static files from `public/`. With `options.logs = 'isolated'` its output goes to `/threads/{name}/logs/debug.log`. When you also set `options.cluster`, every thread runs as a cluster of that size.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdvZ6GR61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Worker, Threads und Cluster","summary":"Führe Code in Worker-Threads und Kindprozessen aus, führe Shell-Befehle aus und betreibe die App als Cluster oder als getrennte Threads.","markdown":"---\ntitle: Worker, Threads und Cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Worker, Threads und Cluster\n\n> Führe Code in Worker-Threads und Kindprozessen aus, führe Shell-Befehle aus und betreibe die App als Cluster oder als getrennte Threads.\n\nEine Total.js 4-Anwendung läuft standardmäßig in einem einzigen Node.js-Prozess. Wenn die Arbeit für diesen Prozess zu schwer ist oder du mehr CPU-Kerne nutzen willst, gibt dir das Framework vier Werkzeuge:\n\n| Werkzeug | Was es startet | Typische Verwendung |\n| --- | --- | --- |\n| `NEWTHREAD()` | Einen `worker_threads`-Thread aus `/workers/` | CPU-intensiver Code, der sich den Prozess teilt |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | Einen Kindprozess aus `/workers/` | Isolierte Jobs, Skripte, die abstürzen können |\n| `SHELL()` | Einen Shell-Befehl | Systemwerkzeuge ausführen (`convert`, `git`, `tar`) |\n| Cluster (`options.cluster`) | Mehrere Instanzen der ganzen App | HTTP auf mehr Kernen bereitstellen |\n\nDas Verzeichnis `/threads/` ist eine andere Funktion: Es teilt ein Projekt in mehrere getrennte Apps auf, die hinter der Haupt-App laufen (siehe den letzten Teil dieses Leitfadens).\n\n## Das Verzeichnis /workers/\n\nWorker-Skripte liegen in `/workers/` (der Konfigurationsschlüssel `directory_workers`, Standard `/workers/`). `PATH.workers('resize.js')` gibt den vollständigen Pfad einer Datei darin zurück. Du übergibst den Namen ohne `.js`. Ein Name, der mit `@` beginnt, verweist auf ein Paket (`PATH.package()`), und bei `NEWTHREAD()` und `NEWFORK()` ist ein Name, der mit `~` beginnt, ein absoluter Pfad zum Skript.\n\n## NEWTHREAD() und NEWFORK()\n\n`NEWTHREAD(name, [data])` führt `/workers/{name}.js` als Node.js-`worker_threads`-Thread aus und gibt den `Worker` zurück. `data` erreicht den Thread als `workerData`. `NEWFORK(name)` führt dieselbe Art von Datei als Kindprozess aus und gibt den `ChildProcess` zurück. Beide Objekte bekommen dieselben Methoden, sodass sich der aufrufende Code beim Wechsel nicht ändert:\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nBei einem Thread rufen `kill()` und `exit()` die Methode `terminate()` auf. Bei einem Fork ist `postMessage()` gleich `send()`, und `terminate()` sendet `SIGTERM`.\n\n## Die Worker-Seite\n\nLade in der Worker-Datei das Framework mit require und rufe `NEWTHREAD()` (oder `NEWFORK()`) **ohne Namen** auf. Das gibt ein kleines Hilfsobjekt zurück, das in einem Thread und in einem Fork gleich funktioniert:\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Member | Was es tut |\n| --- | --- |\n| `worker.data` | Das `data` aus `NEWTHREAD(name, data)`; in einem Fork ein leeres Objekt |\n| `worker.message` | Weise eine Funktion zu; sie empfängt jede Nachricht des Elternprozesses |\n| `worker.send(msg)` | Sendet eine Nachricht an den Elternprozess (Alias `postMessage`) |\n| `worker.exit([code])` | Beendet den Worker (Aliase `kill`, `close`) |\n| `worker.setTimeout(ms)` | Beendet den Worker nach `ms` Millisekunden mit dem Code `1` |\n\nWenn der Worker deine Schemas, Module oder Konfiguration braucht, rufe darin `LOAD()` auf. `LOAD()` lädt Teile der App, ohne den HTTP-Server zu starten, und setzt `isWORKER` auf `true`:\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Thread-Pools\n\n`NEWTHREADPOOL(name, count, [isfork])` startet `count` Worker derselben Datei und leiht jedem Job einen davon. `pool.exec(fn)` ruft `fn(worker, release)` auf, sobald ein Worker frei ist. Rufe `release()` auf, wenn der Job fertig ist, sonst bleibt der Worker belegt:\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nDer Pool entfernt die `message`-Listener eines Workers, bevor er ihn dem nächsten Job gibt.\n\n## WORKER() und WORKER2()\n\n`WORKER(name, [timeout], [args])` ist der ältere Weg, `/workers/{name}.js` zu forken. Es gibt den `ChildProcess` zurück, speichert ihn während der Laufzeit in `F.workers` und beendet ihn mit `SIGKILL`, wenn `timeout` (Millisekunden) abläuft. Der Worker verwendet `process.on('message')` und `process.send()` oder das Hilfsobjekt von `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` führt das Skript still aus, sammelt seine Standardausgabe und ruft `callback(err, buffer)` auf, wenn der Prozess endet. Verwende es für Skripte, die ein Ergebnis ausgeben.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` führt einen Befehl mit `child_process.exec()` im App-Verzeichnis (oder in `cwd`) aus. Der Callback bekommt `(err, stdout, stderr)`. Ohne Callback gibt es ein Promise der Standardausgabe zurück. Der Konfigurationsschlüssel `default_shell` wählt die Shell:\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nSetze niemals Benutzereingaben ohne Escaping in den Befehl ein.\n\n## Cluster\n\nSetze `options.cluster` im Startskript, um mehrere Instanzen der ganzen App hinter einem Port zu betreiben. Der Wert ist eine Anzahl von Instanzen oder `'auto'`:\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nDer Hauptprozess (Master) startet die Instanzen nacheinander. Jede Instanz bekommt `F.id` (`'0'`, `'1'`, ...) und `F.isCluster === true`. Eine Instanz, die sich beendet, wird nach einer Sekunde neu gestartet. Mit `'auto'` startet der Master eine Instanz, misst alle fünf Sekunden die Antwortzeit der Instanzen, fügt eine Instanz hinzu, wenn der Durchschnitt über 70 ms liegt (bis zu `cluster_limit`), und entfernt die letzte, wenn Kapazität frei ist.\n\nIm Cluster-Modus setzt der Master die Zeitzone aller Instanzen auf `options.tz` oder auf `'utc'`, wenn du sie nicht setzt. Sessions werden automatisch zwischen den Instanzen geteilt; der Cache (`CACHE()`, `F.cache`) nur, wenn `allow_cache_cluster` gleich `true` ist.\n\nDer Master schreibt seinen Zustand etwa alle 50 Sekunden in `index.js.json` (der Name des Startskripts plus `.json`). Um alle Instanzen neu zu starten, ohne die App anzuhalten, erstelle eine leere Datei namens `restart` im App-Verzeichnis; der Master startet die Instanzen im Abstand von zwei Sekunden neu und löscht die Datei.\n\n## Nachrichten zwischen Instanzen\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` löst das Event `name` in **jeder** Instanz aus, auch im Absender. Höre mit `ON()` darauf:\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\n`EMIT2()` erreicht ebenfalls die anderen Instanzen (siehe [Planung und Events](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` sendet ein Event nur an den Master-Prozess, wo `F.cluster.on(name, fn)` den Listener registriert. Die Argumente reisen als IPC-Nachrichten, also sende nur einfache, serialisierbare Werte.\n\n## Das Verzeichnis /threads/\n\nSetze `options.threads` im Startskript, und jedes Unterverzeichnis von `/threads/` wird zu einer eigenen App in einem eigenen Prozess:\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nFür `/threads/users/` leitet die Haupt-App jeden Request unter `/api/users/` an diesen Thread weiter und entfernt das Präfix, sodass der Thread `ROUTE('GET /')` für `/api/users/` deklariert. Mit `options.threads = true` ist das Präfix nur der Name des Threads (`/users/`). Die globale Variable `THREAD` enthält den Namen innerhalb des Threads.\n\nEin Thread lädt jede `.js`-Datei seines Verzeichnisses (auch in Unterverzeichnissen) so, wie er Controller lädt, mit `exports.install`. Er überspringt die Wurzelverzeichnisse `/controllers/` und `/middleware/`, lädt aber die anderen gemeinsamen Verzeichnisse (Schemas, Module, Definitionen...). Er liest seine eigenen Dateien `config`, `config-debug`, `config-release` und `.env` aus seinem Verzeichnis, seine Views aus `views/` und statische Dateien aus `public/`. Mit `options.logs = 'isolated'` geht seine Ausgabe nach `/threads/{name}/logs/debug.log`. Wenn du zusätzlich `options.cluster` setzt, läuft jeder Thread als Cluster dieser Größe.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdvZ6GR61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Workers, hilos y clúster","summary":"Ejecuta código en hilos worker y procesos hijo, ejecuta comandos de shell y ejecuta la app como clúster o como hilos separados.","markdown":"---\ntitle: \"Workers, hilos y clúster\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Workers, hilos y clúster\n\n> Ejecuta código en hilos worker y procesos hijo, ejecuta comandos de shell y ejecuta la app como clúster o como hilos separados.\n\nUna aplicación Total.js 4 se ejecuta por defecto en un solo proceso de Node.js. Cuando el trabajo es demasiado pesado para ese proceso, o cuando quieres usar más núcleos de CPU, el framework te da cuatro herramientas:\n\n| Herramienta | Qué inicia | Uso típico |\n| --- | --- | --- |\n| `NEWTHREAD()` | Un hilo `worker_threads` de `/workers/` | Código que consume mucha CPU y comparte el proceso |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | Un proceso hijo de `/workers/` | Trabajos aislados, scripts que pueden fallar |\n| `SHELL()` | Un comando de shell | Ejecutar herramientas del sistema (`convert`, `git`, `tar`) |\n| Clúster (`options.cluster`) | Varias instancias de toda la app | Servir HTTP en más núcleos |\n\nEl directorio `/threads/` es una función distinta: divide un proyecto en varias apps separadas que se ejecutan detrás de la principal (consulta la última parte de esta guía).\n\n## El directorio /workers/\n\nLos scripts de los workers están en `/workers/` (la clave de configuración `directory_workers`, por defecto `/workers/`). `PATH.workers('resize.js')` devuelve la ruta completa de un archivo de ese directorio. El nombre se pasa sin `.js`. Un nombre que empieza por `@` apunta a un paquete (`PATH.package()`), y en `NEWTHREAD()` y `NEWFORK()` un nombre que empieza por `~` es una ruta absoluta al script.\n\n## NEWTHREAD() y NEWFORK()\n\n`NEWTHREAD(name, [data])` ejecuta `/workers/{name}.js` como hilo `worker_threads` de Node.js y devuelve el `Worker`. `data` llega al hilo como `workerData`. `NEWFORK(name)` ejecuta el mismo tipo de archivo como proceso hijo y devuelve el `ChildProcess`. Ambos objetos tienen los mismos métodos, así que el código que los llama no cambia cuando cambias de uno a otro:\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nEn un hilo, `kill()` y `exit()` llaman a `terminate()`. En un fork, `postMessage()` es `send()` y `terminate()` envía `SIGTERM`.\n\n## El lado del worker\n\nDentro del archivo del worker, carga el framework con require y llama a `NEWTHREAD()` (o `NEWFORK()`) **sin nombre**. Devuelve un pequeño objeto auxiliar que funciona igual en un hilo y en un fork:\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Miembro | Qué hace |\n| --- | --- |\n| `worker.data` | El `data` de `NEWTHREAD(name, data)`; un objeto vacío en un fork |\n| `worker.message` | Asígnale una función; recibe cada mensaje del padre |\n| `worker.send(msg)` | Envía un mensaje al padre (alias `postMessage`) |\n| `worker.exit([code])` | Termina el worker (alias `kill`, `close`) |\n| `worker.setTimeout(ms)` | Termina el worker con el código `1` tras `ms` milisegundos |\n\nSi el worker necesita tus esquemas, módulos o configuración, llama a `LOAD()` en él. `LOAD()` carga partes de la app sin iniciar el servidor HTTP y pone `isWORKER` a `true`:\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Pools de hilos\n\n`NEWTHREADPOOL(name, count, [isfork])` inicia `count` workers del mismo archivo y presta uno a cada trabajo. `pool.exec(fn)` llama a `fn(worker, release)` cuando hay un worker libre. Llama a `release()` cuando el trabajo termine, o el worker seguirá ocupado:\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nEl pool elimina los listeners de `message` de un worker antes de dárselo al siguiente trabajo.\n\n## WORKER() y WORKER2()\n\n`WORKER(name, [timeout], [args])` es la forma antigua de hacer fork de `/workers/{name}.js`. Devuelve el `ChildProcess`, lo guarda en `F.workers` mientras se ejecuta y lo mata con `SIGKILL` cuando pasa `timeout` (milisegundos). El worker usa `process.on('message')` y `process.send()`, o el objeto auxiliar de `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` ejecuta el script en silencio, recoge su salida estándar y llama a `callback(err, buffer)` cuando el proceso termina. Úsalo para scripts que imprimen un resultado.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` ejecuta un comando con `child_process.exec()` en el directorio de la app (o en `cwd`). El callback recibe `(err, stdout, stderr)`. Sin callback devuelve una promesa de la salida estándar. La clave de configuración `default_shell` elige la shell:\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nNunca pongas datos del usuario en el comando sin escaparlos.\n\n## Clúster\n\nDefine `options.cluster` en el script de inicio para ejecutar varias instancias de toda la app detrás de un puerto. El valor es un número de instancias o `'auto'`:\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nEl proceso principal (master) inicia las instancias una tras otra. Cada instancia recibe `F.id` (`'0'`, `'1'`, ...) y `F.isCluster === true`. Una instancia que termina se vuelve a iniciar tras un segundo. Con `'auto'`, el master inicia una instancia, mide su tiempo de respuesta cada cinco segundos, añade una instancia cuando la media supera 70 ms (hasta `cluster_limit`) y elimina la última cuando hay capacidad libre.\n\nEn modo clúster el master establece la zona horaria de todas las instancias a `options.tz`, o a `'utc'` si no la defines. Las sesiones se comparten entre instancias automáticamente; la caché (`CACHE()`, `F.cache`) solo cuando `allow_cache_cluster` es `true`.\n\nEl master escribe su estado en `index.js.json` (el nombre del script de inicio más `.json`) aproximadamente cada 50 segundos. Para reiniciar todas las instancias sin detener la app, crea un archivo vacío llamado `restart` en el directorio de la app; el master reinicia las instancias con dos segundos de diferencia y borra el archivo.\n\n## Mensajes entre instancias\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` lanza el evento `name` en **todas** las instancias, incluida la que lo envía. Escúchalo con `ON()`:\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\n`EMIT2()` también llega a las otras instancias (consulta [Programación y eventos](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` envía un evento solo al proceso master, donde `F.cluster.on(name, fn)` registra el listener. Los argumentos viajan como mensajes IPC, así que envía solo valores simples y serializables.\n\n## El directorio /threads/\n\nDefine `options.threads` en el script de inicio y cada subdirectorio de `/threads/` se convierte en su propia app en su propio proceso:\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nPara `/threads/users/` la app principal reenvía cada petición bajo `/api/users/` a ese hilo y quita el prefijo, así que el hilo declara `ROUTE('GET /')` para `/api/users/`. Con `options.threads = true` el prefijo es solo el nombre del hilo (`/users/`). La variable global `THREAD` contiene el nombre dentro del hilo.\n\nUn hilo carga cada archivo `.js` de su directorio (también en subdirectorios) igual que carga los controladores, con `exports.install`. Omite los directorios raíz `/controllers/` y `/middleware/`, pero carga los demás directorios compartidos (esquemas, módulos, definiciones...). Lee sus propios archivos `config`, `config-debug`, `config-release` y `.env` de su directorio, sus vistas de `views/` y los archivos estáticos de `public/`. Con `options.logs = 'isolated'` su salida va a `/threads/{name}/logs/debug.log`. Si además defines `options.cluster`, cada hilo se ejecuta como un clúster de ese tamaño.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdvZ6GR61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Workers, threads et cluster","summary":"Exécute du code dans des threads workers et des processus enfants, lance des commandes shell, et exécute l'application en cluster ou en threads séparés.","markdown":"---\ntitle: Workers, threads et cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Workers, threads et cluster\n\n> Exécute du code dans des threads workers et des processus enfants, lance des commandes shell, et exécute l'application en cluster ou en threads séparés.\n\nPar défaut, une application Total.js 4 s'exécute dans un seul processus Node.js. Lorsque le travail est trop lourd pour ce processus, ou lorsque tu veux utiliser plus de cœurs CPU, le framework t'offre quatre outils :\n\n| Outil | Ce qu'il démarre | Usage typique |\n| --- | --- | --- |\n| `NEWTHREAD()` | Un thread `worker_threads` depuis `/workers/` | Code gourmand en CPU qui partage le processus |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | Un processus enfant depuis `/workers/` | Tâches isolées, scripts susceptibles de planter |\n| `SHELL()` | Une commande shell | Exécuter des outils système (`convert`, `git`, `tar`) |\n| Cluster (`options.cluster`) | Plusieurs instances de toute l'application | Servir le HTTP sur plus de cœurs |\n\nLe répertoire `/threads/` est une fonctionnalité différente : il divise un projet en plusieurs applications séparées qui s'exécutent derrière l'application principale (voir la dernière partie de ce guide).\n\n## Le répertoire /workers/\n\nLes scripts workers se trouvent dans `/workers/` (la clé de configuration `directory_workers`, par défaut `/workers/`). `PATH.workers('resize.js')` renvoie le chemin complet d'un fichier de ce répertoire. Tu passes le nom sans `.js`. Un nom qui commence par `@` désigne un paquet (`PATH.package()`), et pour `NEWTHREAD()` et `NEWFORK()` un nom qui commence par `~` est un chemin absolu vers le script.\n\n## NEWTHREAD() et NEWFORK()\n\n`NEWTHREAD(name, [data])` exécute `/workers/{name}.js` comme thread `worker_threads` de Node.js et renvoie le `Worker`. `data` arrive dans le thread sous forme de `workerData`. `NEWFORK(name)` exécute le même type de fichier comme processus enfant et renvoie le `ChildProcess`. Les deux objets reçoivent les mêmes méthodes, donc le code appelant ne change pas quand tu passes de l'un à l'autre :\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nSur un thread, `kill()` et `exit()` appellent `terminate()`. Sur un fork, `postMessage()` est `send()` et `terminate()` envoie `SIGTERM`.\n\n## Le côté worker\n\nDans le fichier worker, charge le framework avec require et appelle `NEWTHREAD()` (ou `NEWFORK()`) **sans nom**. Cela renvoie un petit objet utilitaire qui fonctionne de la même façon dans un thread et dans un fork :\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Membre | Ce qu'il fait |\n| --- | --- |\n| `worker.data` | Le `data` de `NEWTHREAD(name, data)` ; un objet vide dans un fork |\n| `worker.message` | Assigne une fonction ; elle reçoit chaque message du parent |\n| `worker.send(msg)` | Envoie un message au parent (alias `postMessage`) |\n| `worker.exit([code])` | Termine le worker (alias `kill`, `close`) |\n| `worker.setTimeout(ms)` | Termine le worker avec le code `1` après `ms` millisecondes |\n\nSi le worker a besoin de tes schémas, modules ou de ta configuration, appelles-y `LOAD()`. `LOAD()` charge des parties de l'application sans démarrer le serveur HTTP et met `isWORKER` à `true` :\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Pools de threads\n\n`NEWTHREADPOOL(name, count, [isfork])` démarre `count` workers du même fichier et en prête un à chaque tâche. `pool.exec(fn)` appelle `fn(worker, release)` lorsqu'un worker est libre. Appelle `release()` quand la tâche est terminée, sinon le worker reste occupé :\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nLe pool supprime les écouteurs `message` d'un worker avant de le confier à la tâche suivante.\n\n## WORKER() et WORKER2()\n\n`WORKER(name, [timeout], [args])` est l'ancienne façon de forker `/workers/{name}.js`. Elle renvoie le `ChildProcess`, le stocke dans `F.workers` pendant son exécution, et le tue avec `SIGKILL` lorsque `timeout` (en millisecondes) est écoulé. Le worker utilise `process.on('message')` et `process.send()`, ou l'utilitaire de `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` exécute le script silencieusement, collecte sa sortie standard et appelle `callback(err, buffer)` lorsque le processus se termine. Utilise-la pour les scripts qui affichent un résultat.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` exécute une commande avec `child_process.exec()` dans le répertoire de l'application (ou `cwd`). Le callback reçoit `(err, stdout, stderr)`. Sans callback, elle renvoie une promesse de la sortie standard. La clé de configuration `default_shell` choisit le shell :\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nNe mets jamais une saisie utilisateur dans la commande sans l'échapper.\n\n## Cluster\n\nDéfinis `options.cluster` dans le script de démarrage pour exécuter plusieurs instances de toute l'application derrière un seul port. La valeur est un nombre d'instances ou `'auto'` :\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nLe processus principal (master) démarre les instances l'une après l'autre. Chaque instance reçoit `F.id` (`'0'`, `'1'`, ...) et `F.isCluster === true`. Une instance qui se termine est redémarrée après une seconde. Avec `'auto'`, le master démarre une instance, mesure leur temps de réponse toutes les cinq secondes, ajoute une instance lorsque la moyenne dépasse 70 ms (jusqu'à `cluster_limit`) et retire la dernière lorsqu'il y a de la capacité libre.\n\nEn mode cluster, le master règle le fuseau horaire de toutes les instances sur `options.tz`, ou sur `'utc'` si tu ne le définis pas. Les sessions sont partagées automatiquement entre les instances ; le cache (`CACHE()`, `F.cache`) seulement lorsque `allow_cache_cluster` vaut `true`.\n\nLe master écrit son état dans `index.js.json` (le nom du script de démarrage suivi de `.json`) environ toutes les 50 secondes. Pour redémarrer toutes les instances sans arrêter l'application, crée un fichier vide nommé `restart` dans le répertoire de l'application ; le master redémarre les instances à deux secondes d'intervalle et supprime le fichier.\n\n## Messages entre instances\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` déclenche l'événement `name` dans **chaque** instance, y compris l'émettrice. Écoute-le avec `ON()` :\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\n`EMIT2()` atteint aussi les autres instances (voir [Planification et événements](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` envoie un événement uniquement au processus master, où `F.cluster.on(name, fn)` enregistre l'écouteur. Les arguments transitent sous forme de messages IPC, n'envoie donc que des valeurs simples et sérialisables.\n\n## Le répertoire /threads/\n\nDéfinis `options.threads` dans le script de démarrage, et chaque sous-répertoire de `/threads/` devient une application à part entière dans son propre processus :\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nPour `/threads/users/`, l'application principale transmet chaque requête sous `/api/users/` à ce thread et retire le préfixe ; le thread déclare donc `ROUTE('GET /')` pour `/api/users/`. Avec `options.threads = true`, le préfixe est uniquement le nom du thread (`/users/`). La variable globale `THREAD` contient le nom à l'intérieur du thread.\n\nUn thread charge chaque fichier `.js` de son répertoire (y compris dans les sous-répertoires) comme il charge les contrôleurs, avec `exports.install`. Il ignore les répertoires racine `/controllers/` et `/middleware/` mais charge les autres répertoires partagés (schémas, modules, définitions...). Il lit ses propres fichiers `config`, `config-debug`, `config-release` et `.env` depuis son répertoire, ses vues depuis `views/` et ses fichiers statiques depuis `public/`. Avec `options.logs = 'isolated'`, sa sortie va dans `/threads/{name}/logs/debug.log`. Si tu définis aussi `options.cluster`, chaque thread s'exécute comme un cluster de cette taille.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdvZ6GR61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Worker, thread e cluster","summary":"Esegui codice in worker thread e processi figli, lancia comandi shell ed esegui l'app come cluster o come thread separati.","markdown":"---\ntitle: Worker, thread e cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Worker, thread e cluster\n\n> Esegui codice in worker thread e processi figli, lancia comandi shell ed esegui l'app come cluster o come thread separati.\n\nUn'applicazione Total.js 4 gira per impostazione predefinita in un solo processo Node.js. Quando il lavoro è troppo pesante per quel processo, o quando vuoi usare più core della CPU, il framework ti offre quattro strumenti:\n\n| Strumento | Cosa avvia | Uso tipico |\n| --- | --- | --- |\n| `NEWTHREAD()` | Un thread `worker_threads` da `/workers/` | Codice pesante per la CPU che condivide il processo |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | Un processo figlio da `/workers/` | Job isolati, script che possono andare in crash |\n| `SHELL()` | Un comando shell | Eseguire strumenti di sistema (`convert`, `git`, `tar`) |\n| Cluster (`options.cluster`) | Più istanze dell'intera app | Servire HTTP su più core |\n\nLa directory `/threads/` è una funzionalità diversa: divide un progetto in più app separate che girano dietro quella principale (vedi l'ultima parte di questa guida).\n\n## La directory /workers/\n\nGli script dei worker si trovano in `/workers/` (la chiave di configurazione `directory_workers`, predefinita `/workers/`). `PATH.workers('resize.js')` restituisce il percorso completo di un file al suo interno. Passi il nome senza `.js`. Un nome che inizia con `@` punta a un pacchetto (`PATH.package()`) e, per `NEWTHREAD()` e `NEWFORK()`, un nome che inizia con `~` è un percorso assoluto dello script.\n\n## NEWTHREAD() e NEWFORK()\n\n`NEWTHREAD(name, [data])` esegue `/workers/{name}.js` come thread `worker_threads` di Node.js e restituisce il `Worker`. `data` arriva al thread come `workerData`. `NEWFORK(name)` esegue lo stesso tipo di file come processo figlio e restituisce il `ChildProcess`. Entrambi gli oggetti hanno gli stessi metodi, quindi il codice chiamante non cambia quando passi dall'uno all'altro:\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nSu un thread, `kill()` ed `exit()` chiamano `terminate()`. Su un fork, `postMessage()` è `send()` e `terminate()` invia `SIGTERM`.\n\n## Il lato worker\n\nNel file del worker, carica il framework con require e chiama `NEWTHREAD()` (o `NEWFORK()`) **senza nome**. Restituisce un piccolo oggetto helper che funziona allo stesso modo in un thread e in un fork:\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Membro | Cosa fa |\n| --- | --- |\n| `worker.data` | Il `data` di `NEWTHREAD(name, data)`; un oggetto vuoto in un fork |\n| `worker.message` | Assegna una funzione; riceve ogni messaggio dal processo padre |\n| `worker.send(msg)` | Invia un messaggio al processo padre (alias `postMessage`) |\n| `worker.exit([code])` | Termina il worker (alias `kill`, `close`) |\n| `worker.setTimeout(ms)` | Termina il worker con codice `1` dopo `ms` millisecondi |\n\nSe il worker ha bisogno dei tuoi schemi, moduli o della configurazione, chiama `LOAD()` al suo interno. `LOAD()` carica parti dell'app senza avviare il server HTTP e imposta `isWORKER` a `true`:\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Pool di thread\n\n`NEWTHREADPOOL(name, count, [isfork])` avvia `count` worker dello stesso file e ne presta uno a ogni job. `pool.exec(fn)` chiama `fn(worker, release)` quando un worker è libero. Chiama `release()` quando il job è terminato, altrimenti il worker resta occupato:\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nIl pool rimuove i listener `message` di un worker prima di assegnarlo al job successivo.\n\n## WORKER() e WORKER2()\n\n`WORKER(name, [timeout], [args])` è il modo più vecchio per fare il fork di `/workers/{name}.js`. Restituisce il `ChildProcess`, lo memorizza in `F.workers` mentre è in esecuzione e lo termina con `SIGKILL` quando scade `timeout` (millisecondi). Il worker usa `process.on('message')` e `process.send()`, oppure l'helper di `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` esegue lo script in modo silenzioso, raccoglie il suo standard output e chiama `callback(err, buffer)` quando il processo termina. Usalo per script che stampano un risultato.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` esegue un comando con `child_process.exec()` nella directory dell'app (o in `cwd`). La callback riceve `(err, stdout, stderr)`. Senza callback restituisce una promise dello standard output. La chiave di configurazione `default_shell` sceglie la shell:\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nNon inserire mai input dell'utente nel comando senza farne l'escape.\n\n## Cluster\n\nImposta `options.cluster` nello script di avvio per eseguire più istanze dell'intera app dietro una sola porta. Il valore è un numero di istanze oppure `'auto'`:\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nIl processo principale (master) avvia le istanze una dopo l'altra. Ogni istanza riceve `F.id` (`'0'`, `'1'`, ...) e `F.isCluster === true`. Un'istanza che termina viene riavviata dopo un secondo. Con `'auto'`, il master avvia un'istanza, misura il loro tempo di risposta ogni cinque secondi, aggiunge un'istanza quando la media supera i 70 ms (fino a `cluster_limit`) e rimuove l'ultima quando c'è capacità libera.\n\nIn modalità cluster il master imposta il fuso orario di tutte le istanze su `options.tz`, oppure su `'utc'` se non lo imposti. Le sessioni sono condivise automaticamente tra le istanze; la cache (`CACHE()`, `F.cache`) solo quando `allow_cache_cluster` è `true`.\n\nIl master scrive il suo stato in `index.js.json` (il nome dello script di avvio più `.json`) circa ogni 50 secondi. Per riavviare tutte le istanze senza fermare l'app, crea un file vuoto chiamato `restart` nella directory dell'app; il master riavvia le istanze a due secondi di distanza l'una dall'altra ed elimina il file.\n\n## Messaggi tra istanze\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` genera l'evento `name` in **ogni** istanza, incluso il mittente. Mettiti in ascolto con `ON()`:\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\nAnche `EMIT2()` raggiunge le altre istanze (vedi [Pianificazione ed eventi](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` invia un evento solo al processo master, dove `F.cluster.on(name, fn)` registra il listener. Gli argomenti viaggiano come messaggi IPC, quindi invia solo valori semplici e serializzabili.\n\n## La directory /threads/\n\nImposta `options.threads` nello script di avvio e ogni sottodirectory di `/threads/` diventa un'app a sé, nel proprio processo:\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nPer `/threads/users/` l'app principale inoltra ogni richiesta sotto `/api/users/` a quel thread e rimuove il prefisso, quindi il thread dichiara `ROUTE('GET /')` per `/api/users/`. Con `options.threads = true` il prefisso è solo il nome del thread (`/users/`). La variabile globale `THREAD` contiene il nome all'interno del thread.\n\nUn thread carica ogni file `.js` della sua directory (anche nelle sottodirectory) nello stesso modo in cui carica i controller, con `exports.install`. Salta le directory `/controllers/` e `/middleware/` della radice, ma carica le altre directory condivise (schemi, moduli, definizioni...). Legge i propri file `config`, `config-debug`, `config-release` e `.env` dalla sua directory, le viste da `views/` e i file statici da `public/`. Con `options.logs = 'isolated'` il suo output va in `/threads/{name}/logs/debug.log`. Se imposti anche `options.cluster`, ogni thread gira come un cluster di quella dimensione.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdvZ6GR61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Workery, vlákna a klaster","summary":"Spúšťaj kód vo worker vláknach a podprocesoch, spúšťaj príkazy shellu a spúšťaj aplikáciu ako klaster alebo ako samostatné vlákna.","markdown":"---\ntitle: \"Workery, vlákna a klaster\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/workers-and-threads/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Workery, vlákna a klaster\n\n> Spúšťaj kód vo worker vláknach a podprocesoch, spúšťaj príkazy shellu a spúšťaj aplikáciu ako klaster alebo ako samostatné vlákna.\n\nAplikácia Total.js 4 predvolene beží v jednom procese Node.js. Keď je práca na tento proces príliš ťažká alebo keď chceš využiť viac jadier CPU, framework ti dáva štyri nástroje:\n\n| Nástroj | Čo spúšťa | Typické použitie |\n| --- | --- | --- |\n| `NEWTHREAD()` | Vlákno `worker_threads` z `/workers/` | Kód náročný na CPU, ktorý zdieľa proces |\n| `NEWFORK()`, `WORKER()`, `WORKER2()` | Podproces z `/workers/` | Izolované úlohy, skripty, ktoré môžu spadnúť |\n| `SHELL()` | Príkaz shellu | Spúšťanie systémových nástrojov (`convert`, `git`, `tar`) |\n| Klaster (`options.cluster`) | Niekoľko inštancií celej aplikácie | Obsluha HTTP na viacerých jadrách |\n\nAdresár `/threads/` je iná funkcia: rozdelí jeden projekt na niekoľko samostatných aplikácií, ktoré bežia za hlavnou aplikáciou (pozri poslednú časť tejto príručky).\n\n## Adresár /workers/\n\nSkripty workerov sú v `/workers/` (konfiguračný kľúč `directory_workers`, predvolene `/workers/`). `PATH.workers('resize.js')` vráti úplnú cestu k súboru v ňom. Názov odovzdávaš bez `.js`. Názov, ktorý začína `@`, odkazuje na balík (`PATH.package()`), a pre `NEWTHREAD()` a `NEWFORK()` je názov, ktorý začína `~`, absolútna cesta ku skriptu.\n\n## NEWTHREAD() a NEWFORK()\n\n`NEWTHREAD(name, [data])` spustí `/workers/{name}.js` ako vlákno Node.js `worker_threads` a vráti `Worker`. `data` sa do vlákna dostanú ako `workerData`. `NEWFORK(name)` spustí rovnaký druh súboru ako podproces a vráti `ChildProcess`. Oba objekty dostanú rovnaké metódy, takže volajúci kód sa pri prepnutí nemení:\n\n```js\nvar worker = NEWTHREAD('resize', { quality: 90 });\n\nworker.on('message', function(msg) {\n\tconsole.log('Done', msg);\n\tworker.kill();\n});\n\nworker.postMessage({ filename: PATH.public('photo.jpg') });\n```\n\nVo vlákne `kill()` a `exit()` volajú `terminate()`. Vo forku je `postMessage()` to isté ako `send()` a `terminate()` pošle `SIGTERM`.\n\n## Strana workera\n\nV súbore workera načítaj framework a zavolaj `NEWTHREAD()` (alebo `NEWFORK()`) **bez názvu**. Vráti malý pomocný objekt, ktorý funguje rovnako vo vlákne aj vo forku:\n\n```js\n// /workers/resize.js\nrequire('total4');\n\nvar worker = NEWTHREAD();\n\nworker.message = function(msg) {\n\t// worker.data contains the \"data\" argument of NEWTHREAD()\n\tworker.send({ filename: msg.filename, quality: worker.data.quality });\n\tworker.exit();\n};\n\n// Kill the worker if it runs longer than 30 seconds\nworker.setTimeout(30000);\n```\n\n| Člen | Čo robí |\n| --- | --- |\n| `worker.data` | `data` z `NEWTHREAD(name, data)`; vo forku prázdny objekt |\n| `worker.message` | Priraď funkciu; dostane každú správu od rodiča |\n| `worker.send(msg)` | Pošle správu rodičovi (alias `postMessage`) |\n| `worker.exit([code])` | Ukončí workera (aliasy `kill`, `close`) |\n| `worker.setTimeout(ms)` | Ukončí workera s kódom `1` po `ms` milisekundách |\n\nAk worker potrebuje tvoje schémy, moduly alebo konfiguráciu, zavolaj v ňom `LOAD()`. `LOAD()` načíta časti aplikácie bez spustenia HTTP servera a nastaví `isWORKER` na `true`:\n\n```js\nrequire('total4');\n\nLOAD('config,modules,schemas', function() {\n\tvar worker = NEWFORK();\n\tworker.message = function(msg) {\n\t\tworker.send(msg);\n\t};\n});\n```\n\n## Pooly vlákien\n\n`NEWTHREADPOOL(name, count, [isfork])` spustí `count` workerov z toho istého súboru a každej úlohe jedného požičia. `pool.exec(fn)` zavolá `fn(worker, release)`, keď je niektorý worker voľný. Keď je úloha hotová, zavolaj `release()`, inak worker zostane obsadený:\n\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n\nfunction resize(filename, callback) {\n\tpool.exec(function(worker, release) {\n\t\tworker.on('message', function(msg) {\n\t\t\trelease();\n\t\t\tcallback(null, msg);\n\t\t});\n\t\tworker.postMessage({ filename: filename });\n\t});\n}\n```\n\nPool odstráni poslucháčov `message` workera predtým, ako ho dá ďalšej úlohe.\n\n## WORKER() a WORKER2()\n\n`WORKER(name, [timeout], [args])` je starší spôsob, ako forknúť `/workers/{name}.js`. Vráti `ChildProcess`, počas behu ho uchováva v `F.workers` a zabije ho signálom `SIGKILL`, keď uplynie `timeout` (v milisekundách). Worker používa `process.on('message')` a `process.send()` alebo pomocný objekt z `NEWFORK()`.\n\n`WORKER2(name, [args], callback, [timeout])` spustí skript potichu, zozbiera jeho štandardný výstup a zavolá `callback(err, buffer)`, keď proces skončí. Použi ho pre skripty, ktoré vypisujú výsledok.\n\n## SHELL()\n\n`SHELL(command, [callback], [cwd])` spustí príkaz cez `child_process.exec()` v adresári aplikácie (alebo v `cwd`). Callback dostane `(err, stdout, stderr)`. Bez callbacku vráti promise so štandardným výstupom. Konfiguračný kľúč `default_shell` určuje shell:\n\n```js\nvar output = await SHELL('git rev-parse HEAD');\n```\n\nNikdy nevkladaj vstup používateľa do príkazu bez escapovania.\n\n## Klaster\n\nNastav `options.cluster` v štartovacom skripte, aby si spustil niekoľko inštancií celej aplikácie za jedným portom. Hodnota je počet inštancií alebo `'auto'`:\n\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\n// options.cluster = 'auto';\n// options.cluster_limit = 8;\n// options.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\nHlavný proces (master) spúšťa inštancie jednu po druhej. Každá inštancia dostane `F.id` (`'0'`, `'1'`, ...) a `F.isCluster === true`. Inštancia, ktorá skončí, sa po jednej sekunde spustí znova. Pri `'auto'` master spustí jednu inštanciu, každých päť sekúnd meria čas odozvy inštancií, pridá inštanciu, keď je priemer nad 70 ms (až do `cluster_limit`), a odstráni poslednú, keď je voľná kapacita.\n\nV režime klastra nastaví master časové pásmo všetkých inštancií na `options.tz` alebo na `'utc'`, keď ho nenastavíš. Relácie sa medzi inštanciami zdieľajú automaticky; cache (`CACHE()`, `F.cache`) len vtedy, keď je `allow_cache_cluster` `true`.\n\nMaster zapisuje svoj stav do `index.js.json` (názov štartovacieho skriptu plus `.json`) približne každých 50 sekúnd. Ak chceš reštartovať všetky inštancie bez zastavenia aplikácie, vytvor v adresári aplikácie prázdny súbor s názvom `restart`; master reštartuje inštancie s odstupom dvoch sekúnd a súbor zmaže.\n\n## Správy medzi inštanciami\n\n`F.cluster.emit(name, [a], [b], [c], [d], [e])` vyvolá udalosť `name` v **každej** inštancii vrátane odosielateľa. Počúvaj cez `ON()`:\n\n```js\nON('products_changed', function(id) {\n\tCACHE('products', null);\n});\n\nF.cluster.emit('products_changed', '123');\n```\n\n`EMIT2()` sa tiež dostane k ostatným inštanciám (pozri [Plánovanie a udalosti](../../guides/scheduling-and-events/)). `F.cluster.master(name, ...)` pošle udalosť len hlavnému procesu, kde poslucháča zaregistruje `F.cluster.on(name, fn)`. Argumenty sa prenášajú ako IPC správy, preto posielaj len jednoduché serializovateľné hodnoty.\n\n## Adresár /threads/\n\nNastav `options.threads` v štartovacom skripte a každý podadresár `/threads/` sa stane samostatnou aplikáciou vo vlastnom procese:\n\n```js\nconst options = {};\noptions.threads = '/api/';\n// options.logs = 'isolated';\nrequire('total4/release')(options);\n```\n\nPre `/threads/users/` hlavná aplikácia prepošle každú požiadavku pod `/api/users/` tomuto vláknu a odstráni prefix, takže vlákno deklaruje `ROUTE('GET /')` pre `/api/users/`. Pri `options.threads = true` je prefix len názov vlákna (`/users/`). Globálna premenná `THREAD` obsahuje vo vlákne jeho názov.\n\nVlákno načíta každý súbor `.js` svojho adresára (aj v podadresároch) tak, ako načítava kontroléry, cez `exports.install`. Preskočí koreňové `/controllers/` a `/middleware/`, ale načíta ostatné zdieľané adresáre (schémy, moduly, definície...). Číta vlastné súbory `config`, `config-debug`, `config-release` a `.env` zo svojho adresára, view z `views/` a statické súbory z `public/`. Pri `options.logs = 'isolated'` ide jeho výstup do `/threads/{name}/logs/debug.log`. Keď nastavíš aj `options.cluster`, každé vlákno beží ako klaster tejto veľkosti.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Message Service and APIs","summary":"Publish, receive and call over the Total.js Message Service, connect with TMSCLIENT(), call APIs with API() and NEWAPI(), and expose API routes.","markdown":"---\ntitle: Message Service and APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service and APIs\n\n> Publish, receive and call over the Total.js Message Service, connect with TMSCLIENT(), call APIs with API() and NEWAPI(), and expose API routes.\n\nTotal.js 4 has two ways to connect your app with other services:\n\n- the **Total.js Message Service (TMS)**, a WebSocket endpoint where your app publishes messages, receives messages and answers remote calls, all described by JSON schemas;\n- **APIs**, a small layer that sends named requests to an API provider you register with `NEWAPI()` (Total API is registered by default).\n\nThe same app can also expose its own **API routes**, one URL that runs many actions chosen by name.\n\n## Turning TMS on\n\nTMS is off by default. Enable it in `/config`:\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nThe endpoint is `default_tms_url` (`/$tms/`); `default_tms_maxlength` sets the maximum size of a message in kB (default `1024`). With `secret_tms`, a client must send the token in the `x-token` header. A wrong token closes the connection with code `4001`, and an IP address with more than five failed attempts is refused until the daily reset. Without `secret_tms`, every client is accepted. See [Configuration](../../guides/configuration/) for the other options.\n\n## Publishing messages\n\nA publish channel tells the clients which messages your app sends and how they look. Declare it with `NEWPUBLISH(name, schema)` and send messages with `PUBLISH(name, data)`:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nThe schema can be an inline declaration (`'id:UID, total:Number'`), a JSON schema object with an `$id`, or the name of a JSON schema or a Total.js schema. A name that does not exist throws an error.\n\n`PUBLISH()` sends the message only to connected clients that subscribed to the channel. With no TMS client connected, or for a channel not declared with `NEWPUBLISH()`, it does nothing. The data is not validated on the server: the client converts it with the schema from the channel.\n\n## Receiving messages\n\nA subscribe channel is the other direction: clients send messages and your app handles them. `NEWSUBSCRIBE(name, schema, [callback])` declares the channel and `SUBSCRIBE(name, callback)` adds handlers:\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nEvery incoming message is validated with the channel's schema; invalid messages are dropped. A handler receives the validated data and the WebSocket client. `UNSUBSCRIBE(name, [callback])` removes one handler, or all of them.\n\n## Remote calls\n\n`NEWCALL(name, schema, callback)` registers a call that clients run like a remote procedure. The data is validated first; the callback answers with `next(err, response)`:\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Automatic synchronization\n\nWhen you add or remove channels, calls or handlers, the app sends a fresh `meta` message to all clients one second later. The meta lists the app `name`, the `publish`, `subscribe` and `call` channels with their JSON schemas, and the channels your app subscribes to.\n\n## Publishing from actions\n\n`schema.action()` and `NEWACTION()` accept a `publish` option. It declares a publish channel named after the action (`Schema.action`, or the action name), and `$.publish(value)` in the action sends to it:\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` uses the action's `input` (or `output`) as the channel schema. A string sets its own schema; a string that starts with `+` adds fields to the input.\n\n## Connecting to TMS: TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` connects your app to the TMS endpoint of another Total.js app. It reconnects after the server restarts, and it resubscribes automatically:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` receives messages of the server's publish channels, converted by their schema. `client.publish()` sends to the server's subscribe channels. `client.call()` runs a remote call; without a callback it returns a promise, and it fails with `TMS is offline` before the connection is ready or `408: Timeout` after 10 seconds.\n\n## APIs: NEWAPI() and API()\n\n`API(name, schema, [data])` sends a request to a registered API provider and returns a call object. You chain options and a callback; the request starts on the next tick:\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` registers your own provider. The callback receives `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) and `next(err, response)`. The name `*` registers a fallback for every unknown name:\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nNames are not case-sensitive. The built-in provider `TotalAPI` (alias `TAPI`) posts to Total API with the token from `totalapi`; the older `TotalAPI(type, data, callback)` function does the same in one call.\n\n## API routes\n\nAn API route is one `POST` URL that runs many actions. The client sends `{ \"schema\": \"name/param?query\", \"data\": { ... } }`:\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nThe sign before the name sets the HTTP method used for the action: `+` validates the data like `POST`, `#` like `PATCH`, `-` sends no data like `GET`. URL parameters follow the name. A function instead of `*Schema --> action` handles the call with the controller as `this`. The whole route syntax is in [Routing](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Message Service und APIs","summary":"Über den Total.js Message Service veröffentlichen, empfangen und aufrufen, mit TMSCLIENT() verbinden, APIs mit API() und NEWAPI() aufrufen und API-Routen bereitstellen.","markdown":"---\ntitle: Message Service und APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service und APIs\n\n> Über den Total.js Message Service veröffentlichen, empfangen und aufrufen, mit TMSCLIENT() verbinden, APIs mit API() und NEWAPI() aufrufen und API-Routen bereitstellen.\n\nTotal.js 4 bietet zwei Wege, deine App mit anderen Diensten zu verbinden:\n\n- den **Total.js Message Service (TMS)**, einen WebSocket-Endpunkt, an dem deine App Nachrichten veröffentlicht, Nachrichten empfängt und Remote-Aufrufe beantwortet, alles beschrieben durch JSON-Schemas;\n- **APIs**, eine kleine Schicht, die benannte Anfragen an einen API-Provider sendet, den du mit `NEWAPI()` registrierst (Total API ist standardmäßig registriert).\n\nDieselbe App kann außerdem eigene **API-Routen** bereitstellen: eine URL, die viele nach Namen ausgewählte Aktionen ausführt.\n\n## TMS einschalten\n\nTMS ist standardmäßig ausgeschaltet. Aktiviere es in `/config`:\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nDer Endpunkt ist `default_tms_url` (`/$tms/`); `default_tms_maxlength` legt die maximale Größe einer Nachricht in kB fest (Standard `1024`). Mit `secret_tms` muss ein Client das Token im Header `x-token` senden. Ein falsches Token schließt die Verbindung mit dem Code `4001`, und eine IP-Adresse mit mehr als fünf fehlgeschlagenen Versuchen wird bis zum täglichen Zurücksetzen abgewiesen. Ohne `secret_tms` wird jeder Client akzeptiert. Die anderen Optionen findest du unter [Konfiguration](../../guides/configuration/).\n\n## Nachrichten veröffentlichen\n\nEin Publish-Kanal teilt den Clients mit, welche Nachrichten deine App sendet und wie sie aussehen. Deklariere ihn mit `NEWPUBLISH(name, schema)` und sende Nachrichten mit `PUBLISH(name, data)`:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nDas Schema kann eine Inline-Deklaration (`'id:UID, total:Number'`), ein JSON-Schema-Objekt mit einer `$id` oder der Name eines JSON-Schemas oder eines Total.js-Schemas sein. Ein Name, der nicht existiert, löst einen Fehler aus.\n\n`PUBLISH()` sendet die Nachricht nur an verbundene Clients, die den Kanal abonniert haben. Ist kein TMS-Client verbunden oder wurde der Kanal nicht mit `NEWPUBLISH()` deklariert, passiert nichts. Die Daten werden auf dem Server nicht validiert: Der Client konvertiert sie mit dem Schema des Kanals.\n\n## Nachrichten empfangen\n\nEin Subscribe-Kanal ist die andere Richtung: Clients senden Nachrichten, und deine App verarbeitet sie. `NEWSUBSCRIBE(name, schema, [callback])` deklariert den Kanal, und `SUBSCRIBE(name, callback)` fügt Handler hinzu:\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nJede eingehende Nachricht wird mit dem Schema des Kanals validiert; ungültige Nachrichten werden verworfen. Ein Handler erhält die validierten Daten und den WebSocket-Client. `UNSUBSCRIBE(name, [callback])` entfernt einen Handler oder alle.\n\n## Remote-Aufrufe\n\n`NEWCALL(name, schema, callback)` registriert einen Aufruf, den Clients wie eine entfernte Prozedur ausführen. Die Daten werden zuerst validiert; der Callback antwortet mit `next(err, response)`:\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Automatische Synchronisierung\n\nWenn du Kanäle, Aufrufe oder Handler hinzufügst oder entfernst, sendet die App eine Sekunde später eine neue `meta`-Nachricht an alle Clients. Die Meta-Nachricht enthält den `name` der App, die Kanäle `publish`, `subscribe` und `call` mit ihren JSON-Schemas sowie die Kanäle, die deine App abonniert.\n\n## Aus Aktionen veröffentlichen\n\n`schema.action()` und `NEWACTION()` akzeptieren eine Option `publish`. Sie deklariert einen Publish-Kanal, der nach der Aktion benannt ist (`Schema.action` oder der Name der Aktion), und `$.publish(value)` in der Aktion sendet an ihn:\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` verwendet `input` (oder `output`) der Aktion als Schema des Kanals. Ein String legt ein eigenes Schema fest; ein String, der mit `+` beginnt, fügt dem Input Felder hinzu.\n\n## Mit TMS verbinden: TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` verbindet deine App mit dem TMS-Endpunkt einer anderen Total.js-App. Der Client verbindet sich nach einem Neustart des Servers erneut und abonniert automatisch wieder:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` empfängt Nachrichten der Publish-Kanäle des Servers, konvertiert mit deren Schema. `client.publish()` sendet an die Subscribe-Kanäle des Servers. `client.call()` führt einen Remote-Aufruf aus; ohne Callback gibt es eine Promise zurück, und es schlägt mit `TMS is offline` fehl, bevor die Verbindung bereit ist, oder mit `408: Timeout` nach 10 Sekunden.\n\n## APIs: NEWAPI() und API()\n\n`API(name, schema, [data])` sendet eine Anfrage an einen registrierten API-Provider und gibt ein Aufrufobjekt zurück. Du verkettest Optionen und einen Callback; die Anfrage startet im nächsten Tick:\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` registriert deinen eigenen Provider. Der Callback erhält `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) und `next(err, response)`. Der Name `*` registriert einen Fallback für jeden unbekannten Namen:\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nBei Namen wird die Groß- und Kleinschreibung nicht beachtet. Der integrierte Provider `TotalAPI` (Alias `TAPI`) sendet mit dem Token aus `totalapi` an Total API; die ältere Funktion `TotalAPI(type, data, callback)` macht dasselbe in einem Aufruf.\n\n## API-Routen\n\nEine API-Route ist eine einzige `POST`-URL, die viele Aktionen ausführt. Der Client sendet `{ \"schema\": \"name/param?query\", \"data\": { ... } }`:\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nDas Zeichen vor dem Namen legt die HTTP-Methode fest, die für die Aktion verwendet wird: `+` validiert die Daten wie `POST`, `#` wie `PATCH`, `-` sendet keine Daten wie `GET`. URL-Parameter folgen dem Namen. Eine Funktion anstelle von `*Schema --> action` verarbeitet den Aufruf mit dem Controller als `this`. Die vollständige Syntax für Routen findest du unter [Routing](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Message Service y APIs","summary":"Publica, recibe y llama a través del Total.js Message Service, conéctate con TMSCLIENT(), llama a APIs con API() y NEWAPI(), y expón rutas API.","markdown":"---\ntitle: Message Service y APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service y APIs\n\n> Publica, recibe y llama a través del Total.js Message Service, conéctate con TMSCLIENT(), llama a APIs con API() y NEWAPI(), y expón rutas API.\n\nTotal.js 4 tiene dos formas de conectar tu app con otros servicios:\n\n- el **Total.js Message Service (TMS)**, un endpoint WebSocket donde tu app publica mensajes, recibe mensajes y responde a llamadas remotas, todo descrito con JSON schemas;\n- las **APIs**, una pequeña capa que envía peticiones con nombre a un proveedor de API que registras con `NEWAPI()` (Total API está registrado por defecto).\n\nLa misma app también puede exponer sus propias **rutas API**, una sola URL que ejecuta muchas acciones elegidas por nombre.\n\n## Activar TMS\n\nTMS está desactivado por defecto. Actívalo en `/config`:\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nEl endpoint es `default_tms_url` (`/$tms/`); `default_tms_maxlength` establece el tamaño máximo de un mensaje en kB (por defecto `1024`). Con `secret_tms`, un cliente debe enviar el token en la cabecera `x-token`. Un token incorrecto cierra la conexión con el código `4001`, y una dirección IP con más de cinco intentos fallidos se rechaza hasta el reinicio diario. Sin `secret_tms`, se acepta a todos los clientes. Consulta [Configuración](../../guides/configuration/) para ver las demás opciones.\n\n## Publicar mensajes\n\nUn canal de publicación indica a los clientes qué mensajes envía tu app y qué forma tienen. Decláralo con `NEWPUBLISH(name, schema)` y envía mensajes con `PUBLISH(name, data)`:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nEl esquema puede ser una declaración inline (`'id:UID, total:Number'`), un objeto JSON schema con un `$id`, o el nombre de un JSON schema o de un esquema de Total.js. Un nombre que no existe lanza un error.\n\n`PUBLISH()` envía el mensaje solo a los clientes conectados que se han suscrito al canal. Si no hay ningún cliente TMS conectado, o para un canal no declarado con `NEWPUBLISH()`, no hace nada. Los datos no se validan en el servidor: el cliente los convierte con el esquema del canal.\n\n## Recibir mensajes\n\nUn canal de suscripción es la dirección contraria: los clientes envían mensajes y tu app los gestiona. `NEWSUBSCRIBE(name, schema, [callback])` declara el canal y `SUBSCRIBE(name, callback)` añade handlers:\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nCada mensaje entrante se valida con el esquema del canal; los mensajes no válidos se descartan. Un handler recibe los datos validados y el cliente WebSocket. `UNSUBSCRIBE(name, [callback])` elimina un handler, o todos.\n\n## Llamadas remotas\n\n`NEWCALL(name, schema, callback)` registra una llamada que los clientes ejecutan como un procedimiento remoto. Primero se validan los datos; el callback responde con `next(err, response)`:\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Sincronización automática\n\nCuando añades o eliminas canales, llamadas o handlers, la app envía un mensaje `meta` actualizado a todos los clientes un segundo después. El meta enumera el `name` de la app, los canales `publish`, `subscribe` y `call` con sus JSON schemas, y los canales a los que se suscribe tu app.\n\n## Publicar desde acciones\n\n`schema.action()` y `NEWACTION()` aceptan una opción `publish`. Declara un canal de publicación con el nombre de la acción (`Schema.action`, o el nombre de la acción), y `$.publish(value)` en la acción envía a él:\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` usa el `input` (o el `output`) de la acción como esquema del canal. Una cadena establece su propio esquema; una cadena que empieza por `+` añade campos al input.\n\n## Conectarse a TMS: TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` conecta tu app al endpoint TMS de otra app Total.js. Se reconecta cuando el servidor se reinicia y vuelve a suscribirse automáticamente:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` recibe los mensajes de los canales de publicación del servidor, convertidos por su esquema. `client.publish()` envía a los canales de suscripción del servidor. `client.call()` ejecuta una llamada remota; sin callback devuelve una promesa, y falla con `TMS is offline` antes de que la conexión esté lista o con `408: Timeout` pasados 10 segundos.\n\n## APIs: NEWAPI() y API()\n\n`API(name, schema, [data])` envía una petición a un proveedor de API registrado y devuelve un objeto de llamada. Encadenas opciones y un callback; la petición empieza en el siguiente tick:\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` registra tu propio proveedor. El callback recibe `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) y `next(err, response)`. El nombre `*` registra un proveedor de reserva para cualquier nombre desconocido:\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nLos nombres no distinguen mayúsculas de minúsculas. El proveedor integrado `TotalAPI` (alias `TAPI`) envía a Total API con el token de `totalapi`; la función más antigua `TotalAPI(type, data, callback)` hace lo mismo en una sola llamada.\n\n## Rutas API\n\nUna ruta API es una sola URL `POST` que ejecuta muchas acciones. El cliente envía `{ \"schema\": \"name/param?query\", \"data\": { ... } }`:\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nEl signo antes del nombre establece el método HTTP usado para la acción: `+` valida los datos como `POST`, `#` como `PATCH`, `-` no envía datos, como `GET`. Los parámetros de la URL van después del nombre. Una función en lugar de `*Schema --> action` gestiona la llamada con el controlador como `this`. La sintaxis completa de las rutas está en [Enrutamiento](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Message Service et API","summary":"Publie, reçois et appelle via le Total.js Message Service, connecte-toi avec TMSCLIENT(), appelle des API avec API() et NEWAPI(), et expose des routes API.","markdown":"---\ntitle: Message Service et API\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service et API\n\n> Publie, reçois et appelle via le Total.js Message Service, connecte-toi avec TMSCLIENT(), appelle des API avec API() et NEWAPI(), et expose des routes API.\n\nTotal.js 4 offre deux façons de connecter ton application à d'autres services :\n\n- le **Total.js Message Service (TMS)**, un point d'accès WebSocket où ton application publie des messages, reçoit des messages et répond à des appels distants, le tout décrit par des schémas JSON ;\n- les **API**, une petite couche qui envoie des requêtes nommées à un fournisseur d'API que tu enregistres avec `NEWAPI()` (Total API est enregistré par défaut).\n\nLa même application peut aussi exposer ses propres **routes API** : une seule URL qui exécute de nombreuses actions choisies par leur nom.\n\n## Activer TMS\n\nTMS est désactivé par défaut. Active-le dans `/config` :\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nLe point d'accès est `default_tms_url` (`/$tms/`) ; `default_tms_maxlength` définit la taille maximale d'un message en ko (par défaut `1024`). Avec `secret_tms`, un client doit envoyer le jeton dans l'en-tête `x-token`. Un jeton erroné ferme la connexion avec le code `4001`, et une adresse IP ayant plus de cinq tentatives échouées est refusée jusqu'à la réinitialisation quotidienne. Sans `secret_tms`, tous les clients sont acceptés. Consulte [Configuration](../../guides/configuration/) pour les autres options.\n\n## Publier des messages\n\nUn canal de publication indique aux clients quels messages ton application envoie et à quoi ils ressemblent. Déclare-le avec `NEWPUBLISH(name, schema)` et envoie des messages avec `PUBLISH(name, data)` :\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nLe schéma peut être une déclaration inline (`'id:UID, total:Number'`), un objet de schéma JSON avec un `$id`, ou le nom d'un schéma JSON ou d'un schéma Total.js. Un nom qui n'existe pas lève une erreur.\n\n`PUBLISH()` envoie le message uniquement aux clients connectés qui se sont abonnés au canal. Sans client TMS connecté, ou pour un canal non déclaré avec `NEWPUBLISH()`, il ne fait rien. Les données ne sont pas validées sur le serveur : le client les convertit avec le schéma du canal.\n\n## Recevoir des messages\n\nUn canal d'abonnement fonctionne dans l'autre sens : les clients envoient des messages et ton application les traite. `NEWSUBSCRIBE(name, schema, [callback])` déclare le canal et `SUBSCRIBE(name, callback)` ajoute des handlers :\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nChaque message entrant est validé avec le schéma du canal ; les messages invalides sont abandonnés. Un handler reçoit les données validées et le client WebSocket. `UNSUBSCRIBE(name, [callback])` supprime un handler, ou tous.\n\n## Appels distants\n\n`NEWCALL(name, schema, callback)` enregistre un appel que les clients exécutent comme une procédure distante. Les données sont d'abord validées ; le callback répond avec `next(err, response)` :\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Synchronisation automatique\n\nLorsque tu ajoutes ou supprimes des canaux, des appels ou des handlers, l'application envoie un nouveau message `meta` à tous les clients une seconde plus tard. Le meta liste le `name` de l'application, les canaux `publish`, `subscribe` et `call` avec leurs schémas JSON, ainsi que les canaux auxquels ton application est abonnée.\n\n## Publier depuis des actions\n\n`schema.action()` et `NEWACTION()` acceptent une option `publish`. Elle déclare un canal de publication portant le nom de l'action (`Schema.action`, ou le nom de l'action), et `$.publish(value)` dans l'action y envoie des messages :\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` utilise l'`input` (ou l'`output`) de l'action comme schéma du canal. Une chaîne définit son propre schéma ; une chaîne qui commence par `+` ajoute des champs à l'input.\n\n## Se connecter à TMS : TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` connecte ton application au point d'accès TMS d'une autre application Total.js. Il se reconnecte après un redémarrage du serveur et se réabonne automatiquement :\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` reçoit les messages des canaux de publication du serveur, convertis par leur schéma. `client.publish()` envoie vers les canaux d'abonnement du serveur. `client.call()` exécute un appel distant ; sans callback, il renvoie une promesse, et il échoue avec `TMS is offline` avant que la connexion soit prête ou avec `408: Timeout` après 10 secondes.\n\n## API : NEWAPI() et API()\n\n`API(name, schema, [data])` envoie une requête à un fournisseur d'API enregistré et renvoie un objet d'appel. Tu chaînes les options et un callback ; la requête démarre au tick suivant :\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` enregistre ton propre fournisseur. Le callback reçoit `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) et `next(err, response)`. Le nom `*` enregistre un fournisseur de repli pour tout nom inconnu :\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nLes noms ne sont pas sensibles à la casse. Le fournisseur intégré `TotalAPI` (alias `TAPI`) envoie des requêtes POST à Total API avec le jeton de `totalapi` ; l'ancienne fonction `TotalAPI(type, data, callback)` fait la même chose en un seul appel.\n\n## Routes API\n\nUne route API est une seule URL `POST` qui exécute de nombreuses actions. Le client envoie `{ \"schema\": \"name/param?query\", \"data\": { ... } }` :\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nLe signe placé avant le nom définit la méthode HTTP utilisée pour l'action : `+` valide les données comme `POST`, `#` comme `PATCH`, `-` n'envoie aucune donnée comme `GET`. Les paramètres d'URL suivent le nom. Une fonction à la place de `*Schema --> action` traite l'appel avec le contrôleur comme `this`. La syntaxe complète des routes se trouve dans [Routage](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Message Service e API","summary":"Pubblica, ricevi ed esegui chiamate tramite il Total.js Message Service, connettiti con TMSCLIENT(), chiama le API con API() e NEWAPI() ed esponi route API.","markdown":"---\ntitle: Message Service e API\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service e API\n\n> Pubblica, ricevi ed esegui chiamate tramite il Total.js Message Service, connettiti con TMSCLIENT(), chiama le API con API() e NEWAPI() ed esponi route API.\n\nTotal.js 4 offre due modi per collegare la tua app ad altri servizi:\n\n- il **Total.js Message Service (TMS)**, un endpoint WebSocket dove la tua app pubblica messaggi, riceve messaggi e risponde a chiamate remote, tutto descritto da schemi JSON;\n- le **API**, un piccolo livello che invia richieste con nome a un provider di API che registri con `NEWAPI()` (Total API è registrato per impostazione predefinita).\n\nLa stessa app può anche esporre le proprie **route API**, un unico URL che esegue molte azioni scelte per nome.\n\n## Attivare TMS\n\nTMS è disattivato per impostazione predefinita. Attivalo in `/config`:\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nL'endpoint è `default_tms_url` (`/$tms/`); `default_tms_maxlength` imposta la dimensione massima di un messaggio in kB (predefinita `1024`). Con `secret_tms`, un client deve inviare il token nell'header `x-token`. Un token errato chiude la connessione con il codice `4001`, e un indirizzo IP con più di cinque tentativi falliti viene rifiutato fino al reset giornaliero. Senza `secret_tms`, ogni client viene accettato. Vedi [Configurazione](../../guides/configuration/) per le altre opzioni.\n\n## Pubblicare messaggi\n\nUn canale di pubblicazione dice ai client quali messaggi invia la tua app e che aspetto hanno. Dichiaralo con `NEWPUBLISH(name, schema)` e invia i messaggi con `PUBLISH(name, data)`:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nLo schema può essere una dichiarazione inline (`'id:UID, total:Number'`), un oggetto JSON schema con un `$id`, oppure il nome di un JSON schema o di uno schema Total.js. Un nome che non esiste genera un errore.\n\n`PUBLISH()` invia il messaggio solo ai client connessi che si sono iscritti al canale. Senza client TMS connessi, o per un canale non dichiarato con `NEWPUBLISH()`, non fa nulla. I dati non vengono validati sul server: il client li converte con lo schema del canale.\n\n## Ricevere messaggi\n\nUn canale di iscrizione è la direzione opposta: i client inviano messaggi e la tua app li gestisce. `NEWSUBSCRIBE(name, schema, [callback])` dichiara il canale e `SUBSCRIBE(name, callback)` aggiunge gli handler:\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nOgni messaggio in arrivo viene validato con lo schema del canale; i messaggi non validi vengono scartati. Un handler riceve i dati validati e il client WebSocket. `UNSUBSCRIBE(name, [callback])` rimuove un handler, oppure tutti.\n\n## Chiamate remote\n\n`NEWCALL(name, schema, callback)` registra una chiamata che i client eseguono come una procedura remota. Prima i dati vengono validati; la callback risponde con `next(err, response)`:\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Sincronizzazione automatica\n\nQuando aggiungi o rimuovi canali, chiamate o handler, l'app invia un nuovo messaggio `meta` a tutti i client un secondo dopo. Il meta elenca il `name` dell'app, i canali `publish`, `subscribe` e `call` con i loro schemi JSON, e i canali a cui la tua app è iscritta.\n\n## Pubblicare dalle azioni\n\n`schema.action()` e `NEWACTION()` accettano un'opzione `publish`. Dichiara un canale di pubblicazione con il nome dell'azione (`Schema.action`, oppure il nome dell'azione), e `$.publish(value)` nell'azione invia a quel canale:\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` usa l'`input` (o l'`output`) dell'azione come schema del canale. Una stringa imposta un proprio schema; una stringa che inizia con `+` aggiunge campi all'input.\n\n## Connettersi a TMS: TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` collega la tua app all'endpoint TMS di un'altra app Total.js. Si riconnette dopo il riavvio del server e rinnova automaticamente le iscrizioni:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` riceve i messaggi dei canali di pubblicazione del server, convertiti con il loro schema. `client.publish()` invia ai canali di iscrizione del server. `client.call()` esegue una chiamata remota; senza callback restituisce una promise, e fallisce con `TMS is offline` prima che la connessione sia pronta oppure con `408: Timeout` dopo 10 secondi.\n\n## API: NEWAPI() e API()\n\n`API(name, schema, [data])` invia una richiesta a un provider di API registrato e restituisce un oggetto chiamata. Concateni le opzioni e una callback; la richiesta parte al tick successivo:\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` registra un tuo provider. La callback riceve `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) e `next(err, response)`. Il nome `*` registra un fallback per ogni nome sconosciuto:\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nI nomi non distinguono tra maiuscole e minuscole. Il provider integrato `TotalAPI` (alias `TAPI`) invia a Total API con il token di `totalapi`; la vecchia funzione `TotalAPI(type, data, callback)` fa lo stesso in un'unica chiamata.\n\n## Route API\n\nUna route API è un unico URL `POST` che esegue molte azioni. Il client invia `{ \"schema\": \"name/param?query\", \"data\": { ... } }`:\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nIl segno prima del nome imposta il metodo HTTP usato per l'azione: `+` valida i dati come `POST`, `#` come `PATCH`, `-` non invia dati come `GET`. I parametri URL seguono il nome. Una funzione al posto di `*Schema --> action` gestisce la chiamata con il controller come `this`. La sintassi completa delle route è in [Routing](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdc61cT61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Message Service a API","summary":"Publikuj, prijímaj a volaj cez Total.js Message Service, pripájaj sa pomocou TMSCLIENT(), volaj API pomocou API() a NEWAPI() a sprístupni API trasy.","markdown":"---\ntitle: Message Service a API\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/message-service-and-apis/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Message Service a API\n\n> Publikuj, prijímaj a volaj cez Total.js Message Service, pripájaj sa pomocou TMSCLIENT(), volaj API pomocou API() a NEWAPI() a sprístupni API trasy.\n\nTotal.js 4 má dva spôsoby, ako prepojiť tvoju aplikáciu s inými službami:\n\n- **Total.js Message Service (TMS)**, WebSocket endpoint, kde tvoja aplikácia publikuje správy, prijíma správy a odpovedá na vzdialené volania, všetko popísané JSON schémami;\n- **API**, malá vrstva, ktorá posiela pomenované požiadavky poskytovateľovi API, ktorého zaregistruješ pomocou `NEWAPI()` (Total API je zaregistrované predvolene).\n\nTá istá aplikácia môže sprístupniť aj vlastné **API trasy**, jednu URL, ktorá spúšťa mnoho akcií vybraných podľa názvu.\n\n## Zapnutie TMS\n\nTMS je predvolene vypnuté. Zapni ho v `/config`:\n\n```\nallow_tms       : true\nsecret_tms      : my-secret-token\n```\n\nEndpoint je `default_tms_url` (`/$tms/`); `default_tms_maxlength` nastavuje maximálnu veľkosť správy v kB (predvolene `1024`). So `secret_tms` musí klient poslať token v hlavičke `x-token`. Nesprávny token zatvorí spojenie s kódom `4001` a IP adresa s viac ako piatimi neúspešnými pokusmi je odmietaná až do denného resetu. Bez `secret_tms` sa prijme každý klient. Ďalšie voľby nájdeš v [Konfigurácia](../../guides/configuration/).\n\n## Publikovanie správ\n\nPublikačný kanál hovorí klientom, ktoré správy tvoja aplikácia posiela a ako vyzerajú. Deklaruj ho pomocou `NEWPUBLISH(name, schema)` a správy posielaj pomocou `PUBLISH(name, data)`:\n\n```js\n// definitions/tms.js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('orders').insert(model);\n\t\t\tPUBLISH('orders_created', model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\nSchéma môže byť inline deklarácia (`'id:UID, total:Number'`), objekt JSON schémy s `$id`, alebo názov JSON schémy či Total.js schémy. Názov, ktorý neexistuje, vyhodí chybu.\n\n`PUBLISH()` pošle správu iba pripojeným klientom, ktorí sa prihlásili na odber kanála. Keď nie je pripojený žiadny TMS klient, alebo pre kanál nedeklarovaný pomocou `NEWPUBLISH()`, nerobí nič. Dáta sa na serveri nevalidujú: klient ich prevedie pomocou schémy z kanála.\n\n## Prijímanie správ\n\nOdberový kanál je opačný smer: klienti posielajú správy a tvoja aplikácia ich spracúva. `NEWSUBSCRIBE(name, schema, [callback])` deklaruje kanál a `SUBSCRIBE(name, callback)` pridáva handlery:\n\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n\n// another handler for the same channel\nSUBSCRIBE('products_updated', function(data) {\n\tconsole.log('Product updated', data.id);\n});\n```\n\nKaždá prichádzajúca správa sa validuje schémou kanála; neplatné správy sa zahodia. Handler dostane zvalidované dáta a WebSocket klienta. `UNSUBSCRIBE(name, [callback])` odstráni jeden handler alebo všetky.\n\n## Vzdialené volania\n\n`NEWCALL(name, schema, callback)` zaregistruje volanie, ktoré klienti spúšťajú ako vzdialenú procedúru. Dáta sa najprv zvalidujú; callback odpovie pomocou `next(err, response)`:\n\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n\n// or run a schema operation\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n## Automatická synchronizácia\n\nKeď pridáš alebo odstrániš kanály, volania alebo handlery, aplikácia o sekundu neskôr pošle všetkým klientom čerstvú správu `meta`. Meta uvádza `name` aplikácie, kanály `publish`, `subscribe` a `call` s ich JSON schémami a kanály, na ktoré je tvoja aplikácia prihlásená.\n\n## Publikovanie z akcií\n\n`schema.action()` a `NEWACTION()` prijímajú voľbu `publish`. Deklaruje publikačný kanál pomenovaný podľa akcie (`Schema.action`, alebo názov akcie) a `$.publish(value)` v akcii doň posiela:\n\n```js\nNEWACTION('Orders/create', {\n\tinput: '*email:Email, *total:Number',\n\tpublish: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\t$.publish(model);\n\t\t$.success(model.id);\n\t}\n});\n```\n\n`publish: true` použije `input` (alebo `output`) akcie ako schému kanála. Reťazec nastaví vlastnú schému; reťazec, ktorý začína `+`, pridá polia k vstupu.\n\n## Pripojenie k TMS: TMSCLIENT()\n\n`TMSCLIENT(url, [token], [callback])` pripojí tvoju aplikáciu k TMS endpointu inej Total.js aplikácie. Po reštarte servera sa znova pripojí a automaticky obnoví odbery:\n\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\n\tclient.subscribe('orders_created', function(data) {\n\t\tconsole.log('New order', data.id, data.total);\n\t});\n\n\tclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n\n\tclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\t\tconsole.log(err, response);\n\t});\n});\n```\n\n`client.subscribe()` prijíma správy z publikačných kanálov servera, prevedené ich schémou. `client.publish()` posiela do odberových kanálov servera. `client.call()` spustí vzdialené volanie; bez callbacku vráti promise a zlyhá s `TMS is offline` pred pripravením spojenia alebo s `408: Timeout` po 10 sekundách.\n\n## API: NEWAPI() a API()\n\n`API(name, schema, [data])` pošle požiadavku zaregistrovanému poskytovateľovi API a vráti objekt volania. Reťazíš voľby a callback; požiadavka sa spustí v ďalšom ticku:\n\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n\n// service_name is a placeholder for a Total API service\nvar base64 = await API('TotalAPI', 'service_name', { value: 'Hello' }).output('base64').promise();\n```\n\n`NEWAPI(name, callback)` zaregistruje tvojho vlastného poskytovateľa. Callback dostane `opt` (`name`, `schema`, `data`, `controller`, `files`, `output`) a `next(err, response)`. Názov `*` zaregistruje záložného poskytovateľa pre každý neznámy názov:\n\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n\nAPI('Payments', 'charge', { amount: 100 }).fail(console.error).data(console.log);\n```\n\nNázvy nerozlišujú veľké a malé písmená. Vstavaný poskytovateľ `TotalAPI` (alias `TAPI`) posiela požiadavky na Total API s tokenom z `totalapi`; staršia funkcia `TotalAPI(type, data, callback)` robí to isté jedným volaním.\n\n## API trasy\n\nAPI trasa je jedna `POST` URL, ktorá spúšťa mnoho akcií. Klient posiela `{ \"schema\": \"name/param?query\", \"data\": { ... } }`:\n\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n\tROUTE('+API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n};\n```\n\nZnak pred názvom určuje HTTP metódu použitú pre akciu: `+` validuje dáta ako `POST`, `#` ako `PATCH`, `-` neposiela žiadne dáta ako `GET`. Parametre URL nasledujú za názvom. Funkcia namiesto `*Schema --> action` spracuje volanie s kontrolérom ako `this`. Celá syntax trás je v [Smerovanie](../../guides/routing/).\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabdVC1cH61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Images","summary":"Resize, crop, convert and measure images with the Image module and GraphicsMagick or ImageMagick.","markdown":"---\ntitle: Images\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Images\n\n> Resize, crop, convert and measure images with the Image module and GraphicsMagick or ImageMagick.\n\nThe global `Image` object processes pictures: resizing, cropping, rotating, filters, watermarks and format conversion. It does not process the pixels itself. It builds a command line and runs **GraphicsMagick** or **ImageMagick**, so one of them must be installed on the server.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nThe module also measures the size of images (JPG, PNG, GIF, WebP, SVG, BMP, PSD) from a buffer, in pure JavaScript, without any external tool.\n\n## Requirements\n\nInstall one of the tools and make it available in the `PATH` of the process:\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nThe config key [`default_image_converter`](../../guides/configuration/) chooses the tool:\n\n| Value | Tool | Command that runs |\n| --- | --- | --- |\n| `gm` (default) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nThe second argument of `Image.load()` overrides the config for one image.\n\n## Loading an image\n\n`Image.load(source, [converter], [width], [height])` creates an `Image` object; `Image.init()` is the same function. The source is a file name, a readable stream or a `Buffer`:\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nFor a file, the output format is its extension. For a stream or a buffer, the output format is `jpg` until you call `image.output()`.\n\n## Building the operations\n\nEach method adds a command-line option and returns the image, so calls can be chained. Nothing runs until `save()`, `pipe()` or `stream()`:\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nThe options do not run in the order of your calls. Each one has a fixed priority, and the framework sorts them before it builds the command:\n\n| Priority | Methods |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, first part of `sepia()` |\n| 5 | `quality()`, second part of `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (default) |\n\nSo `rotate()` always runs after `crop()`. Use `command()` with your own priority when you need another order.\n\n### Resizing\n\n| Method | Result |\n| --- | --- |\n| `resize(w, h, [options])` | Fits the image into `w` x `h` and keeps the aspect ratio. Omit one side to compute it. |\n| `resizeCenter(w, h, [color])` | Fills `w` x `h` and crops the overflow around the center. |\n| `resizeAlign(w, h, [align], [color])` | Like `resizeCenter()`, but crops around `align` (`top`, `bottom left`...). |\n| `miniature(w, h, [color], [filter])` | Fits the whole image into `w` x `h` and fills the rest with `color`. |\n| `thumbnail(w, h, [options])` | Like `resize()`, with the `-thumbnail` option of the tool. |\n| `scale(w, h, [options])` | Fast resize without a filter. |\n\n`options` is a string appended to the size, with the meaning the tool gives it: `!` ignores the aspect ratio, `>` only shrinks, `<` only enlarges, `^` fills the area, `%` reads the numbers as percentages:\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Other operations\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` calls `fn` with the image, so you can group operations in a function and reuse it:\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Quality\n\n`quality(percentage)` sets the compression quality (`-quality`). Without an argument it uses **80**. An image without `quality()` gets the default quality of GraphicsMagick or ImageMagick.\n\n## Output\n\n`save([filename], [callback])` runs the command and writes the result. Without a file name, it overwrites the source file. The format of the saved file comes from the extension of `filename`:\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` sends the result into a writable stream, and `stream([type])` returns a readable stream. Here the format is `type`, or the value of `output()`, or the extension of the source file. Supported types are `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` and `ico`:\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nWhen an image has no operation at all, `save()`, `pipe()` and `stream()` add `minify()` on their own.\n\n## Measuring images\n\n`Image.measure(type, buffer)` reads the width and height from the first bytes of a file. `type` is an extension (`.png` or `png`) or a MIME type (`image/png`):\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nThere are also functions for each format: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` and `Image.measurePSD()`. The framework uses them for uploaded files, which is why `file.width` and `file.height` are filled for images.\n\nTo measure a file on disk, use `image.measure(callback)` (JPG, PNG, GIF, WebP) or `image.identify(callback)`, which asks the external tool and works for any format it knows.\n\n## Images in responses\n\nIn a route, `controller.image()` and `res.image()` load an image, let you set the operations and send the result with a cache. `RESIZE()` creates resized copies of static images on demand:\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nBoth are described in [Static files](../../guides/static-files/). Images from a FileStorage are loaded with `FILESTORAGE(name).image()`, see [File storage](../../guides/file-storage/).\n\n## Output middleware\n\n`Image.middleware(type, fn)` registers a function that returns a transform stream. Every output of that type passes through it, for example a PNG optimizer:\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nThe function must return a new stream on each call. With `save()`, the result is written to the file first, then passed through the stream and written again.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"JabdVC1cH61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Bilder","summary":"Bilder mit dem Image-Modul und GraphicsMagick oder ImageMagick skalieren, zuschneiden, konvertieren und vermessen.","markdown":"---\ntitle: Bilder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Bilder\n\n> Bilder mit dem Image-Modul und GraphicsMagick oder ImageMagick skalieren, zuschneiden, konvertieren und vermessen.\n\nDas globale Objekt `Image` verarbeitet Bilder: Skalieren, Zuschneiden, Drehen, Filter, Wasserzeichen und Formatkonvertierung. Es verarbeitet die Pixel nicht selbst. Es baut eine Kommandozeile und führt **GraphicsMagick** oder **ImageMagick** aus, daher muss eines der beiden auf dem Server installiert sein.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nDas Modul ermittelt außerdem die Größe von Bildern (JPG, PNG, GIF, WebP, SVG, BMP, PSD) aus einem Buffer, in reinem JavaScript, ohne externes Werkzeug.\n\n## Voraussetzungen\n\nInstalliere eines der Werkzeuge und mache es im `PATH` des Prozesses verfügbar:\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nDer Konfigurationsschlüssel [`default_image_converter`](../../guides/configuration/) wählt das Werkzeug:\n\n| Wert | Werkzeug | Ausgeführter Befehl |\n| --- | --- | --- |\n| `gm` (Standard) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nDas zweite Argument von `Image.load()` überschreibt die Konfiguration für ein einzelnes Bild.\n\n## Ein Bild laden\n\n`Image.load(source, [converter], [width], [height])` erstellt ein `Image`-Objekt; `Image.init()` ist dieselbe Funktion. Die Quelle ist ein Dateiname, ein lesbarer Stream oder ein `Buffer`:\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nBei einer Datei ist das Ausgabeformat ihre Endung. Bei einem Stream oder Buffer ist das Ausgabeformat `jpg`, bis du `image.output()` aufrufst.\n\n## Die Operationen aufbauen\n\nJede Methode fügt eine Kommandozeilenoption hinzu und gibt das Bild zurück, sodass Aufrufe verkettet werden können. Nichts läuft vor `save()`, `pipe()` oder `stream()`:\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nDie Optionen laufen nicht in der Reihenfolge deiner Aufrufe. Jede hat eine feste Priorität, und das Framework sortiert sie, bevor es den Befehl baut:\n\n| Priorität | Methoden |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, erster Teil von `sepia()` |\n| 5 | `quality()`, zweiter Teil von `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (Standard) |\n\n`rotate()` läuft also immer nach `crop()`. Verwende `command()` mit einer eigenen Priorität, wenn du eine andere Reihenfolge brauchst.\n\n### Skalieren\n\n| Methode | Ergebnis |\n| --- | --- |\n| `resize(w, h, [options])` | Passt das Bild in `w` x `h` ein und behält das Seitenverhältnis bei. Lass eine Seite weg, damit sie berechnet wird. |\n| `resizeCenter(w, h, [color])` | Füllt `w` x `h` aus und schneidet den Überstand um die Mitte herum ab. |\n| `resizeAlign(w, h, [align], [color])` | Wie `resizeCenter()`, schneidet aber um `align` (`top`, `bottom left`...) herum zu. |\n| `miniature(w, h, [color], [filter])` | Passt das ganze Bild in `w` x `h` ein und füllt den Rest mit `color`. |\n| `thumbnail(w, h, [options])` | Wie `resize()`, mit der Option `-thumbnail` des Werkzeugs. |\n| `scale(w, h, [options])` | Schnelles Skalieren ohne Filter. |\n\n`options` ist ein String, der an die Größe angehängt wird, mit der Bedeutung, die das Werkzeug ihm gibt: `!` ignoriert das Seitenverhältnis, `>` verkleinert nur, `<` vergrößert nur, `^` füllt die Fläche aus, `%` liest die Zahlen als Prozentwerte:\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Weitere Operationen\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` ruft `fn` mit dem Bild auf, sodass du Operationen in einer Funktion bündeln und wiederverwenden kannst:\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Qualität\n\n`quality(percentage)` setzt die Kompressionsqualität (`-quality`). Ohne Argument wird **80** verwendet. Ein Bild ohne `quality()` erhält die Standardqualität von GraphicsMagick oder ImageMagick.\n\n## Ausgabe\n\n`save([filename], [callback])` führt den Befehl aus und schreibt das Ergebnis. Ohne Dateinamen wird die Quelldatei überschrieben. Das Format der gespeicherten Datei ergibt sich aus der Endung von `filename`:\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` sendet das Ergebnis in einen beschreibbaren Stream, und `stream([type])` gibt einen lesbaren Stream zurück. Hier ist das Format `type`, der Wert von `output()` oder die Endung der Quelldatei. Unterstützte Typen sind `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` und `ico`:\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nWenn ein Bild überhaupt keine Operation hat, fügen `save()`, `pipe()` und `stream()` selbst `minify()` hinzu.\n\n## Bilder vermessen\n\n`Image.measure(type, buffer)` liest Breite und Höhe aus den ersten Bytes einer Datei. `type` ist eine Endung (`.png` oder `png`) oder ein MIME-Typ (`image/png`):\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nEs gibt auch Funktionen für jedes Format: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` und `Image.measurePSD()`. Das Framework verwendet sie für hochgeladene Dateien, deshalb sind `file.width` und `file.height` bei Bildern gefüllt.\n\nUm eine Datei auf der Festplatte zu vermessen, verwende `image.measure(callback)` (JPG, PNG, GIF, WebP) oder `image.identify(callback)`, das das externe Werkzeug fragt und für jedes Format funktioniert, das es kennt.\n\n## Bilder in Antworten\n\nIn einer Route laden `controller.image()` und `res.image()` ein Bild, lassen dich die Operationen festlegen und senden das Ergebnis mit einem Cache. `RESIZE()` erstellt bei Bedarf skalierte Kopien statischer Bilder:\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nBeides ist in [Statische Dateien](../../guides/static-files/) beschrieben. Bilder aus einem FileStorage werden mit `FILESTORAGE(name).image()` geladen, siehe [Dateispeicher](../../guides/file-storage/).\n\n## Ausgabe-Middleware\n\n`Image.middleware(type, fn)` registriert eine Funktion, die einen Transform-Stream zurückgibt. Jede Ausgabe dieses Typs läuft durch ihn hindurch, zum Beispiel ein PNG-Optimierer:\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nDie Funktion muss bei jedem Aufruf einen neuen Stream zurückgeben. Bei `save()` wird das Ergebnis zuerst in die Datei geschrieben, dann durch den Stream geleitet und erneut geschrieben.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"JabdVC1cH61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Imágenes","summary":"Redimensiona, recorta, convierte y mide imágenes con el módulo Image y GraphicsMagick o ImageMagick.","markdown":"---\ntitle: \"Imágenes\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Imágenes\n\n> Redimensiona, recorta, convierte y mide imágenes con el módulo Image y GraphicsMagick o ImageMagick.\n\nEl objeto global `Image` procesa imágenes: redimensionado, recorte, rotación, filtros, marcas de agua y conversión de formato. No procesa los píxeles por sí mismo. Construye una línea de comandos y ejecuta **GraphicsMagick** o **ImageMagick**, así que uno de los dos debe estar instalado en el servidor.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nEl módulo también mide el tamaño de las imágenes (JPG, PNG, GIF, WebP, SVG, BMP, PSD) a partir de un buffer, en JavaScript puro, sin ninguna herramienta externa.\n\n## Requisitos\n\nInstala una de las herramientas y haz que esté disponible en el `PATH` del proceso:\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nLa clave de configuración [`default_image_converter`](../../guides/configuration/) elige la herramienta:\n\n| Valor | Herramienta | Comando que se ejecuta |\n| --- | --- | --- |\n| `gm` (por defecto) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nEl segundo argumento de `Image.load()` anula la configuración para una sola imagen.\n\n## Cargar una imagen\n\n`Image.load(source, [converter], [width], [height])` crea un objeto `Image`; `Image.init()` es la misma función. El origen es un nombre de archivo, un stream de lectura o un `Buffer`:\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nPara un archivo, el formato de salida es su extensión. Para un stream o un buffer, el formato de salida es `jpg` hasta que llames a `image.output()`.\n\n## Construir las operaciones\n\nCada método añade una opción de línea de comandos y devuelve la imagen, así que las llamadas se pueden encadenar. No se ejecuta nada hasta `save()`, `pipe()` o `stream()`:\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nLas opciones no se ejecutan en el orden de tus llamadas. Cada una tiene una prioridad fija, y el framework las ordena antes de construir el comando:\n\n| Prioridad | Métodos |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, primera parte de `sepia()` |\n| 5 | `quality()`, segunda parte de `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (por defecto) |\n\nAsí, `rotate()` siempre se ejecuta después de `crop()`. Usa `command()` con tu propia prioridad cuando necesites otro orden.\n\n### Redimensionar\n\n| Método | Resultado |\n| --- | --- |\n| `resize(w, h, [options])` | Ajusta la imagen a `w` x `h` y mantiene la relación de aspecto. Omite un lado para que se calcule. |\n| `resizeCenter(w, h, [color])` | Rellena `w` x `h` y recorta lo que sobra alrededor del centro. |\n| `resizeAlign(w, h, [align], [color])` | Como `resizeCenter()`, pero recorta alrededor de `align` (`top`, `bottom left`...). |\n| `miniature(w, h, [color], [filter])` | Ajusta la imagen completa a `w` x `h` y rellena el resto con `color`. |\n| `thumbnail(w, h, [options])` | Como `resize()`, con la opción `-thumbnail` de la herramienta. |\n| `scale(w, h, [options])` | Redimensionado rápido sin filtro. |\n\n`options` es una cadena que se añade al tamaño, con el significado que le da la herramienta: `!` ignora la relación de aspecto, `>` solo reduce, `<` solo amplía, `^` rellena el área, `%` interpreta los números como porcentajes:\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Otras operaciones\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` llama a `fn` con la imagen, así que puedes agrupar operaciones en una función y reutilizarla:\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Calidad\n\n`quality(percentage)` establece la calidad de compresión (`-quality`). Sin argumento, usa **80**. Una imagen sin `quality()` recibe la calidad por defecto de GraphicsMagick o ImageMagick.\n\n## Salida\n\n`save([filename], [callback])` ejecuta el comando y escribe el resultado. Sin nombre de archivo, sobrescribe el archivo de origen. El formato del archivo guardado viene de la extensión de `filename`:\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` envía el resultado a un stream de escritura, y `stream([type])` devuelve un stream de lectura. Aquí el formato es `type`, o el valor de `output()`, o la extensión del archivo de origen. Los tipos admitidos son `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` e `ico`:\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nCuando una imagen no tiene ninguna operación, `save()`, `pipe()` y `stream()` añaden `minify()` por su cuenta.\n\n## Medir imágenes\n\n`Image.measure(type, buffer)` lee el ancho y el alto de los primeros bytes de un archivo. `type` es una extensión (`.png` o `png`) o un tipo MIME (`image/png`):\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nTambién hay funciones para cada formato: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` e `Image.measurePSD()`. El framework las usa para los archivos subidos, por eso `file.width` y `file.height` se rellenan en las imágenes.\n\nPara medir un archivo en disco, usa `image.measure(callback)` (JPG, PNG, GIF, WebP) o `image.identify(callback)`, que consulta a la herramienta externa y funciona con cualquier formato que esta conozca.\n\n## Imágenes en las respuestas\n\nEn una ruta, `controller.image()` y `res.image()` cargan una imagen, te permiten establecer las operaciones y envían el resultado con caché. `RESIZE()` crea bajo demanda copias redimensionadas de imágenes estáticas:\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nAmbos se describen en [Archivos estáticos](../../guides/static-files/). Las imágenes de un FileStorage se cargan con `FILESTORAGE(name).image()`, consulta [Almacenamiento de archivos](../../guides/file-storage/).\n\n## Middleware de salida\n\n`Image.middleware(type, fn)` registra una función que devuelve un stream de transformación. Toda salida de ese tipo pasa por él, por ejemplo un optimizador de PNG:\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nLa función debe devolver un stream nuevo en cada llamada. Con `save()`, el resultado se escribe primero en el archivo, después pasa por el stream y se vuelve a escribir.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"JabdVC1cH61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Images","summary":"Redimensionne, recadre, convertis et mesure des images avec le module Image et GraphicsMagick ou ImageMagick.","markdown":"---\ntitle: Images\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Images\n\n> Redimensionne, recadre, convertis et mesure des images avec le module Image et GraphicsMagick ou ImageMagick.\n\nL'objet global `Image` traite les images : redimensionnement, recadrage, rotation, filtres, filigranes et conversion de format. Il ne traite pas les pixels lui-même. Il construit une ligne de commande et exécute **GraphicsMagick** ou **ImageMagick** : l'un des deux doit donc être installé sur le serveur.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nLe module mesure aussi la taille des images (JPG, PNG, GIF, WebP, SVG, BMP, PSD) à partir d'un buffer, en JavaScript pur, sans aucun outil externe.\n\n## Prérequis\n\nInstalle l'un des outils et rends-le disponible dans le `PATH` du processus :\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nLa clé de configuration [`default_image_converter`](../../guides/configuration/) choisit l'outil :\n\n| Valeur | Outil | Commande exécutée |\n| --- | --- | --- |\n| `gm` (par défaut) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nLe deuxième argument de `Image.load()` remplace la configuration pour une seule image.\n\n## Charger une image\n\n`Image.load(source, [converter], [width], [height])` crée un objet `Image` ; `Image.init()` est la même fonction. La source est un nom de fichier, un stream lisible ou un `Buffer` :\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nPour un fichier, le format de sortie est son extension. Pour un stream ou un buffer, le format de sortie est `jpg` tant que tu n'appelles pas `image.output()`.\n\n## Construire les opérations\n\nChaque méthode ajoute une option de ligne de commande et renvoie l'image : les appels peuvent donc être chaînés. Rien ne s'exécute avant `save()`, `pipe()` ou `stream()` :\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nLes options ne s'exécutent pas dans l'ordre de tes appels. Chacune a une priorité fixe, et le framework les trie avant de construire la commande :\n\n| Priorité | Méthodes |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, première partie de `sepia()` |\n| 5 | `quality()`, seconde partie de `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (par défaut) |\n\nAinsi, `rotate()` s'exécute toujours après `crop()`. Utilise `command()` avec ta propre priorité lorsque tu as besoin d'un autre ordre.\n\n### Redimensionnement\n\n| Méthode | Résultat |\n| --- | --- |\n| `resize(w, h, [options])` | Ajuste l'image à `w` x `h` en conservant le ratio. Omets un côté pour qu'il soit calculé. |\n| `resizeCenter(w, h, [color])` | Remplit `w` x `h` et recadre le dépassement autour du centre. |\n| `resizeAlign(w, h, [align], [color])` | Comme `resizeCenter()`, mais recadre autour de `align` (`top`, `bottom left`...). |\n| `miniature(w, h, [color], [filter])` | Ajuste l'image entière à `w` x `h` et remplit le reste avec `color`. |\n| `thumbnail(w, h, [options])` | Comme `resize()`, avec l'option `-thumbnail` de l'outil. |\n| `scale(w, h, [options])` | Redimensionnement rapide sans filtre. |\n\n`options` est une chaîne ajoutée à la taille, avec le sens que lui donne l'outil : `!` ignore le ratio, `>` réduit uniquement, `<` agrandit uniquement, `^` remplit la zone, `%` lit les nombres comme des pourcentages :\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Autres opérations\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` appelle `fn` avec l'image : tu peux ainsi regrouper des opérations dans une fonction et la réutiliser :\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Qualité\n\n`quality(percentage)` définit la qualité de compression (`-quality`). Sans argument, elle vaut **80**. Une image sans `quality()` reçoit la qualité par défaut de GraphicsMagick ou d'ImageMagick.\n\n## Sortie\n\n`save([filename], [callback])` exécute la commande et écrit le résultat. Sans nom de fichier, il écrase le fichier source. Le format du fichier enregistré provient de l'extension de `filename` :\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` envoie le résultat dans un stream inscriptible, et `stream([type])` renvoie un stream lisible. Ici, le format est `type`, ou la valeur de `output()`, ou l'extension du fichier source. Les types pris en charge sont `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` et `ico` :\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nLorsqu'une image n'a aucune opération, `save()`, `pipe()` et `stream()` ajoutent `minify()` d'eux-mêmes.\n\n## Mesurer des images\n\n`Image.measure(type, buffer)` lit la largeur et la hauteur dans les premiers octets d'un fichier. `type` est une extension (`.png` ou `png`) ou un type MIME (`image/png`) :\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nIl existe aussi des fonctions pour chaque format : `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` et `Image.measurePSD()`. Le framework les utilise pour les fichiers envoyés : c'est pourquoi `file.width` et `file.height` sont renseignés pour les images.\n\nPour mesurer un fichier sur le disque, utilise `image.measure(callback)` (JPG, PNG, GIF, WebP) ou `image.identify(callback)`, qui interroge l'outil externe et fonctionne pour tous les formats qu'il connaît.\n\n## Images dans les réponses\n\nDans une route, `controller.image()` et `res.image()` chargent une image, te laissent définir les opérations et envoient le résultat avec un cache. `RESIZE()` crée à la demande des copies redimensionnées d'images statiques :\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nLes deux sont décrits dans [Fichiers statiques](../../guides/static-files/). Les images d'un FileStorage se chargent avec `FILESTORAGE(name).image()`, voir [Stockage de fichiers](../../guides/file-storage/).\n\n## Middleware de sortie\n\n`Image.middleware(type, fn)` enregistre une fonction qui renvoie un stream de transformation. Chaque sortie de ce type passe par celui-ci, par exemple un optimiseur PNG :\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nLa fonction doit renvoyer un nouveau stream à chaque appel. Avec `save()`, le résultat est d'abord écrit dans le fichier, puis passé dans le stream et écrit à nouveau.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"JabdVC1cH61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Immagini","summary":"Ridimensiona, ritaglia, converti e misura le immagini con il modulo Image e GraphicsMagick o ImageMagick.","markdown":"---\ntitle: Immagini\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Immagini\n\n> Ridimensiona, ritaglia, converti e misura le immagini con il modulo Image e GraphicsMagick o ImageMagick.\n\nL'oggetto globale `Image` elabora le immagini: ridimensionamento, ritaglio, rotazione, filtri, filigrane e conversione di formato. Non elabora da solo i pixel. Costruisce una riga di comando ed esegue **GraphicsMagick** o **ImageMagick**, quindi uno dei due deve essere installato sul server.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nIl modulo misura anche le dimensioni delle immagini (JPG, PNG, GIF, WebP, SVG, BMP, PSD) a partire da un buffer, in puro JavaScript, senza alcuno strumento esterno.\n\n## Requisiti\n\nInstalla uno dei due strumenti e rendilo disponibile nel `PATH` del processo:\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nLa chiave di configurazione [`default_image_converter`](../../guides/configuration/) sceglie lo strumento:\n\n| Valore | Strumento | Comando eseguito |\n| --- | --- | --- |\n| `gm` (predefinito) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nIl secondo argomento di `Image.load()` sovrascrive la configurazione per una singola immagine.\n\n## Caricare un'immagine\n\n`Image.load(source, [converter], [width], [height])` crea un oggetto `Image`; `Image.init()` è la stessa funzione. La sorgente è un nome di file, uno stream leggibile o un `Buffer`:\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nPer un file, il formato di output è la sua estensione. Per uno stream o un buffer, il formato di output è `jpg` finché non chiami `image.output()`.\n\n## Costruire le operazioni\n\nOgni metodo aggiunge un'opzione della riga di comando e restituisce l'immagine, quindi le chiamate si possono concatenare. Non viene eseguito nulla fino a `save()`, `pipe()` o `stream()`:\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nLe opzioni non vengono eseguite nell'ordine delle tue chiamate. Ognuna ha una priorità fissa, e il framework le ordina prima di costruire il comando:\n\n| Priorità | Metodi |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, prima parte di `sepia()` |\n| 5 | `quality()`, seconda parte di `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (predefinito) |\n\nQuindi `rotate()` viene sempre eseguito dopo `crop()`. Usa `command()` con una tua priorità quando ti serve un altro ordine.\n\n### Ridimensionamento\n\n| Metodo | Risultato |\n| --- | --- |\n| `resize(w, h, [options])` | Adatta l'immagine a `w` x `h` e mantiene le proporzioni. Ometti un lato per calcolarlo. |\n| `resizeCenter(w, h, [color])` | Riempie `w` x `h` e ritaglia l'eccedenza attorno al centro. |\n| `resizeAlign(w, h, [align], [color])` | Come `resizeCenter()`, ma ritaglia attorno ad `align` (`top`, `bottom left`...). |\n| `miniature(w, h, [color], [filter])` | Adatta l'intera immagine a `w` x `h` e riempie il resto con `color`. |\n| `thumbnail(w, h, [options])` | Come `resize()`, con l'opzione `-thumbnail` dello strumento. |\n| `scale(w, h, [options])` | Ridimensionamento veloce senza filtro. |\n\n`options` è una stringa aggiunta alla dimensione, con il significato che le dà lo strumento: `!` ignora le proporzioni, `>` solo riduce, `<` solo ingrandisce, `^` riempie l'area, `%` interpreta i numeri come percentuali:\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Altre operazioni\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` chiama `fn` con l'immagine, così puoi raggruppare le operazioni in una funzione e riutilizzarla:\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Qualità\n\n`quality(percentage)` imposta la qualità di compressione (`-quality`). Senza argomento usa **80**. Un'immagine senza `quality()` riceve la qualità predefinita di GraphicsMagick o ImageMagick.\n\n## Output\n\n`save([filename], [callback])` esegue il comando e scrive il risultato. Senza nome di file, sovrascrive il file sorgente. Il formato del file salvato deriva dall'estensione di `filename`:\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` invia il risultato a uno stream scrivibile, e `stream([type])` restituisce uno stream leggibile. Qui il formato è `type`, oppure il valore di `output()`, oppure l'estensione del file sorgente. I tipi supportati sono `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` e `ico`:\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nQuando un'immagine non ha alcuna operazione, `save()`, `pipe()` e `stream()` aggiungono da soli `minify()`.\n\n## Misurare le immagini\n\n`Image.measure(type, buffer)` legge larghezza e altezza dai primi byte di un file. `type` è un'estensione (`.png` o `png`) o un tipo MIME (`image/png`):\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nCi sono anche funzioni per ogni formato: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` e `Image.measurePSD()`. Il framework le usa per i file caricati, ed è per questo che `file.width` e `file.height` sono valorizzati per le immagini.\n\nPer misurare un file su disco, usa `image.measure(callback)` (JPG, PNG, GIF, WebP) oppure `image.identify(callback)`, che interroga lo strumento esterno e funziona con qualsiasi formato che conosce.\n\n## Immagini nelle risposte\n\nIn una route, `controller.image()` e `res.image()` caricano un'immagine, ti permettono di impostare le operazioni e inviano il risultato con una cache. `RESIZE()` crea su richiesta copie ridimensionate delle immagini statiche:\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nEntrambi sono descritti in [File statici](../../guides/static-files/). Le immagini da un FileStorage si caricano con `FILESTORAGE(name).image()`, vedi [Archiviazione dei file](../../guides/file-storage/).\n\n## Middleware di output\n\n`Image.middleware(type, fn)` registra una funzione che restituisce uno stream di trasformazione. Ogni output di quel tipo passa attraverso di esso, per esempio un ottimizzatore PNG:\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nLa funzione deve restituire un nuovo stream a ogni chiamata. Con `save()`, il risultato viene prima scritto nel file, poi passato attraverso lo stream e scritto di nuovo.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"JabdVC1cH61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/images/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Obrázky","summary":"Mení veľkosť, orezáva, konvertuje a meria obrázky pomocou modulu Image a nástroja GraphicsMagick alebo ImageMagick.","markdown":"---\ntitle: \"Obrázky\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/images/\nupdated: 2026-11-16T15:50:05.282Z\n---\n\n# Obrázky\n\n> Mení veľkosť, orezáva, konvertuje a meria obrázky pomocou modulu Image a nástroja GraphicsMagick alebo ImageMagick.\n\nGlobálny objekt `Image` spracúva obrázky: zmenu veľkosti, orezanie, otáčanie, filtre, vodoznaky a konverziu formátov. Samotné pixely nespracúva. Zostaví príkazový riadok a spustí **GraphicsMagick** alebo **ImageMagick**, takže jeden z nich musí byť na serveri nainštalovaný.\n\n```js\nvar image = Image.load(PATH.public('photos/beach.jpg'));\nimage.resizeCenter(400, 300);\nimage.quality(85);\nimage.save(PATH.public('photos/beach-small.jpg'), function(err) {\n\terr && console.error(err);\n});\n```\n\nModul tiež meria veľkosť obrázkov (JPG, PNG, GIF, WebP, SVG, BMP, PSD) z buffera, v čistom JavaScripte, bez akéhokoľvek externého nástroja.\n\n## Požiadavky\n\nNainštaluj jeden z nástrojov a sprístupni ho v `PATH` procesu:\n\n```text\n# macOS\nbrew install graphicsmagick\n\n# Debian / Ubuntu\napt-get install graphicsmagick\n```\n\nKonfiguračný kľúč [`default_image_converter`](../../guides/configuration/) určuje nástroj:\n\n| Hodnota | Nástroj | Spúšťaný príkaz |\n| --- | --- | --- |\n| `gm` (predvolené) | GraphicsMagick | `gm convert ...` |\n| `im` | ImageMagick 6 | `convert ...` |\n| `magick` | ImageMagick 7 | `magick ...` |\n\n```text\n// /config\ndefault_image_converter : im\n```\n\nDruhý argument `Image.load()` prepíše konfiguráciu pre jeden obrázok.\n\n## Načítanie obrázka\n\n`Image.load(source, [converter], [width], [height])` vytvorí objekt `Image`; `Image.init()` je tá istá funkcia. Zdrojom je názov súboru, čitateľný stream alebo `Buffer`:\n\n```js\nvar a = Image.load('/www/photos/cat.png');      // file\nvar b = Image.load(Fs.createReadStream(path)); // stream\nvar c = Image.load(buffer, 'magick');           // Buffer, ImageMagick 7\n```\n\nPri súbore je výstupným formátom jeho prípona. Pri streame alebo bufferi je výstupný formát `jpg`, kým nezavoláš `image.output()`.\n\n## Skladanie operácií\n\nKaždá metóda pridá voľbu príkazového riadka a vráti obrázok, takže volania môžeš reťaziť. Nič sa nespustí, kým nezavoláš `save()`, `pipe()` alebo `stream()`:\n\n```js\nImage.load(filename)\n\t.resize(800)\n\t.grayscale()\n\t.quality(70)\n\t.save(PATH.temp('gray.jpg'), function(err, saved) {\n\t\tconsole.log(saved);\n\t});\n```\n\nVoľby sa nespúšťajú v poradí tvojich volaní. Každá má pevnú prioritu a framework ich pred zostavením príkazu zoradí:\n\n| Priorita | Metódy |\n| --- | --- |\n| 1 | `resize()`, `thumbnail()`, `scale()`, `filter()`, `limit()` |\n| 2 | `background()`, `fill()` |\n| 3 | `align()` (`-gravity`) |\n| 4 | `crop()`, `extent()`, prvá časť `sepia()` |\n| 5 | `quality()`, druhá časť `sepia()` |\n| 6 | `watermark()` |\n| 8 | `rotate()` |\n| 10 | `blur()`, `flip()`, `flop()`, `grayscale()`, `normalize()`, `colors()`, `bitdepth()`, `command()` (predvolené) |\n\n`rotate()` sa teda vždy spustí po `crop()`. Keď potrebuješ iné poradie, použi `command()` s vlastnou prioritou.\n\n### Zmena veľkosti\n\n| Metóda | Výsledok |\n| --- | --- |\n| `resize(w, h, [options])` | Vloží obrázok do `w` x `h` a zachová pomer strán. Jednu stranu vynechaj a dopočíta sa. |\n| `resizeCenter(w, h, [color])` | Vyplní `w` x `h` a orezá presah okolo stredu. |\n| `resizeAlign(w, h, [align], [color])` | Ako `resizeCenter()`, ale orezáva okolo `align` (`top`, `bottom left`...). |\n| `miniature(w, h, [color], [filter])` | Vloží celý obrázok do `w` x `h` a zvyšok vyplní farbou `color`. |\n| `thumbnail(w, h, [options])` | Ako `resize()`, s voľbou `-thumbnail` nástroja. |\n| `scale(w, h, [options])` | Rýchla zmena veľkosti bez filtra. |\n\n`options` je reťazec pripojený k veľkosti, s významom, aký mu dáva nástroj: `!` ignoruje pomer strán, `>` iba zmenšuje, `<` iba zväčšuje, `^` vyplní plochu, `%` číta čísla ako percentá:\n\n```js\nimage.resize(1200, 1200, '>'); // never upscale\nimage.resize(50, 50, '%');     // half the size\n```\n\n### Ďalšie operácie\n\n```js\nimage.crop(200, 200, 10, 10); // w, h, x, y\nimage.rotate(90);\nimage.flip();                 // vertical mirror\nimage.flop();                 // horizontal mirror\nimage.blur(3);\nimage.grayscale();\nimage.sepia();\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\nimage.background('#FFFFFF');\nimage.minify();               // removes EXIF and other profiles\n```\n\n`make(fn)` zavolá `fn` s obrázkom, takže môžeš operácie zoskupiť do funkcie a opakovane ju použiť:\n\n```js\nfunction avatar(image) {\n\timage.resizeCenter(128, 128);\n\timage.quality(80);\n}\n\nImage.load(filename).make(avatar).save(target);\n```\n\n## Kvalita\n\n`quality(percentage)` nastaví kvalitu kompresie (`-quality`). Bez argumentu použije **80**. Obrázok bez `quality()` dostane predvolenú kvalitu GraphicsMagick alebo ImageMagick.\n\n## Výstup\n\n`save([filename], [callback])` spustí príkaz a zapíše výsledok. Bez názvu súboru prepíše zdrojový súbor. Formát uloženého súboru vychádza z prípony `filename`:\n\n```js\nImage.load(PATH.public('photo.jpg')).resize(300).save(PATH.public('photo.webp'));\n```\n\n`pipe(stream, [type])` pošle výsledok do zapisovateľného streamu a `stream([type])` vráti čitateľný stream. Tu je formátom `type`, alebo hodnota `output()`, alebo prípona zdrojového súboru. Podporované typy sú `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` a `ico`:\n\n```js\nvar file = Fs.createWriteStream(PATH.temp('out.png'));\nImage.load(buffer).resize(100).pipe(file, 'png');\n```\n\nKeď obrázok nemá vôbec žiadnu operáciu, `save()`, `pipe()` a `stream()` samy pridajú `minify()`.\n\n## Meranie obrázkov\n\n`Image.measure(type, buffer)` prečíta šírku a výšku z prvých bajtov súboru. `type` je prípona (`.png` alebo `png`) alebo MIME typ (`image/png`):\n\n```js\nvar size = Image.measure('.png', buffer);\n// { width: 800, height: 600 }\n```\n\nExistujú aj funkcie pre jednotlivé formáty: `Image.measureJPG()`, `Image.measurePNG()`, `Image.measureGIF()`, `Image.measureWEBP()`, `Image.measureSVG()`, `Image.measureBMP()` a `Image.measurePSD()`. Framework ich používa pre nahrané súbory, preto sú pri obrázkoch vyplnené `file.width` a `file.height`.\n\nNa zmeranie súboru na disku použi `image.measure(callback)` (JPG, PNG, GIF, WebP) alebo `image.identify(callback)`, ktoré sa opýta externého nástroja a funguje pre každý formát, ktorý pozná.\n\n## Obrázky v odpovediach\n\nV trase `controller.image()` a `res.image()` načítajú obrázok, umožnia ti nastaviť operácie a pošlú výsledok s cache. `RESIZE()` vytvára zmenšené kópie statických obrázkov na požiadanie:\n\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\nObe sú popísané v [Statické súbory](../../guides/static-files/). Obrázky z FileStorage sa načítajú pomocou `FILESTORAGE(name).image()`, pozri [Úložisko súborov](../../guides/file-storage/).\n\n## Výstupný middleware\n\n`Image.middleware(type, fn)` zaregistruje funkciu, ktorá vracia transformačný stream. Každý výstup daného typu ním prechádza, napríklad optimalizátor PNG:\n\n```js\n// a stream that receives all PNG output\nImage.middleware('png', function() {\n\tvar Stream = require('stream');\n\treturn new Stream.PassThrough();\n});\n```\n\nFunkcia musí pri každom volaní vrátiť nový stream. Pri `save()` sa výsledok najprv zapíše do súboru, potom prejde streamom a zapíše sa znova.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:50:05.282Z"}
{"id":"Jabe5n2SJ61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"HTTP server: CORS, proxy and errors","summary":"Start the HTTP server, allow cross-origin requests, forward and redirect requests, and design error pages.","markdown":"---\ntitle: HTTP server: CORS, proxy and errors\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# HTTP server: CORS, proxy and errors\n\n> Start the HTTP server, allow cross-origin requests, forward and redirect requests, and design error pages.\n\nThis page covers the parts of the HTTP server that are not routes: starting the server, CORS, reverse proxies, redirects, the sitemap and error pages. Routes themselves are explained in [Routing](../routing/).\n\n## Starting the server\n\nThe start script calls `HTTP()` (or `HTTPS()` when you pass `https` keys). You can also call it yourself:\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nThe first argument is the mode: `'debug'` or `'release'`. The options are:\n\n| Option | What it does |\n| --- | --- |\n| `port` | The port. Without it, the config key `default_port` is used, and then `8000` |\n| `ip` | The address to listen on. Without it, `default_ip`, and then `0.0.0.0` |\n| `unixsocket` | Listens on a Unix socket instead of a port |\n| `unixsocket777` | Sets the permissions of the socket file to `0777` |\n| `config` | An object whose values are written into `CONF` |\n| `https` | `{ key, cert }` for an HTTPS server |\n| `middleware` | `function(listen)` that decides when the server starts listening |\n| `id` | The identifier of the instance, kept in `F.id` |\n\nA number on the command line (`node index.js 8080`) sets the port when the options do not have one. Any other argument that does not start with `--` and is not a URL is used as a Unix socket path.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\nA `key` or `cert` that contains a dot is read as a file. Without a dot, it is decoded from base64. After the start, `F.server` is the Node.js server and `F.port` and `F.ip` hold the address.\n\n## CORS\n\n`CORS()` lets browsers on other origins call your routes. It answers the preflight `OPTIONS` request itself with status `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nThe flags in the array are:\n\n- Origins: `'https://example.com'`, `'http://example.com'` or `'//example.com'`.\n- HTTP methods: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Without them, all methods are allowed.\n- A number: the `Access-Control-Max-Age` in seconds (otherwise `default_cors_maxage`, `120`).\n- `true` or `'credentials'`: sends `Access-Control-Allow-Credentials: true`.\n\nWithout origins, the config key `default_cors` gives the list. Without that, any origin is allowed. A request from an origin that is not on the list gets an empty `404`.\n\nTwo short forms cover the whole application:\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nThe routing flag `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) registers a CORS rule for that one URL. `CORS()` returns an object with `remove()`, which deletes the rule again.\n\n## Reverse proxy\n\n`PROXY(url, target)` sends every request whose path starts with `url` to another server and streams its answer back. The `url` must end with `/`.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nThe target can be an `http://` or `https://` address or the path of a Unix socket. Proxies run before redirects, middleware and routes, and also forward WebSocket connections.\n\nThe third argument says how the path is passed on:\n\n| `copypath` | `/api/users/?page=2` to `http://server/v1` becomes |\n| --- | --- |\n| not set | `/v1/api/users/?page=2` |\n| `true`, `'replace'` or `'extend'` | `/v1/users/?page=2` (the prefix is removed) |\n| `false` | `/v1` |\n\nWith a target without a path (`http://server`), `'replace'` removes the prefix and `true` keeps it. The framework adds the headers `X-Forwarded-For`, `X-Forwarded-Url` and `X-Forwarded-Host`. If the target does not answer, the client gets the error page `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Redirects\n\n`REDIRECT()` has two forms. With full addresses it redirects a whole host, before routing:\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nThe third argument keeps the path and the query, the fourth makes the redirect permanent (`301`). With paths, it creates a route that redirects one URL and keeps the query string:\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Error pages\n\nEvery error status first looks for a status route: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` and `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nWithout such a route, the framework answers with its built-in HTML page. For XHR requests (`default_errorbuilder_forxhr`) and when `default_errorbuilder_errors` is on, it answers with JSON errors instead. In middleware and file handlers, `res.throw404()` and its siblings start the same process. See also [Controllers](../controllers/).\n\n`F.error(err, name)` logs an error, and `ERROR(name)` returns a callback that does it:\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` builds the `{ success: true }` object that `$.success()` also returns. `FINISHED(stream, fn)` calls `fn` when a request, response or stream ends, and `DESTROY(stream)` closes a stream.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabe5n2SJ61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"HTTP-Server: CORS, Proxy und Fehler","summary":"Starte den HTTP-Server, erlaube Cross-Origin-Requests, leite Requests weiter und um und gestalte Fehlerseiten.","markdown":"---\ntitle: HTTP-Server: CORS, Proxy und Fehler\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# HTTP-Server: CORS, Proxy und Fehler\n\n> Starte den HTTP-Server, erlaube Cross-Origin-Requests, leite Requests weiter und um und gestalte Fehlerseiten.\n\nDiese Seite behandelt die Teile des HTTP-Servers, die keine Routen sind: den Start des Servers, CORS, Reverse Proxies, Weiterleitungen, die Sitemap und Fehlerseiten. Die Routen selbst werden in [Routing](../routing/) erklärt.\n\n## Den Server starten\n\nDas Startskript ruft `HTTP()` auf (oder `HTTPS()`, wenn du `https`-Schlüssel übergibst). Du kannst es auch selbst aufrufen:\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nDas erste Argument ist der Modus: `'debug'` oder `'release'`. Die Optionen sind:\n\n| Option | Was sie tut |\n| --- | --- |\n| `port` | Der Port. Ohne ihn wird der Konfigurationsschlüssel `default_port` verwendet, danach `8000` |\n| `ip` | Die Adresse, auf der gelauscht wird. Ohne sie `default_ip`, danach `0.0.0.0` |\n| `unixsocket` | Lauscht auf einem Unix-Socket statt auf einem Port |\n| `unixsocket777` | Setzt die Berechtigungen der Socket-Datei auf `0777` |\n| `config` | Ein Objekt, dessen Werte in `CONF` geschrieben werden |\n| `https` | `{ key, cert }` für einen HTTPS-Server |\n| `middleware` | `function(listen)`, die entscheidet, wann der Server zu lauschen beginnt |\n| `id` | Die Kennung der Instanz, gespeichert in `F.id` |\n\nEine Zahl auf der Kommandozeile (`node index.js 8080`) setzt den Port, wenn die Optionen keinen haben. Jedes andere Argument, das nicht mit `--` beginnt und keine URL ist, wird als Pfad eines Unix-Sockets verwendet.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\nEin `key` oder `cert` mit einem Punkt wird als Datei gelesen. Ohne Punkt wird er aus Base64 dekodiert. Nach dem Start ist `F.server` der Node.js-Server, und `F.port` und `F.ip` enthalten die Adresse.\n\n## CORS\n\nMit `CORS()` dürfen Browser von anderen Origins deine Routen aufrufen. Es beantwortet den Preflight-Request `OPTIONS` selbst mit dem Status `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nDie Flags im Array sind:\n\n- Origins: `'https://example.com'`, `'http://example.com'` oder `'//example.com'`.\n- HTTP-Methoden: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Ohne sie sind alle Methoden erlaubt.\n- Eine Zahl: das `Access-Control-Max-Age` in Sekunden (sonst `default_cors_maxage`, `120`).\n- `true` oder `'credentials'`: sendet `Access-Control-Allow-Credentials: true`.\n\nOhne Origins liefert der Konfigurationsschlüssel `default_cors` die Liste. Ohne diesen ist jeder Origin erlaubt. Ein Request von einem Origin, der nicht in der Liste steht, bekommt eine leere `404`.\n\nZwei Kurzformen decken die ganze Anwendung ab:\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nDas Routing-Flag `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) registriert eine CORS-Regel für genau diese eine URL. `CORS()` gibt ein Objekt mit `remove()` zurück, das die Regel wieder löscht.\n\n## Reverse Proxy\n\n`PROXY(url, target)` schickt jeden Request, dessen Pfad mit `url` beginnt, an einen anderen Server und streamt dessen Antwort zurück. Die `url` muss mit `/` enden.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nDas Ziel kann eine `http://`- oder `https://`-Adresse oder der Pfad eines Unix-Sockets sein. Proxies laufen vor Weiterleitungen, Middleware und Routen und leiten auch WebSocket-Verbindungen weiter.\n\nDas dritte Argument legt fest, wie der Pfad weitergegeben wird:\n\n| `copypath` | `/api/users/?page=2` an `http://server/v1` wird zu |\n| --- | --- |\n| nicht gesetzt | `/v1/api/users/?page=2` |\n| `true`, `'replace'` oder `'extend'` | `/v1/users/?page=2` (das Präfix wird entfernt) |\n| `false` | `/v1` |\n\nBei einem Ziel ohne Pfad (`http://server`) entfernt `'replace'` das Präfix und `true` behält es. Das Framework fügt die Header `X-Forwarded-For`, `X-Forwarded-Url` und `X-Forwarded-Host` hinzu. Antwortet das Ziel nicht, bekommt der Client die Fehlerseite `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Weiterleitungen\n\n`REDIRECT()` hat zwei Formen. Mit vollständigen Adressen leitet es einen ganzen Host um, noch vor dem Routing:\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nDas dritte Argument behält Pfad und Query, das vierte macht die Weiterleitung permanent (`301`). Mit Pfaden erzeugt es eine Route, die eine URL umleitet und den Query-String behält:\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Fehlerseiten\n\nJeder Fehlerstatus sucht zuerst nach einer Status-Route: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` und `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nOhne eine solche Route antwortet das Framework mit seiner eingebauten HTML-Seite. Bei XHR-Requests (`default_errorbuilder_forxhr`) und wenn `default_errorbuilder_errors` aktiv ist, antwortet es stattdessen mit JSON-Fehlern. In Middleware und Datei-Handlern startet `res.throw404()` und seine Geschwister denselben Ablauf. Siehe auch [Controller](../controllers/).\n\n`F.error(err, name)` protokolliert einen Fehler, und `ERROR(name)` gibt einen Callback zurück, der das tut:\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` baut das Objekt `{ success: true }`, das auch `$.success()` zurückgibt. `FINISHED(stream, fn)` ruft `fn` auf, wenn ein Request, eine Response oder ein Stream endet, und `DESTROY(stream)` schließt einen Stream.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabe5n2SJ61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Servidor HTTP: CORS, proxy y errores","summary":"Inicia el servidor HTTP, permite peticiones de otros orígenes, reenvía y redirige peticiones, y diseña páginas de error.","markdown":"---\ntitle: Servidor HTTP: CORS, proxy y errores\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Servidor HTTP: CORS, proxy y errores\n\n> Inicia el servidor HTTP, permite peticiones de otros orígenes, reenvía y redirige peticiones, y diseña páginas de error.\n\nEsta página cubre las partes del servidor HTTP que no son rutas: iniciar el servidor, CORS, proxies inversos, redirecciones, el sitemap y las páginas de error. Las rutas en sí se explican en [Enrutamiento](../routing/).\n\n## Iniciar el servidor\n\nEl script de inicio llama a `HTTP()` (o a `HTTPS()` cuando pasas las claves `https`). También puedes llamarlo tú mismo:\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nEl primer argumento es el modo: `'debug'` o `'release'`. Las opciones son:\n\n| Opción | Qué hace |\n| --- | --- |\n| `port` | El puerto. Sin él, se usa la clave de configuración `default_port` y, después, `8000` |\n| `ip` | La dirección en la que escuchar. Sin ella, `default_ip` y, después, `0.0.0.0` |\n| `unixsocket` | Escucha en un socket Unix en lugar de en un puerto |\n| `unixsocket777` | Establece los permisos del archivo del socket a `0777` |\n| `config` | Un objeto cuyos valores se escriben en `CONF` |\n| `https` | `{ key, cert }` para un servidor HTTPS |\n| `middleware` | `function(listen)` que decide cuándo empieza a escuchar el servidor |\n| `id` | El identificador de la instancia, guardado en `F.id` |\n\nUn número en la línea de comandos (`node index.js 8080`) define el puerto cuando las opciones no lo tienen. Cualquier otro argumento que no empiece por `--` y no sea una URL se usa como ruta de un socket Unix.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\nUn `key` o `cert` que contiene un punto se lee como archivo. Sin punto, se decodifica desde base64. Tras el inicio, `F.server` es el servidor de Node.js y `F.port` y `F.ip` contienen la dirección.\n\n## CORS\n\n`CORS()` permite que los navegadores de otros orígenes llamen a tus rutas. Responde por sí mismo a la petición preflight `OPTIONS` con el estado `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nLos flags del array son:\n\n- Orígenes: `'https://example.com'`, `'http://example.com'` o `'//example.com'`.\n- Métodos HTTP: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Sin ellos, se permiten todos los métodos.\n- Un número: el `Access-Control-Max-Age` en segundos (si no, `default_cors_maxage`, `120`).\n- `true` o `'credentials'`: envía `Access-Control-Allow-Credentials: true`.\n\nSin orígenes, la clave de configuración `default_cors` da la lista. Sin ella, se permite cualquier origen. Una petición de un origen que no está en la lista recibe un `404` vacío.\n\nDos formas cortas cubren toda la aplicación:\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nEl flag de enrutamiento `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) registra una regla CORS para esa URL concreta. `CORS()` devuelve un objeto con `remove()`, que vuelve a eliminar la regla.\n\n## Proxy inverso\n\n`PROXY(url, target)` envía a otro servidor cada petición cuya ruta empieza por `url` y devuelve su respuesta en streaming. La `url` debe terminar en `/`.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nEl destino puede ser una dirección `http://` o `https://` o la ruta de un socket Unix. Los proxies se ejecutan antes que las redirecciones, el middleware y las rutas, y también reenvían las conexiones WebSocket.\n\nEl tercer argumento indica cómo se transmite la ruta:\n\n| `copypath` | `/api/users/?page=2` hacia `http://server/v1` se convierte en |\n| --- | --- |\n| sin definir | `/v1/api/users/?page=2` |\n| `true`, `'replace'` o `'extend'` | `/v1/users/?page=2` (se quita el prefijo) |\n| `false` | `/v1` |\n\nCon un destino sin ruta (`http://server`), `'replace'` quita el prefijo y `true` lo conserva. El framework añade las cabeceras `X-Forwarded-For`, `X-Forwarded-Url` y `X-Forwarded-Host`. Si el destino no responde, el cliente recibe la página de error `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Redirecciones\n\n`REDIRECT()` tiene dos formas. Con direcciones completas redirige un host entero, antes del enrutamiento:\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nEl tercer argumento conserva la ruta y la query, el cuarto hace que la redirección sea permanente (`301`). Con rutas, crea una ruta que redirige una URL y conserva el query string:\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Páginas de error\n\nCada estado de error busca primero una ruta de estado: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` y `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nSin una ruta así, el framework responde con su página HTML integrada. Para peticiones XHR (`default_errorbuilder_forxhr`) y cuando `default_errorbuilder_errors` está activado, responde en su lugar con errores JSON. En el middleware y en los manejadores de archivos, `res.throw404()` y sus métodos hermanos inician el mismo proceso. Consulta también [Controladores](../controllers/).\n\n`F.error(err, name)` registra un error en el log, y `ERROR(name)` devuelve un callback que lo hace:\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` construye el objeto `{ success: true }` que también devuelve `$.success()`. `FINISHED(stream, fn)` llama a `fn` cuando termina una petición, una respuesta o un stream, y `DESTROY(stream)` cierra un stream.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabe5n2SJ61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Serveur HTTP : CORS, proxy et erreurs","summary":"Démarre le serveur HTTP, autorise les requêtes cross-origin, transmets et redirige des requêtes, et conçois les pages d'erreur.","markdown":"---\ntitle: Serveur HTTP : CORS, proxy et erreurs\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Serveur HTTP : CORS, proxy et erreurs\n\n> Démarre le serveur HTTP, autorise les requêtes cross-origin, transmets et redirige des requêtes, et conçois les pages d'erreur.\n\nCette page couvre les parties du serveur HTTP qui ne sont pas des routes : le démarrage du serveur, CORS, les reverse proxies, les redirections, le sitemap et les pages d'erreur. Les routes elles-mêmes sont expliquées dans [Routage](../routing/).\n\n## Démarrer le serveur\n\nLe script de démarrage appelle `HTTP()` (ou `HTTPS()` lorsque tu passes des clés `https`). Tu peux aussi l'appeler toi-même :\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nLe premier argument est le mode : `'debug'` ou `'release'`. Les options sont :\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `port` | Le port. Sans lui, la clé de configuration `default_port` est utilisée, puis `8000` |\n| `ip` | L'adresse d'écoute. Sans elle, `default_ip`, puis `0.0.0.0` |\n| `unixsocket` | Écoute sur un socket Unix au lieu d'un port |\n| `unixsocket777` | Règle les permissions du fichier socket sur `0777` |\n| `config` | Un objet dont les valeurs sont écrites dans `CONF` |\n| `https` | `{ key, cert }` pour un serveur HTTPS |\n| `middleware` | `function(listen)` qui décide quand le serveur commence à écouter |\n| `id` | L'identifiant de l'instance, conservé dans `F.id` |\n\nUn nombre sur la ligne de commande (`node index.js 8080`) définit le port lorsque les options n'en ont pas. Tout autre argument qui ne commence pas par `--` et n'est pas une URL est utilisé comme chemin de socket Unix.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\nUne `key` ou un `cert` qui contient un point est lu comme un fichier. Sans point, il est décodé depuis le base64. Après le démarrage, `F.server` est le serveur Node.js et `F.port` et `F.ip` contiennent l'adresse.\n\n## CORS\n\n`CORS()` permet aux navigateurs d'autres origines d'appeler tes routes. Elle répond elle-même à la requête préliminaire `OPTIONS` avec le statut `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nLes flags du tableau sont :\n\n- Origines : `'https://example.com'`, `'http://example.com'` ou `'//example.com'`.\n- Méthodes HTTP : `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Sans elles, toutes les méthodes sont autorisées.\n- Un nombre : le `Access-Control-Max-Age` en secondes (sinon `default_cors_maxage`, `120`).\n- `true` ou `'credentials'` : envoie `Access-Control-Allow-Credentials: true`.\n\nSans origines, la clé de configuration `default_cors` fournit la liste. Sans elle, toute origine est autorisée. Une requête provenant d'une origine absente de la liste reçoit une `404` vide.\n\nDeux formes courtes couvrent toute l'application :\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nLe flag de routage `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) enregistre une règle CORS pour cette seule URL. `CORS()` renvoie un objet avec `remove()`, qui supprime à nouveau la règle.\n\n## Reverse proxy\n\n`PROXY(url, target)` envoie chaque requête dont le chemin commence par `url` vers un autre serveur et renvoie sa réponse en flux. L'`url` doit se terminer par `/`.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nLa cible peut être une adresse `http://` ou `https://` ou le chemin d'un socket Unix. Les proxies s'exécutent avant les redirections, le middleware et les routes, et transmettent aussi les connexions WebSocket.\n\nLe troisième argument indique comment le chemin est transmis :\n\n| `copypath` | `/api/users/?page=2` vers `http://server/v1` devient |\n| --- | --- |\n| non défini | `/v1/api/users/?page=2` |\n| `true`, `'replace'` ou `'extend'` | `/v1/users/?page=2` (le préfixe est retiré) |\n| `false` | `/v1` |\n\nAvec une cible sans chemin (`http://server`), `'replace'` retire le préfixe et `true` le conserve. Le framework ajoute les en-têtes `X-Forwarded-For`, `X-Forwarded-Url` et `X-Forwarded-Host`. Si la cible ne répond pas, le client reçoit la page d'erreur `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Redirections\n\n`REDIRECT()` a deux formes. Avec des adresses complètes, elle redirige un hôte entier, avant le routage :\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nLe troisième argument conserve le chemin et la query, le quatrième rend la redirection permanente (`301`). Avec des chemins, elle crée une route qui redirige une URL et conserve la query string :\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Pages d'erreur\n\nChaque statut d'erreur cherche d'abord une route de statut : `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` et `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nSans une telle route, le framework répond avec sa page HTML intégrée. Pour les requêtes XHR (`default_errorbuilder_forxhr`) et lorsque `default_errorbuilder_errors` est activé, il répond plutôt avec des erreurs JSON. Dans le middleware et les gestionnaires de fichiers, `res.throw404()` et ses équivalents lancent le même processus. Voir aussi [Contrôleurs](../controllers/).\n\n`F.error(err, name)` journalise une erreur, et `ERROR(name)` renvoie un callback qui le fait :\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` construit l'objet `{ success: true }` que renvoie aussi `$.success()`. `FINISHED(stream, fn)` appelle `fn` lorsqu'une requête, une réponse ou un flux se termine, et `DESTROY(stream)` ferme un flux.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabe5n2SJ61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Server HTTP: CORS, proxy ed errori","summary":"Avvia il server HTTP, consenti richieste cross-origin, inoltra e reindirizza le richieste e progetta le pagine di errore.","markdown":"---\ntitle: Server HTTP: CORS, proxy ed errori\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Server HTTP: CORS, proxy ed errori\n\n> Avvia il server HTTP, consenti richieste cross-origin, inoltra e reindirizza le richieste e progetta le pagine di errore.\n\nQuesta pagina tratta le parti del server HTTP che non sono route: avvio del server, CORS, reverse proxy, redirect, sitemap e pagine di errore. Le route vere e proprie sono spiegate in [Routing](../routing/).\n\n## Avviare il server\n\nLo script di avvio chiama `HTTP()` (oppure `HTTPS()` quando passi le chiavi `https`). Puoi anche chiamarla tu stesso:\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nIl primo argomento è la modalità: `'debug'` o `'release'`. Le opzioni sono:\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `port` | La porta. Senza di essa si usa la chiave di configurazione `default_port`, e poi `8000` |\n| `ip` | L'indirizzo su cui mettersi in ascolto. Senza di esso, `default_ip`, e poi `0.0.0.0` |\n| `unixsocket` | Si mette in ascolto su un socket Unix invece che su una porta |\n| `unixsocket777` | Imposta i permessi del file del socket a `0777` |\n| `config` | Un oggetto i cui valori vengono scritti in `CONF` |\n| `https` | `{ key, cert }` per un server HTTPS |\n| `middleware` | `function(listen)` che decide quando il server inizia ad ascoltare |\n| `id` | L'identificatore dell'istanza, conservato in `F.id` |\n\nUn numero sulla riga di comando (`node index.js 8080`) imposta la porta quando le opzioni non ne hanno una. Qualsiasi altro argomento che non inizia con `--` e non è un URL viene usato come percorso di un socket Unix.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\nUn `key` o `cert` che contiene un punto viene letto come file. Senza punto, viene decodificato da base64. Dopo l'avvio, `F.server` è il server Node.js e `F.port` e `F.ip` contengono l'indirizzo.\n\n## CORS\n\n`CORS()` permette ai browser di altre origini di chiamare le tue route. Risponde direttamente alla richiesta preflight `OPTIONS` con lo stato `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nI flag nell'array sono:\n\n- Origini: `'https://example.com'`, `'http://example.com'` o `'//example.com'`.\n- Metodi HTTP: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Senza di essi, tutti i metodi sono consentiti.\n- Un numero: il `Access-Control-Max-Age` in secondi (altrimenti `default_cors_maxage`, `120`).\n- `true` o `'credentials'`: invia `Access-Control-Allow-Credentials: true`.\n\nSenza origini, la chiave di configurazione `default_cors` fornisce l'elenco. Senza quella, qualsiasi origine è consentita. Una richiesta da un'origine che non è nell'elenco riceve un `404` vuoto.\n\nDue forme brevi coprono l'intera applicazione:\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nIl flag di routing `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) registra una regola CORS per quel singolo URL. `CORS()` restituisce un oggetto con `remove()`, che elimina di nuovo la regola.\n\n## Reverse proxy\n\n`PROXY(url, target)` invia ogni richiesta il cui percorso inizia con `url` a un altro server e ne restituisce la risposta in streaming. L'`url` deve terminare con `/`.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nLa destinazione può essere un indirizzo `http://` o `https://` oppure il percorso di un socket Unix. I proxy vengono eseguiti prima di redirect, middleware e route, e inoltrano anche le connessioni WebSocket.\n\nIl terzo argomento indica come viene passato il percorso:\n\n| `copypath` | `/api/users/?page=2` verso `http://server/v1` diventa |\n| --- | --- |\n| non impostato | `/v1/api/users/?page=2` |\n| `true`, `'replace'` o `'extend'` | `/v1/users/?page=2` (il prefisso viene rimosso) |\n| `false` | `/v1` |\n\nCon una destinazione senza percorso (`http://server`), `'replace'` rimuove il prefisso e `true` lo mantiene. Il framework aggiunge gli header `X-Forwarded-For`, `X-Forwarded-Url` e `X-Forwarded-Host`. Se la destinazione non risponde, il client riceve la pagina di errore `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Redirect\n\n`REDIRECT()` ha due forme. Con indirizzi completi reindirizza un intero host, prima del routing:\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nIl terzo argomento mantiene il percorso e la query, il quarto rende il redirect permanente (`301`). Con i percorsi, crea una route che reindirizza un URL e mantiene la query string:\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Pagine di errore\n\nOgni stato di errore cerca prima una route di stato: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` e `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nSenza una route di questo tipo, il framework risponde con la sua pagina HTML integrata. Per le richieste XHR (`default_errorbuilder_forxhr`) e quando `default_errorbuilder_errors` è attivo, risponde invece con errori JSON. Nei middleware e nei gestori di file, `res.throw404()` e i metodi analoghi avviano lo stesso processo. Vedi anche [Controller](../controllers/).\n\n`F.error(err, name)` registra un errore nel log, e `ERROR(name)` restituisce una callback che lo fa:\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` costruisce l'oggetto `{ success: true }` che restituisce anche `$.success()`. `FINISHED(stream, fn)` chiama `fn` quando una richiesta, una risposta o uno stream termina, e `DESTROY(stream)` chiude uno stream.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabe5n2SJ61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/http-server/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"HTTP server: CORS, proxy a chyby","summary":"Spusti HTTP server, povoľ požiadavky z iných originov, presmeruj a preposielaj požiadavky a navrhni chybové stránky.","markdown":"---\ntitle: HTTP server: CORS, proxy a chyby\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/http-server/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# HTTP server: CORS, proxy a chyby\n\n> Spusti HTTP server, povoľ požiadavky z iných originov, presmeruj a preposielaj požiadavky a navrhni chybové stránky.\n\nTáto stránka pokrýva časti HTTP servera, ktoré nie sú trasy: spustenie servera, CORS, reverzné proxy, presmerovania, sitemapu a chybové stránky. Samotné trasy sú vysvetlené v časti [Smerovanie](../routing/).\n\n## Spustenie servera\n\nŠtartovací skript volá `HTTP()` (alebo `HTTPS()`, keď odovzdáš kľúče `https`). Môžeš ho zavolať aj sám:\n\n```js\nrequire('total4');\n\nHTTP('release', {\n\tport: 8000,\n\tip: '127.0.0.1',\n\tconfig: { name: 'My app' }\n});\n```\n\nPrvý argument je režim: `'debug'` alebo `'release'`. Možnosti sú:\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `port` | Port. Bez neho sa použije konfiguračný kľúč `default_port` a potom `8000` |\n| `ip` | Adresa, na ktorej server počúva. Bez nej `default_ip` a potom `0.0.0.0` |\n| `unixsocket` | Počúva na Unix sockete namiesto portu |\n| `unixsocket777` | Nastaví oprávnenia súboru socketu na `0777` |\n| `config` | Objekt, ktorého hodnoty sa zapíšu do `CONF` |\n| `https` | `{ key, cert }` pre HTTPS server |\n| `middleware` | `function(listen)`, ktorá rozhoduje, kedy server začne počúvať |\n| `id` | Identifikátor inštancie, uložený v `F.id` |\n\nČíslo na príkazovom riadku (`node index.js 8080`) nastaví port, keď ho možnosti neobsahujú. Akýkoľvek iný argument, ktorý nezačína `--` a nie je URL, sa použije ako cesta k Unix socketu.\n\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: { key: 'keys/server.key', cert: 'keys/server.crt' }\n});\n```\n\n`key` alebo `cert`, ktorý obsahuje bodku, sa načíta ako súbor. Bez bodky sa dekóduje z base64. Po spustení je `F.server` server Node.js a `F.port` a `F.ip` obsahujú adresu.\n\n## CORS\n\n`CORS()` umožní prehliadačom z iných originov volať tvoje trasy. Na preflight požiadavku `OPTIONS` odpovie sám so stavom `200`.\n\n```js\nexports.install = function() {\n\t// All paths below /api/, from two origins, with cookies\n\tCORS('/api/*', ['https://app.example.com', 'https://admin.example.com', 'credentials']);\n\n\tROUTE('GET /api/products/', products);\n};\n```\n\nFlagy v poli sú:\n\n- Originy: `'https://example.com'`, `'http://example.com'` alebo `'//example.com'`.\n- HTTP metódy: `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'`. Bez nich sú povolené všetky metódy.\n- Číslo: `Access-Control-Max-Age` v sekundách (inak `default_cors_maxage`, `120`).\n- `true` alebo `'credentials'`: posiela `Access-Control-Allow-Credentials: true`.\n\nBez originov dá zoznam konfiguračný kľúč `default_cors`. Bez neho je povolený akýkoľvek origin. Požiadavka z originu, ktorý nie je v zozname, dostane prázdnu odpoveď `404`.\n\nDve krátke formy pokrývajú celú aplikáciu:\n\n```js\nCORS();                                               // every path, every origin\nCORS('https://app.example.com, https://example.com'); // every path, these origins\n```\n\nFlag smerovania `cors` (`ROUTE('POST /api/orders/', fn, ['cors'])`) zaregistruje pravidlo CORS pre túto jednu URL. `CORS()` vracia objekt s `remove()`, ktorý pravidlo opäť zmaže.\n\n## Reverzné proxy\n\n`PROXY(url, target)` pošle každú požiadavku, ktorej cesta začína na `url`, na iný server a jeho odpoveď streamuje späť. `url` musí končiť znakom `/`.\n\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001');\n};\n```\n\nCieľ môže byť adresa `http://` alebo `https://` alebo cesta k Unix socketu. Proxy sa spúšťajú pred presmerovaniami, middleware a trasami a preposielajú aj spojenia WebSocket.\n\nTretí argument určuje, ako sa cesta odovzdá ďalej:\n\n| `copypath` | `/api/users/?page=2` na `http://server/v1` sa stane |\n| --- | --- |\n| nenastavené | `/v1/api/users/?page=2` |\n| `true`, `'replace'` alebo `'extend'` | `/v1/users/?page=2` (prefix sa odstráni) |\n| `false` | `/v1` |\n\nPri cieli bez cesty (`http://server`) `'replace'` prefix odstráni a `true` ho ponechá. Framework pridá hlavičky `X-Forwarded-For`, `X-Forwarded-Url` a `X-Forwarded-Host`. Ak cieľ neodpovie, klient dostane chybovú stránku `503`.\n\n```js\nPROXY('/files/', 'http://127.0.0.1:8002', 'replace', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n}, null, req => req.method === 'GET', 5000);\n```\n\n## Presmerovania\n\n`REDIRECT()` má dve formy. S úplnými adresami presmeruje celý host, ešte pred smerovaním:\n\n```js\n// http://example.com/anything -> https://www.example.com/anything\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nTretí argument ponechá cestu a query, štvrtý urobí presmerovanie trvalým (`301`). S cestami vytvorí trasu, ktorá presmeruje jednu URL a ponechá query string:\n\n```js\nREDIRECT('/old-shop/', '/shop/', true); // 301 Moved Permanently\nREDIRECT('/docs.pdf', 'https://cdn.example.com/docs.pdf');\n```\n\n## Chybové stránky\n\nKaždý chybový stav najprv hľadá stavovú trasu: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` a `#503`.\n\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.view('500', { error: this.exception });\n}\n```\n\nBez takej trasy framework odpovie svojou vstavanou HTML stránkou. Pri XHR požiadavkách (`default_errorbuilder_forxhr`) a keď je zapnuté `default_errorbuilder_errors`, odpovie namiesto toho chybami v JSON. V middleware a obsluhe súborov spustí rovnaký proces `res.throw404()` a jej príbuzné metódy. Pozri aj [Kontroléry](../controllers/).\n\n`F.error(err, name)` zaloguje chybu a `ERROR(name)` vráti callback, ktorý to urobí:\n\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n`SUCCESS()` vytvorí objekt `{ success: true }`, ktorý vracia aj `$.success()`. `FINISHED(stream, fn)` zavolá `fn`, keď skončí požiadavka, odpoveď alebo stream, a `DESTROY(stream)` stream zatvorí.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Sitemap","summary":"Describe the pages of a website in the sitemap file and use it for navigation and breadcrumbs.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Describe the pages of a website in the sitemap file and use it for navigation and breadcrumbs.\n\nThe file `sitemap` in the root of the application describes the pages of a website. Each line is `id : title --> url --> parent`:\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nLines that start with `#` or `// ` are comments. `@(...)` around a title or URL translates it with the [localization](../localization/) resources. `{0}` is a placeholder that you fill later, and a URL that ends with `*` is a wildcard.\n\nA route can use the ID instead of the URL. Without an action, the route renders the view with the name of the ID (`index` for `/`):\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` also works in `WEBSOCKET()`, `MERGE()`, `MAP()` and `LOCALIZE()`. A route with an unknown ID throws an error.\n\nFor an ID route with a view name or no action, the framework loads the breadcrumb itself; in your own action call `this.sitemap()`. It also sets the page title to the name of the current item. Views read the breadcrumb as `sitemap`:\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` returns the breadcrumb outside a controller, and `F.sitemap_navigation(parent)` the items with one parent, for menus.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Sitemap","summary":"Beschreibe die Seiten einer Website in der Datei sitemap und nutze sie für Navigation und Breadcrumbs.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Beschreibe die Seiten einer Website in der Datei sitemap und nutze sie für Navigation und Breadcrumbs.\n\nDie Datei `sitemap` im Wurzelverzeichnis der Anwendung beschreibt die Seiten einer Website. Jede Zeile ist `id : title --> url --> parent`:\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nZeilen, die mit `#` oder `// ` beginnen, sind Kommentare. `@(...)` um einen Titel oder eine URL übersetzt ihn mit den Ressourcen der [Lokalisierung](../localization/). `{0}` ist ein Platzhalter, den du später füllst, und eine URL, die mit `*` endet, ist ein Wildcard.\n\nEine Route kann statt der URL die ID verwenden. Ohne Action rendert die Route die View mit dem Namen der ID (`index` für `/`):\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` funktioniert auch in `WEBSOCKET()`, `MERGE()`, `MAP()` und `LOCALIZE()`. Eine Route mit einer unbekannten ID wirft einen Fehler.\n\nBei einer ID-Route mit einem View-Namen oder ohne Action lädt das Framework den Breadcrumb selbst; in deiner eigenen Action rufst du `this.sitemap()` auf. Es setzt auch den Seitentitel auf den Namen des aktuellen Eintrags. Views lesen den Breadcrumb als `sitemap`:\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` gibt den Breadcrumb außerhalb eines Controllers zurück, und `F.sitemap_navigation(parent)` die Einträge mit einem bestimmten Elternelement, für Menüs.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Sitemap","summary":"Describe las páginas de un sitio en el archivo sitemap y úsalo para la navegación y las migas de pan.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Describe las páginas de un sitio en el archivo sitemap y úsalo para la navegación y las migas de pan.\n\nEl archivo `sitemap` de la raíz de la aplicación describe las páginas de un sitio web. Cada línea es `id : title --> url --> parent`:\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nLas líneas que empiezan por `#` o `// ` son comentarios. `@(...)` alrededor de un título o de una URL lo traduce con los recursos de [localización](../localization/). `{0}` es un marcador que rellenas después, y una URL que termina en `*` es un comodín.\n\nUna ruta puede usar el ID en lugar de la URL. Sin acción, la ruta renderiza la vista con el nombre del ID (`index` para `/`):\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` también funciona en `WEBSOCKET()`, `MERGE()`, `MAP()` y `LOCALIZE()`. Una ruta con un ID desconocido lanza un error.\n\nEn una ruta con ID que tiene un nombre de vista o no tiene acción, el framework carga la ruta de navegación (breadcrumb) por sí mismo; en tu propia acción, llama a `this.sitemap()`. También establece el título de la página con el nombre del elemento actual. Las vistas leen el breadcrumb como `sitemap`:\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` devuelve el breadcrumb fuera de un controlador, y `F.sitemap_navigation(parent)` los elementos con un mismo padre, para menús.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Sitemap","summary":"Décris les pages d'un site dans le fichier sitemap et utilise-le pour la navigation et le fil d'Ariane.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Décris les pages d'un site dans le fichier sitemap et utilise-le pour la navigation et le fil d'Ariane.\n\nLe fichier `sitemap` à la racine de l'application décrit les pages d'un site web. Chaque ligne est `id : title --> url --> parent` :\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nLes lignes qui commencent par `#` ou `// ` sont des commentaires. `@(...)` autour d'un titre ou d'une URL le traduit avec les ressources de [localisation](../localization/). `{0}` est un placeholder que tu remplis plus tard, et une URL qui se termine par `*` est un joker.\n\nUne route peut utiliser l'ID au lieu de l'URL. Sans action, la route rend la vue portant le nom de l'ID (`index` pour `/`) :\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` fonctionne aussi dans `WEBSOCKET()`, `MERGE()`, `MAP()` et `LOCALIZE()`. Une route avec un ID inconnu lève une erreur.\n\nPour une route à ID avec un nom de vue ou sans action, le framework charge lui-même le fil d'Ariane ; dans ta propre action, appelle `this.sitemap()`. Il définit aussi le titre de la page avec le nom de l'élément courant. Les vues lisent le fil d'Ariane sous le nom `sitemap` :\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` renvoie le fil d'Ariane hors d'un contrôleur, et `F.sitemap_navigation(parent)` les éléments ayant un même parent, pour les menus.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Sitemap","summary":"Descrivi le pagine di un sito nel file sitemap e usalo per la navigazione e il breadcrumb.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Descrivi le pagine di un sito nel file sitemap e usalo per la navigazione e il breadcrumb.\n\nIl file `sitemap` nella radice dell'applicazione descrive le pagine di un sito web. Ogni riga è `id : title --> url --> parent`:\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nLe righe che iniziano con `#` o `// ` sono commenti. `@(...)` attorno a un titolo o a un URL lo traduce con le risorse di [localizzazione](../localization/). `{0}` è un segnaposto che compili in seguito, e un URL che termina con `*` è un carattere jolly.\n\nUna route può usare l'ID al posto dell'URL. Senza un'azione, la route esegue il rendering della vista con il nome dell'ID (`index` per `/`):\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` funziona anche in `WEBSOCKET()`, `MERGE()`, `MAP()` e `LOCALIZE()`. Una route con un ID sconosciuto lancia un errore.\n\nPer una route con ID che ha un nome di vista o nessuna azione, il framework carica da sé il breadcrumb; nella tua azione chiama `this.sitemap()`. Imposta anche il titolo della pagina sul nome dell'elemento corrente. Le viste leggono il breadcrumb come `sitemap`:\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` restituisce il breadcrumb fuori da un controller, e `F.sitemap_navigation(parent)` gli elementi con un dato padre, per i menu.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjqg3gX61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/sitemap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Sitemap","summary":"Opíš stránky webu v súbore sitemap a používaj ho na navigáciu a omrvinkovú navigáciu.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/sitemap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Sitemap\n\n> Opíš stránky webu v súbore sitemap a používaj ho na navigáciu a omrvinkovú navigáciu.\n\nSúbor `sitemap` v koreni aplikácie opisuje stránky webu. Každý riadok má tvar `id : title --> url --> parent`:\n\n```text\n// sitemap\nhomepage : Homepage            --> /\nproducts : Products            --> /products/          --> homepage\ndetail   : {0}                 --> /products/{0}/      --> products\ncontact  : @(Contact)          --> /contact/           --> homepage\n```\n\nRiadky, ktoré začínajú `#` alebo `// `, sú komentáre. `@(...)` okolo názvu alebo URL ho preloží pomocou zdrojov [lokalizácie](../localization/). `{0}` je zástupný symbol, ktorý vyplníš neskôr, a URL, ktorá končí `*`, je zástupný znak (wildcard).\n\nTrasa môže namiesto URL použiť ID. Bez akcie trasa vykreslí view s názvom ID (`index` pre `/`):\n\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', 'Product ' + id);\n\tthis.view('products/detail');\n}\n```\n\n`#id` funguje aj vo `WEBSOCKET()`, `MERGE()`, `MAP()` a `LOCALIZE()`. Trasa s neznámym ID vyhodí chybu.\n\nPri ID trase s názvom view alebo bez akcie načíta framework navigačnú cestu (breadcrumb) sám; vo vlastnej akcii zavolaj `this.sitemap()`. Zároveň nastaví titulok stránky na názov aktuálnej položky. View čítajú navigačnú cestu ako `sitemap`:\n\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ol>\n\n<a href=\"@{sitemap_url('detail', model.id)}\">@{sitemap_name('products')}</a>\n```\n\n`SITEMAP(id)` vráti navigačnú cestu mimo kontroléra a `F.sitemap_navigation(parent)` položky s jedným rodičom, pre menu.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Cache, counters and small stores","summary":"Keep values in the in-memory cache, in files and in preferences, count statistics, and back up folders.","markdown":"---\ntitle: Cache, counters and small stores\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, counters and small stores\n\n> Keep values in the in-memory cache, in files and in preferences, count statistics, and back up folders.\n\nTotal.js has several small stores for data that does not need a full database: an in-memory cache, preferences, a persistent object, file caches, counters and two extra text databases. All of them are global functions, so every file of an app can use them.\n\n| Function | Where the data lives | Use it for |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Memory of the process | Values that expire, for example results of slow queries |\n| `FILECACHE()` | A file in the `tmp/` folder | Results that should survive a restart and expire |\n| `PREF` | `databases/preferences.json` | Settings that the app changes at run time |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | A plain object saved to a file |\n| `COUNTER()` | `databases/{name}.counter` | Daily statistics of hits or amounts |\n| `INMEMORY()` | Memory, saved to `databases/{name}.inmemory` | A small NoSQL collection kept in memory |\n| `TEXTDB()` | Files in `databases/textdb-{name}/` | A NoSQL collection split into several files |\n\n`BACKUP()` and `RESTORE()` pack files of a folder into one file and unpack them again. `MODIFY()` changes the content of views, styles, scripts and localized static files before Total.js compiles them.\n\n## The in-memory cache\n\n`CACHE(key, value, [expire])` saves a value and `CACHE(key)` reads it. The value is kept in the memory of the process, so it is lost after a restart. The expiration is a text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 5 minutes.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` is the object behind `CACHE()`. It has more methods:\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js checks the cache once a minute and removes expired items. It emits the events `cache_set` and `cache_expired` (see [Scheduling and events](../../guides/scheduling-and-events/)). The option `allow_cache_snapshot` saves the whole cache to `databases/cache.json` every minute and loads it at start, and `allow_cache_cluster` copies changes to the other processes of a cluster (see [Configuration](../../guides/configuration/)).\n\n### Read or create a value\n\n`F.cache.fn()` returns a cached value or calls your function to make it. The function receives `next(value, [expire])`:\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nA value that is `false`, `0`, `''` or `null` does not count as cached, so the function runs again.\n\n## A cache in a file\n\n`FILECACHE(id, expire, callback, maker, [encoding])` works like `F.cache.fn()`, but it saves the value to a file in the `tmp/` folder. The file stays valid until it is older than `expire`, even after a restart. The `maker` function receives `next(err, value)`:\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nThe value is saved as JSON. Pass `'utf8'` as `encoding` to keep a text as it is. See [HTTP requests](../../guides/http-requests/) for `RESTBuilder`.\n\n## Preferences\n\n`PREF` holds values that the app sets at run time and that must survive a restart, for example a token or the date of the last import. Total.js loads them at start from `databases/preferences.json`. Read a value as a property and write it with `PREF.set()`:\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nChanges are written to the file one second after the last change. To keep the preferences somewhere else (for example in SQL), replace the delegates `DEF.onPrefLoad` and `DEF.onPrefSave` in a definition file.\n\n## A persistent object\n\n`MEMORIZE([name], [delay], [skip])` reads `databases/memorize_{name}.json` (or `databases/memorize.json` without a name) and returns it as an object. Change the object and call `save()`: Total.js writes it after `delay` milliseconds (10 seconds by default), so many changes give one write.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nEvery call reads the file again and returns a new object: call `MEMORIZE()` once and keep the object. The `skip` argument lists keys that are not saved, for example temporary data.\n\n## Counters\n\n`COUNTER(name)` counts hits or amounts per day. `hit(id, [value])` adds a value in memory; about every five minutes Total.js writes the sums to `databases/{name}.counter`, one document per id and day with `sum`, `min` and `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nHits that are not written yet are lost if the process stops; call `flush()` to write them earlier.\n\n## INMEMORY and TEXTDB\n\n`INMEMORY(name)` and `TEXTDB(name)` return a database with the same methods as `NOSQL()` (see [NoSQL database](../../guides/nosql/)).\n\n- `INMEMORY()` keeps all documents in memory and writes them to `databases/{name}.inmemory` 5 seconds after a change. It is fast for a small collection that is read often. It supports `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` and `remove()`.\n- `TEXTDB()` keeps documents in the folder `databases/textdb-{name}/`, in several files of about 512 kB. Use it for a collection that grows.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Backup and restore of files\n\n`BACKUP(filename, path, [callback], [filter])` packs all files of a folder (or a list of files) into one text file. Each file is compressed with GZIP. `RESTORE(filename, target, [callback], [filter])` unpacks it into a folder.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Cache, Zähler und kleine Speicher","summary":"Werte im In-Memory-Cache, in Dateien und in Präferenzen halten, Statistiken zählen und Ordner sichern.","markdown":"---\ntitle: \"Cache, Zähler und kleine Speicher\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, Zähler und kleine Speicher\n\n> Werte im In-Memory-Cache, in Dateien und in Präferenzen halten, Statistiken zählen und Ordner sichern.\n\nTotal.js hat mehrere kleine Speicher für Daten, die keine vollständige Datenbank brauchen: einen In-Memory-Cache, Präferenzen, ein persistentes Objekt, Datei-Caches, Zähler und zwei zusätzliche Textdatenbanken. Alle sind globale Funktionen, sodass jede Datei einer App sie nutzen kann.\n\n| Funktion | Wo die Daten liegen | Wofür |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Speicher des Prozesses | Werte, die ablaufen, zum Beispiel Ergebnisse langsamer Abfragen |\n| `FILECACHE()` | Eine Datei im Ordner `tmp/` | Ergebnisse, die einen Neustart überdauern und ablaufen sollen |\n| `PREF` | `databases/preferences.json` | Einstellungen, die die App zur Laufzeit ändert |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | Ein einfaches Objekt, in einer Datei gespeichert |\n| `COUNTER()` | `databases/{name}.counter` | Tägliche Statistiken von Aufrufen oder Beträgen |\n| `INMEMORY()` | Speicher, gesichert in `databases/{name}.inmemory` | Eine kleine NoSQL-Collection im Speicher |\n| `TEXTDB()` | Dateien in `databases/textdb-{name}/` | Eine NoSQL-Collection, auf mehrere Dateien verteilt |\n\n`BACKUP()` und `RESTORE()` packen die Dateien eines Ordners in eine Datei und entpacken sie wieder. `MODIFY()` ändert den Inhalt von Views, Styles, Skripten und lokalisierten statischen Dateien, bevor Total.js sie kompiliert.\n\n## Der In-Memory-Cache\n\n`CACHE(key, value, [expire])` speichert einen Wert und `CACHE(key)` liest ihn. Der Wert liegt im Speicher des Prozesses und geht daher nach einem Neustart verloren. Der Ablauf ist ein Text wie `'5 minutes'` oder `'1 hour'` oder ein `Date`. Ohne ihn läuft der Wert nach 5 Minuten ab.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` ist das Objekt hinter `CACHE()`. Es hat weitere Methoden:\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js prüft den Cache einmal pro Minute und entfernt abgelaufene Einträge. Es löst die Events `cache_set` und `cache_expired` aus (siehe [Zeitplanung und Events](../../guides/scheduling-and-events/)). Die Option `allow_cache_snapshot` speichert den ganzen Cache jede Minute in `databases/cache.json` und lädt ihn beim Start, und `allow_cache_cluster` kopiert Änderungen zu den anderen Prozessen eines Clusters (siehe [Konfiguration](../../guides/configuration/)).\n\n### Einen Wert lesen oder erzeugen\n\n`F.cache.fn()` gibt einen gecachten Wert zurück oder ruft deine Funktion auf, um ihn zu erzeugen. Die Funktion erhält `next(value, [expire])`:\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nEin Wert, der `false`, `0`, `''` oder `null` ist, gilt nicht als gecacht, also läuft die Funktion erneut.\n\n## Ein Cache in einer Datei\n\n`FILECACHE(id, expire, callback, maker, [encoding])` funktioniert wie `F.cache.fn()`, speichert den Wert aber in einer Datei im Ordner `tmp/`. Die Datei bleibt gültig, bis sie älter als `expire` ist, auch nach einem Neustart. Die Funktion `maker` erhält `next(err, value)`:\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nDer Wert wird als JSON gespeichert. Übergib `'utf8'` als `encoding`, um einen Text unverändert zu behalten. Siehe [HTTP-Requests](../../guides/http-requests/) für `RESTBuilder`.\n\n## Präferenzen\n\n`PREF` enthält Werte, die die App zur Laufzeit setzt und die einen Neustart überdauern müssen, zum Beispiel ein Token oder das Datum des letzten Imports. Total.js lädt sie beim Start aus `databases/preferences.json`. Lies einen Wert als Eigenschaft und schreibe ihn mit `PREF.set()`:\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nÄnderungen werden eine Sekunde nach der letzten Änderung in die Datei geschrieben. Um die Präferenzen woanders zu halten (zum Beispiel in SQL), ersetze die Delegates `DEF.onPrefLoad` und `DEF.onPrefSave` in einer Definitionsdatei.\n\n## Ein persistentes Objekt\n\n`MEMORIZE([name], [delay], [skip])` liest `databases/memorize_{name}.json` (oder ohne Namen `databases/memorize.json`) und gibt es als Objekt zurück. Ändere das Objekt und rufe `save()` auf: Total.js schreibt es nach `delay` Millisekunden (standardmäßig 10 Sekunden), sodass viele Änderungen einen einzigen Schreibvorgang ergeben.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nJeder Aufruf liest die Datei erneut und gibt ein neues Objekt zurück: Rufe `MEMORIZE()` einmal auf und behalte das Objekt. Das Argument `skip` listet Schlüssel auf, die nicht gespeichert werden, zum Beispiel temporäre Daten.\n\n## Zähler\n\n`COUNTER(name)` zählt Aufrufe oder Beträge pro Tag. `hit(id, [value])` addiert einen Wert im Speicher; etwa alle fünf Minuten schreibt Total.js die Summen nach `databases/{name}.counter`, ein Dokument pro ID und Tag mit `sum`, `min` und `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nNoch nicht geschriebene Aufrufe gehen verloren, wenn der Prozess stoppt; rufe `flush()` auf, um sie früher zu schreiben.\n\n## INMEMORY und TEXTDB\n\n`INMEMORY(name)` und `TEXTDB(name)` geben eine Datenbank mit denselben Methoden wie `NOSQL()` zurück (siehe [NoSQL-Datenbank](../../guides/nosql/)).\n\n- `INMEMORY()` hält alle Dokumente im Speicher und schreibt sie 5 Sekunden nach einer Änderung nach `databases/{name}.inmemory`. Es ist schnell für eine kleine Collection, die oft gelesen wird. Es unterstützt `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` und `remove()`.\n- `TEXTDB()` hält die Dokumente im Ordner `databases/textdb-{name}/`, in mehreren Dateien von etwa 512 kB. Nutze es für eine Collection, die wächst.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Sicherung und Wiederherstellung von Dateien\n\n`BACKUP(filename, path, [callback], [filter])` packt alle Dateien eines Ordners (oder eine Liste von Dateien) in eine Textdatei. Jede Datei wird mit GZIP komprimiert. `RESTORE(filename, target, [callback], [filter])` entpackt sie in einen Ordner.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Caché, contadores y almacenes pequeños","summary":"Guarda valores en la caché en memoria, en archivos y en preferencias, cuenta estadísticas y haz copias de seguridad de carpetas.","markdown":"---\ntitle: \"Caché, contadores y almacenes pequeños\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Caché, contadores y almacenes pequeños\n\n> Guarda valores en la caché en memoria, en archivos y en preferencias, cuenta estadísticas y haz copias de seguridad de carpetas.\n\nTotal.js tiene varios almacenes pequeños para datos que no necesitan una base de datos completa: una caché en memoria, preferencias, un objeto persistente, cachés en archivo, contadores y dos bases de datos de texto adicionales. Todos son funciones globales, así que cualquier archivo de una aplicación puede usarlos.\n\n| Función | Dónde viven los datos | Úsala para |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Memoria del proceso | Valores que caducan, por ejemplo resultados de consultas lentas |\n| `FILECACHE()` | Un archivo en la carpeta `tmp/` | Resultados que deben sobrevivir a un reinicio y caducar |\n| `PREF` | `databases/preferences.json` | Ajustes que la aplicación cambia en tiempo de ejecución |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | Un objeto plano guardado en un archivo |\n| `COUNTER()` | `databases/{name}.counter` | Estadísticas diarias de visitas o importes |\n| `INMEMORY()` | Memoria, guardada en `databases/{name}.inmemory` | Una pequeña colección NoSQL mantenida en memoria |\n| `TEXTDB()` | Archivos en `databases/textdb-{name}/` | Una colección NoSQL dividida en varios archivos |\n\n`BACKUP()` y `RESTORE()` empaquetan los archivos de una carpeta en un solo archivo y los desempaquetan de nuevo. `MODIFY()` cambia el contenido de vistas, estilos, scripts y archivos estáticos localizados antes de que Total.js los compile.\n\n## La caché en memoria\n\n`CACHE(key, value, [expire])` guarda un valor y `CACHE(key)` lo lee. El valor se mantiene en la memoria del proceso, así que se pierde tras un reinicio. La caducidad es un texto como `'5 minutes'` o `'1 hour'`, o un `Date`. Sin ella, el valor caduca en 5 minutos.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` es el objeto que hay detrás de `CACHE()`. Tiene más métodos:\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js revisa la caché una vez por minuto y elimina los elementos caducados. Emite los eventos `cache_set` y `cache_expired` (consulta [Programación y eventos](../../guides/scheduling-and-events/)). La opción `allow_cache_snapshot` guarda toda la caché en `databases/cache.json` cada minuto y la carga al arrancar, y `allow_cache_cluster` copia los cambios a los otros procesos de un clúster (consulta [Configuración](../../guides/configuration/)).\n\n### Leer o crear un valor\n\n`F.cache.fn()` devuelve un valor de la caché o llama a tu función para crearlo. La función recibe `next(value, [expire])`:\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nUn valor que es `false`, `0`, `''` o `null` no cuenta como cacheado, así que la función se vuelve a ejecutar.\n\n## Una caché en un archivo\n\n`FILECACHE(id, expire, callback, maker, [encoding])` funciona como `F.cache.fn()`, pero guarda el valor en un archivo de la carpeta `tmp/`. El archivo sigue siendo válido hasta que es más antiguo que `expire`, incluso tras un reinicio. La función `maker` recibe `next(err, value)`:\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nEl valor se guarda como JSON. Pasa `'utf8'` como `encoding` para mantener un texto tal cual. Consulta [Peticiones HTTP](../../guides/http-requests/) para `RESTBuilder`.\n\n## Preferencias\n\n`PREF` contiene valores que la aplicación asigna en tiempo de ejecución y que deben sobrevivir a un reinicio, por ejemplo un token o la fecha de la última importación. Total.js los carga al arrancar desde `databases/preferences.json`. Lee un valor como una propiedad y escríbelo con `PREF.set()`:\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nLos cambios se escriben en el archivo un segundo después del último cambio. Para guardar las preferencias en otro sitio (por ejemplo en SQL), reemplaza los delegados `DEF.onPrefLoad` y `DEF.onPrefSave` en un archivo de definición.\n\n## Un objeto persistente\n\n`MEMORIZE([name], [delay], [skip])` lee `databases/memorize_{name}.json` (o `databases/memorize.json` sin nombre) y lo devuelve como un objeto. Modifica el objeto y llama a `save()`: Total.js lo escribe tras `delay` milisegundos (10 segundos por defecto), así que muchos cambios dan una sola escritura.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nCada llamada vuelve a leer el archivo y devuelve un objeto nuevo: llama a `MEMORIZE()` una vez y conserva el objeto. El argumento `skip` lista claves que no se guardan, por ejemplo datos temporales.\n\n## Contadores\n\n`COUNTER(name)` cuenta visitas o importes por día. `hit(id, [value])` suma un valor en memoria; aproximadamente cada cinco minutos Total.js escribe las sumas en `databases/{name}.counter`, un documento por id y día con `sum`, `min` y `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nLas visitas que aún no se han escrito se pierden si el proceso se detiene; llama a `flush()` para escribirlas antes.\n\n## INMEMORY y TEXTDB\n\n`INMEMORY(name)` y `TEXTDB(name)` devuelven una base de datos con los mismos métodos que `NOSQL()` (consulta [Base de datos NoSQL](../../guides/nosql/)).\n\n- `INMEMORY()` mantiene todos los documentos en memoria y los escribe en `databases/{name}.inmemory` 5 segundos después de un cambio. Es rápida para una colección pequeña que se lee a menudo. Admite `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` y `remove()`.\n- `TEXTDB()` guarda los documentos en la carpeta `databases/textdb-{name}/`, en varios archivos de unos 512 kB. Úsala para una colección que crece.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Copia de seguridad y restauración de archivos\n\n`BACKUP(filename, path, [callback], [filter])` empaqueta todos los archivos de una carpeta (o una lista de archivos) en un único archivo de texto. Cada archivo se comprime con GZIP. `RESTORE(filename, target, [callback], [filter])` lo desempaqueta en una carpeta.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Cache, compteurs et petits stockages","summary":"Conserve des valeurs dans le cache en mémoire, dans des fichiers et dans les préférences, compte des statistiques et sauvegarde des dossiers.","markdown":"---\ntitle: Cache, compteurs et petits stockages\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, compteurs et petits stockages\n\n> Conserve des valeurs dans le cache en mémoire, dans des fichiers et dans les préférences, compte des statistiques et sauvegarde des dossiers.\n\nTotal.js propose plusieurs petits stockages pour les données qui ne nécessitent pas une base de données complète : un cache en mémoire, des préférences, un objet persistant, des caches de fichiers, des compteurs et deux bases de données texte supplémentaires. Ce sont toutes des fonctions globales ; chaque fichier d'une application peut donc les utiliser.\n\n| Fonction | Emplacement des données | Utilisation |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Mémoire du processus | Valeurs qui expirent, par exemple les résultats de requêtes lentes |\n| `FILECACHE()` | Un fichier dans le dossier `tmp/` | Résultats qui doivent survivre à un redémarrage et expirer |\n| `PREF` | `databases/preferences.json` | Paramètres que l'application modifie à l'exécution |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | Un objet simple enregistré dans un fichier |\n| `COUNTER()` | `databases/{name}.counter` | Statistiques quotidiennes de visites ou de montants |\n| `INMEMORY()` | Mémoire, enregistrée dans `databases/{name}.inmemory` | Une petite collection NoSQL conservée en mémoire |\n| `TEXTDB()` | Fichiers dans `databases/textdb-{name}/` | Une collection NoSQL répartie sur plusieurs fichiers |\n\n`BACKUP()` et `RESTORE()` regroupent les fichiers d'un dossier dans un seul fichier et les extraient à nouveau. `MODIFY()` modifie le contenu des vues, des styles, des scripts et des fichiers statiques localisés avant que Total.js ne les compile.\n\n## Le cache en mémoire\n\n`CACHE(key, value, [expire])` enregistre une valeur et `CACHE(key)` la lit. La valeur est conservée dans la mémoire du processus ; elle est donc perdue après un redémarrage. L'expiration est un texte tel que `'5 minutes'` ou `'1 hour'`, ou une `Date`. Sans elle, la valeur expire au bout de 5 minutes.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` est l'objet derrière `CACHE()`. Il possède d'autres méthodes :\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js vérifie le cache une fois par minute et supprime les éléments expirés. Il émet les événements `cache_set` et `cache_expired` (voir [Planification et événements](../../guides/scheduling-and-events/)). L'option `allow_cache_snapshot` enregistre tout le cache dans `databases/cache.json` chaque minute et le charge au démarrage, et `allow_cache_cluster` copie les modifications vers les autres processus d'un cluster (voir [Configuration](../../guides/configuration/)).\n\n### Lire ou créer une valeur\n\n`F.cache.fn()` renvoie une valeur en cache ou appelle ta fonction pour la créer. La fonction reçoit `next(value, [expire])` :\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nUne valeur `false`, `0`, `''` ou `null` n'est pas considérée comme en cache ; la fonction s'exécute donc à nouveau.\n\n## Un cache dans un fichier\n\n`FILECACHE(id, expire, callback, maker, [encoding])` fonctionne comme `F.cache.fn()`, mais enregistre la valeur dans un fichier du dossier `tmp/`. Le fichier reste valide tant qu'il n'est pas plus ancien que `expire`, même après un redémarrage. La fonction `maker` reçoit `next(err, value)` :\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nLa valeur est enregistrée en JSON. Passe `'utf8'` comme `encoding` pour conserver un texte tel quel. Voir [Requêtes HTTP](../../guides/http-requests/) pour `RESTBuilder`.\n\n## Préférences\n\n`PREF` contient des valeurs que l'application définit à l'exécution et qui doivent survivre à un redémarrage, par exemple un jeton ou la date du dernier import. Total.js les charge au démarrage depuis `databases/preferences.json`. Lis une valeur comme une propriété et écris-la avec `PREF.set()` :\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nLes modifications sont écrites dans le fichier une seconde après la dernière modification. Pour conserver les préférences ailleurs (par exemple en SQL), remplace les délégués `DEF.onPrefLoad` et `DEF.onPrefSave` dans un fichier de définition.\n\n## Un objet persistant\n\n`MEMORIZE([name], [delay], [skip])` lit `databases/memorize_{name}.json` (ou `databases/memorize.json` sans nom) et le renvoie sous forme d'objet. Modifie l'objet et appelle `save()` : Total.js l'écrit après `delay` millisecondes (10 secondes par défaut) ; de nombreuses modifications donnent donc une seule écriture.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nChaque appel relit le fichier et renvoie un nouvel objet : appelle `MEMORIZE()` une seule fois et conserve l'objet. L'argument `skip` liste les clés qui ne sont pas enregistrées, par exemple des données temporaires.\n\n## Compteurs\n\n`COUNTER(name)` compte des visites ou des montants par jour. `hit(id, [value])` ajoute une valeur en mémoire ; environ toutes les cinq minutes, Total.js écrit les sommes dans `databases/{name}.counter`, un document par id et par jour avec `sum`, `min` et `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nLes visites non encore écrites sont perdues si le processus s'arrête ; appelle `flush()` pour les écrire plus tôt.\n\n## INMEMORY et TEXTDB\n\n`INMEMORY(name)` et `TEXTDB(name)` renvoient une base de données avec les mêmes méthodes que `NOSQL()` (voir [Base de données NoSQL](../../guides/nosql/)).\n\n- `INMEMORY()` conserve tous les documents en mémoire et les écrit dans `databases/{name}.inmemory` 5 secondes après une modification. Elle est rapide pour une petite collection souvent lue. Elle prend en charge `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` et `remove()`.\n- `TEXTDB()` conserve les documents dans le dossier `databases/textdb-{name}/`, dans plusieurs fichiers d'environ 512 kB. Utilise-la pour une collection qui grandit.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Sauvegarde et restauration de fichiers\n\n`BACKUP(filename, path, [callback], [filter])` regroupe tous les fichiers d'un dossier (ou une liste de fichiers) dans un seul fichier texte. Chaque fichier est compressé avec GZIP. `RESTORE(filename, target, [callback], [filter])` l'extrait dans un dossier.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Cache, counter e piccoli archivi","summary":"Conserva valori nella cache in memoria, in file e nelle preferenze, conta statistiche e fai il backup delle cartelle.","markdown":"---\ntitle: Cache, counter e piccoli archivi\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, counter e piccoli archivi\n\n> Conserva valori nella cache in memoria, in file e nelle preferenze, conta statistiche e fai il backup delle cartelle.\n\nTotal.js offre diversi piccoli archivi per dati che non richiedono un database completo: una cache in memoria, le preferenze, un oggetto persistente, cache su file, counter e due database testuali aggiuntivi. Sono tutte funzioni globali, quindi ogni file di un'app può usarle.\n\n| Funzione | Dove si trovano i dati | Usala per |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Memoria del processo | Valori che scadono, ad esempio i risultati di query lente |\n| `FILECACHE()` | Un file nella cartella `tmp/` | Risultati che devono sopravvivere a un riavvio e scadere |\n| `PREF` | `databases/preferences.json` | Impostazioni che l'app modifica durante l'esecuzione |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | Un semplice oggetto salvato in un file |\n| `COUNTER()` | `databases/{name}.counter` | Statistiche giornaliere di accessi o importi |\n| `INMEMORY()` | Memoria, salvata in `databases/{name}.inmemory` | Una piccola collezione NoSQL tenuta in memoria |\n| `TEXTDB()` | File in `databases/textdb-{name}/` | Una collezione NoSQL suddivisa in più file |\n\n`BACKUP()` e `RESTORE()` impacchettano i file di una cartella in un unico file e li spacchettano di nuovo. `MODIFY()` modifica il contenuto di viste, stili, script e file statici localizzati prima che Total.js li compili.\n\n## La cache in memoria\n\n`CACHE(key, value, [expire])` salva un valore e `CACHE(key)` lo legge. Il valore viene tenuto nella memoria del processo, quindi va perso dopo un riavvio. La scadenza è un testo come `'5 minutes'` o `'1 hour'`, oppure una `Date`. Senza di essa il valore scade dopo 5 minuti.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` è l'oggetto dietro `CACHE()`. Ha altri metodi:\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js controlla la cache una volta al minuto e rimuove gli elementi scaduti. Emette gli eventi `cache_set` e `cache_expired` (vedi [Pianificazione ed eventi](../../guides/scheduling-and-events/)). L'opzione `allow_cache_snapshot` salva l'intera cache in `databases/cache.json` ogni minuto e la carica all'avvio, e `allow_cache_cluster` copia le modifiche negli altri processi di un cluster (vedi [Configurazione](../../guides/configuration/)).\n\n### Leggere o creare un valore\n\n`F.cache.fn()` restituisce un valore in cache oppure chiama la tua funzione per crearlo. La funzione riceve `next(value, [expire])`:\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nUn valore `false`, `0`, `''` o `null` non conta come presente in cache, quindi la funzione viene eseguita di nuovo.\n\n## Una cache in un file\n\n`FILECACHE(id, expire, callback, maker, [encoding])` funziona come `F.cache.fn()`, ma salva il valore in un file nella cartella `tmp/`. Il file resta valido finché non è più vecchio di `expire`, anche dopo un riavvio. La funzione `maker` riceve `next(err, value)`:\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nIl valore viene salvato come JSON. Passa `'utf8'` come `encoding` per mantenere un testo così com'è. Vedi [Richieste HTTP](../../guides/http-requests/) per `RESTBuilder`.\n\n## Preferenze\n\n`PREF` contiene valori che l'app imposta durante l'esecuzione e che devono sopravvivere a un riavvio, ad esempio un token o la data dell'ultima importazione. Total.js li carica all'avvio da `databases/preferences.json`. Leggi un valore come proprietà e scrivilo con `PREF.set()`:\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nLe modifiche vengono scritte nel file un secondo dopo l'ultima modifica. Per conservare le preferenze altrove (ad esempio in SQL), sostituisci i delegati `DEF.onPrefLoad` e `DEF.onPrefSave` in un file di definizione.\n\n## Un oggetto persistente\n\n`MEMORIZE([name], [delay], [skip])` legge `databases/memorize_{name}.json` (o `databases/memorize.json` senza nome) e lo restituisce come oggetto. Modifica l'oggetto e chiama `save()`: Total.js lo scrive dopo `delay` millisecondi (10 secondi per impostazione predefinita), quindi molte modifiche producono una sola scrittura.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nOgni chiamata rilegge il file e restituisce un nuovo oggetto: chiama `MEMORIZE()` una volta e conserva l'oggetto. L'argomento `skip` elenca le chiavi che non vengono salvate, ad esempio dati temporanei.\n\n## Counter\n\n`COUNTER(name)` conta accessi o importi per giorno. `hit(id, [value])` aggiunge un valore in memoria; circa ogni cinque minuti Total.js scrive le somme in `databases/{name}.counter`, un documento per id e giorno con `sum`, `min` e `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nGli accessi non ancora scritti vanno persi se il processo si ferma; chiama `flush()` per scriverli prima.\n\n## INMEMORY e TEXTDB\n\n`INMEMORY(name)` e `TEXTDB(name)` restituiscono un database con gli stessi metodi di `NOSQL()` (vedi [Database NoSQL](../../guides/nosql/)).\n\n- `INMEMORY()` tiene tutti i documenti in memoria e li scrive in `databases/{name}.inmemory` 5 secondi dopo una modifica. È veloce per una piccola collezione letta spesso. Supporta `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` e `remove()`.\n- `TEXTDB()` conserva i documenti nella cartella `databases/textdb-{name}/`, in più file da circa 512 kB. Usalo per una collezione che cresce.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Backup e ripristino dei file\n\n`BACKUP(filename, path, [callback], [filter])` impacchetta tutti i file di una cartella (o un elenco di file) in un unico file di testo. Ogni file viene compresso con GZIP. `RESTORE(filename, target, [callback], [filter])` lo spacchetta in una cartella.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdpo3Sl61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Cache, počítadlá a malé úložiská","summary":"Uchovávaj hodnoty v pamäťovej cache, v súboroch a v preferenciách, počítaj štatistiky a zálohuj priečinky.","markdown":"---\ntitle: \"Cache, počítadlá a malé úložiská\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, počítadlá a malé úložiská\n\n> Uchovávaj hodnoty v pamäťovej cache, v súboroch a v preferenciách, počítaj štatistiky a zálohuj priečinky.\n\nTotal.js má niekoľko malých úložísk pre dáta, ktoré nepotrebujú plnohodnotnú databázu: pamäťovú cache, preferencie, perzistentný objekt, súborové cache, počítadlá a dve ďalšie textové databázy. Všetky sú globálne funkcie, takže ich môže používať každý súbor aplikácie.\n\n| Funkcia | Kde sú dáta uložené | Na čo ju použiť |\n| --- | --- | --- |\n| `CACHE()` / `F.cache` | Pamäť procesu | Hodnoty, ktorým vyprší platnosť, napríklad výsledky pomalých dotazov |\n| `FILECACHE()` | Súbor v priečinku `tmp/` | Výsledky, ktoré majú prežiť reštart a ktorým vyprší platnosť |\n| `PREF` | `databases/preferences.json` | Nastavenia, ktoré aplikácia mení za behu |\n| `MEMORIZE()` | `databases/memorize_{name}.json` | Jednoduchý objekt uložený do súboru |\n| `COUNTER()` | `databases/{name}.counter` | Denné štatistiky prístupov alebo súm |\n| `INMEMORY()` | Pamäť, ukladá sa do `databases/{name}.inmemory` | Malá NoSQL kolekcia držaná v pamäti |\n| `TEXTDB()` | Súbory v `databases/textdb-{name}/` | NoSQL kolekcia rozdelená do viacerých súborov |\n\n`BACKUP()` a `RESTORE()` zbalia súbory priečinka do jedného súboru a znova ich rozbalia. `MODIFY()` mení obsah view, štýlov, skriptov a lokalizovaných statických súborov predtým, ako ich Total.js skompiluje.\n\n## Pamäťová cache\n\n`CACHE(key, value, [expire])` uloží hodnotu a `CACHE(key)` ju načíta. Hodnota sa drží v pamäti procesu, takže sa po reštarte stratí. Platnosť sa zadáva textom ako `'5 minutes'` alebo `'1 hour'`, prípadne ako `Date`. Bez nej hodnota vyprší o 5 minút.\n\n```js\nCACHE('products', items, '10 minutes');\n\nvar items = CACHE('products'); // undefined after 10 minutes\n```\n\n`F.cache` je objekt za `CACHE()`. Má ďalšie metódy:\n\n```js\nF.cache.set('user_' + id, user, '1 hour');\nF.cache.get('user_' + id, null);\t\t  // the second argument is a default value\nF.cache.setExpire('user_' + id, '2 hours'); // a new expiration\nF.cache.remove('user_' + id);\nF.cache.removeAll('user_');\t\t\t\t // every key that contains \"user_\"\nF.cache.clear();\t\t\t\t\t\t\t// everything\n```\n\nTotal.js kontroluje cache raz za minútu a odstraňuje položky, ktorým vypršala platnosť. Vysiela udalosti `cache_set` a `cache_expired` (pozri [Plánovanie a udalosti](../../guides/scheduling-and-events/)). Voľba `allow_cache_snapshot` každú minútu uloží celú cache do `databases/cache.json` a pri štarte ju načíta a `allow_cache_cluster` kopíruje zmeny do ostatných procesov clustra (pozri [Konfigurácia](../../guides/configuration/)).\n\n### Načítanie alebo vytvorenie hodnoty\n\n`F.cache.fn()` vráti hodnotu z cache alebo zavolá tvoju funkciu, ktorá ju vytvorí. Funkcia dostane `next(value, [expire])`:\n\n```js\nF.cache.fn('stats', function(next) {\n\tNOSQL('orders').count().callback(function(err, count) {\n\t\tnext({ count: count }, '5 minutes');\n\t});\n}, function(value, fromcache) {\n\tconsole.log(value.count, fromcache);\n});\n```\n\nHodnota `false`, `0`, `''` alebo `null` sa nepovažuje za uloženú v cache, takže funkcia sa spustí znova.\n\n## Cache v súbore\n\n`FILECACHE(id, expire, callback, maker, [encoding])` funguje ako `F.cache.fn()`, ale hodnotu uloží do súboru v priečinku `tmp/`. Súbor zostáva platný, kým nie je starší ako `expire`, aj po reštarte. Funkcia `maker` dostane `next(err, value)`:\n\n```js\nFILECACHE('exchange-rates', '1 hour', function(err, rates) {\n\tconsole.log(rates);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/rates.json').callback(next);\n});\n```\n\nHodnota sa ukladá ako JSON. Ak chceš text ponechať tak, ako je, odovzdaj ako `encoding` hodnotu `'utf8'`. `RESTBuilder` nájdeš v časti [HTTP požiadavky](../../guides/http-requests/).\n\n## Preferencie\n\n`PREF` obsahuje hodnoty, ktoré aplikácia nastavuje za behu a ktoré musia prežiť reštart, napríklad token alebo dátum posledného importu. Total.js ich pri štarte načíta z `databases/preferences.json`. Hodnotu čítaš ako vlastnosť a zapisuješ ju cez `PREF.set()`:\n\n```js\nPREF.set('last_import', NOW);\nPREF.inc('imports');\t  // adds 1 and returns the new value\n\nif (PREF.last_import)\n\tconsole.log(PREF.last_import);\n```\n\nZmeny sa zapíšu do súboru sekundu po poslednej zmene. Ak chceš preferencie uchovávať inde (napríklad v SQL), nahraď delegáty `DEF.onPrefLoad` a `DEF.onPrefSave` v definičnom súbore.\n\n## Perzistentný objekt\n\n`MEMORIZE([name], [delay], [skip])` načíta `databases/memorize_{name}.json` (alebo `databases/memorize.json` bez názvu) a vráti ho ako objekt. Zmeň objekt a zavolaj `save()`: Total.js ho zapíše po `delay` milisekundách (predvolene 10 sekúnd), takže veľa zmien dá jeden zápis.\n\n```js\nvar settings = MEMORIZE('settings');\n\nsettings.theme = 'dark';\nsettings.save();\n```\n\nKaždé volanie súbor načíta znova a vráti nový objekt: zavolaj `MEMORIZE()` raz a objekt si ponechaj. Argument `skip` uvádza kľúče, ktoré sa neukladajú, napríklad dočasné dáta.\n\n## Počítadlá\n\n`COUNTER(name)` počíta prístupy alebo sumy za deň. `hit(id, [value])` pridá hodnotu v pamäti; približne každých päť minút Total.js zapíše súčty do `databases/{name}.counter`, jeden dokument na id a deň so `sum`, `min` a `max`.\n\n```js\nCOUNTER('visits').hit('homepage');\nCOUNTER('sales').hit('eshop', 49.90);\n\nCOUNTER('visits').monthly('homepage', function(err, months) {\n\t// [{ date: '202611', year: 2026, month: 11, sum: 1520, count: 15, min: 1, max: 1 }]\n});\n```\n\nPrístupy, ktoré ešte nie sú zapísané, sa stratia, ak sa proces zastaví; ak ich chceš zapísať skôr, zavolaj `flush()`.\n\n## INMEMORY a TEXTDB\n\n`INMEMORY(name)` a `TEXTDB(name)` vracajú databázu s rovnakými metódami ako `NOSQL()` (pozri [NoSQL databáza](../../guides/nosql/)).\n\n- `INMEMORY()` drží všetky dokumenty v pamäti a zapíše ich do `databases/{name}.inmemory` 5 sekúnd po zmene. Je rýchla pre malú kolekciu, ktorá sa často číta. Podporuje `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()` a `remove()`.\n- `TEXTDB()` uchováva dokumenty v priečinku `databases/textdb-{name}/` vo viacerých súboroch s veľkosťou približne 512 kB. Použi ju pre kolekciu, ktorá rastie.\n\n```js\nINMEMORY('sessions').insert({ id: UID(), userid: user.id, created: NOW });\nINMEMORY('sessions').find().where('userid', user.id).callback(console.log);\n```\n\n## Záloha a obnova súborov\n\n`BACKUP(filename, path, [callback], [filter])` zbalí všetky súbory priečinka (alebo zoznam súborov) do jedného textového súboru. Každý súbor sa komprimuje cez GZIP. `RESTORE(filename, target, [callback], [filter])` ho rozbalí do priečinka.\n\n```js\nBACKUP(PATH.temp('public.backup'), PATH.public(), function(err, meta) {\n\tconsole.log(meta.files, meta.size);\n});\n\nRESTORE(PATH.temp('public.backup'), PATH.root('public2'), function(err, meta) {\n\tconsole.log(meta.files);\n});\n```\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabnJ61zA60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Application structure and modes","summary":"Which directories Total.js 4 loads and in which order, debug and release modes, bundles, packages and workers.","markdown":"---\ntitle: Application structure and modes\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Application structure and modes\n\n> Which directories Total.js 4 loads and in which order, debug and release modes, bundles, packages and workers.\n\nA Total.js 4 application is a directory. You do not register files: the framework reads well-known directories when it starts, `require()`s every script it finds and calls its `exports.install()`. This page explains which directories are read and in which order, how the debug and release modes differ, how bundles and packages work, and how to test the application.\n\n## Starting the application\n\nThe start script (usually `index.js`) loads `total4/debug` or `total4/release` and passes an options object. Both modules export a function:\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nFor production, use `require('total4/release')(options)`. A free command-line argument is read as the port (`node index.js 8001`), as `http://ip:port`, or otherwise as the path of a Unix socket.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Process | A watcher process forks the app | The app runs in the same process, unless `--watcher` or `options.watcher` is set |\n| Restart | On every change in the watched directories | Only when the app exits or asks for a restart |\n| Files `*-debug.js` | Loaded | Skipped |\n| Files `*-release.js` | Skipped | Loaded |\n| Source maps | Generated (unless `CONF.nosourcemap`) | Not generated |\n\nBoth modes write a `.pid` file named like the start script (`index.pid`). Delete it and the process ends within about four seconds. That is a simple way for a deployment script to stop the app.\n\n## What the watcher watches\n\nIn debug mode the watcher looks every few seconds at `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` and `.url` files, at `jsonschemas/*.json` and at the configuration files in the root (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). It reads the directories `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` and `plugins`, plus the directories in `options.watch`. Views and public files do not cause a restart. With `options.livereload` the watcher also watches them and tells the browser to reload.\n\nEach change prints a line (`ADD`, `UPD`, `REM`) and restarts the app. The event `ON('watcher', process)` runs in the watcher process; `ON('debug_start')` and `ON('debug_restart')` run in the app (see [Scheduling and events](../scheduling-and-events/)).\n\n## The load order\n\nWhen the server starts, the framework reads the directories below in this order. Every directory has a `CONF.directory_*` key (see [Configuration](../configuration/)), and scripts in subdirectories are loaded too.\n\n| # | Directory | What is loaded |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | `*.json` and `*.txt` JSON schemas |\n| 2 | `/modules/` | Modules, available through `MODULE()` and `MODS` |\n| 3 | `/packages/` | `.package` files or directories |\n| 4 | `/models/` | Models, available through `MODEL()` |\n| 5 | `/schemas/` | Schemas (see [Schemas](../schemas/)) |\n| 6 | `/actions/` | Actions |\n| 7 | `/tasks/` | Tasks |\n| 8 | `/operations/` | Operations (see [Operations and tasks](../operations-and-tasks/)) |\n| 9 | `/themes/` | Each subdirectory is a theme, its `index.js` is installed |\n| 10 | `/definitions/` | Definitions: global code, delegates, `AUTH()` |\n| 11 | `/controllers/` | Controllers with routes |\n| 12 | `/components/` | `.html` components |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | `.build` and `.url` files of UI Builder |\n| 15 | `/extensions/` | Extensions, through `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` and `plugins/{name}.html` |\n| 17 | `/flowstreams/` | `.flow` files (see [FlowStream](../flowstream/)) |\n\nThe order is the order of installation, not of `require()` only. Everything you declare in a definition already sees the models, schemas and operations. When all files are installed, the framework sorts the routes, loads the preferences and emits `load` and `ready`.\n\nA plugin is a small application inside `plugins/{name}/`. Besides its `index.js`, the framework loads its own `definitions`, `operations`, `actions`, `schemas`, `tasks` and `flowstreams` directories.\n\nSome files are always skipped: names that start with a dot, and names that end with `-bk.js` or `_bk.js`. Use these suffixes to keep an old copy next to the new one.\n\n## exports.install\n\nEach file can export `install(options)`. The framework calls it once, right after `require()`. The argument is the configuration key `{type}_{name}`, for example `module_mail` for `/modules/mail.js`:\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nAfter installation the framework emits `ON('install', type, name, module)`.\n\n## Using installed code\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundles\n\nA bundle is one `.bundle` file that contains a whole application or a part of it. Put bundles into `/bundles/`. On start the framework extracts every bundle into the hidden directory `/.src/`, then copies the files of the application over it, and runs the application from `/.src/`.\n\n- Files of the application win over files of the bundle, so you can override a single view or a script.\n- `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` and `.resource` files are merged, not replaced.\n- A file whose name starts with `--` is appended to the file without the prefix: `/public/css/--custom.css` is appended to `/public/css/custom.css`.\n- Existing files in `/databases/` and `/updates/` are never overwritten.\n- A `.url` file in `/bundles/` contains a URL; the bundle is downloaded from it.\n- `.bundleignore` in the root lists paths that are not copied.\n\nCreate a bundle with the command line: `total4 bundle app.bundle`. Extract one with `total4 extract app.bundle`.\n\n## Packages\n\nA package is a `.package` file (or a directory named `name.package`) in `/packages/`. It is extracted into the temporary directory and its `index.js` is installed. Read its files with `PATH.package('name/file.txt')`.\n\n## Loading without a server\n\n`LOAD()` installs the application without starting the HTTP server. Use it in scripts, workers and tests:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Workers\n\n`/workers/` contains scripts that run in a separate process (`WORKER()`, `NEWFORK()`) or a worker thread (`NEWTHREAD()`). They are not installed on start.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnJ61zA60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Anwendungsstruktur und Modi","summary":"Welche Verzeichnisse Total.js 4 in welcher Reihenfolge lädt, Debug- und Release-Modus, Bundles, Pakete und Worker.","markdown":"---\ntitle: Anwendungsstruktur und Modi\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Anwendungsstruktur und Modi\n\n> Welche Verzeichnisse Total.js 4 in welcher Reihenfolge lädt, Debug- und Release-Modus, Bundles, Pakete und Worker.\n\nEine Total.js 4-Anwendung ist ein Verzeichnis. Du registrierst keine Dateien: Das Framework liest beim Start bekannte Verzeichnisse, lädt jedes gefundene Skript mit `require()` und ruft sein `exports.install()` auf. Diese Seite erklärt, welche Verzeichnisse in welcher Reihenfolge gelesen werden, wie sich Debug- und Release-Modus unterscheiden, wie Bundles und Pakete funktionieren und wie du die Anwendung testest.\n\n## Die Anwendung starten\n\nDas Startskript (meist `index.js`) lädt `total4/debug` oder `total4/release` und übergibt ein Options-Objekt. Beide Module exportieren eine Funktion:\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nFür die Produktion verwendest du `require('total4/release')(options)`. Ein freies Kommandozeilenargument wird als Port gelesen (`node index.js 8001`), als `http://ip:port` oder sonst als Pfad eines Unix-Sockets.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Prozess | Ein Watcher-Prozess forkt die App | Die App läuft im selben Prozess, außer `--watcher` oder `options.watcher` ist gesetzt |\n| Neustart | Bei jeder Änderung in den überwachten Verzeichnissen | Nur wenn die App beendet wird oder einen Neustart anfordert |\n| Dateien `*-debug.js` | Geladen | Übersprungen |\n| Dateien `*-release.js` | Übersprungen | Geladen |\n| Source Maps | Erzeugt (außer bei `CONF.nosourcemap`) | Nicht erzeugt |\n\nBeide Modi schreiben eine `.pid`-Datei, die wie das Startskript heißt (`index.pid`). Lösche sie, und der Prozess endet innerhalb von etwa vier Sekunden. So kann ein Deployment-Skript die App einfach stoppen.\n\n## Was der Watcher überwacht\n\nIm Debug-Modus prüft der Watcher alle paar Sekunden `.js`-, `.ts`-, `.resource`-, `.package`-, `.bundle`-, `.build`-, `.flow`- und `.url`-Dateien, `jsonschemas/*.json` und die Konfigurationsdateien im Stammverzeichnis (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). Er liest die Verzeichnisse `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` und `plugins` sowie die Verzeichnisse in `options.watch`. Views und öffentliche Dateien lösen keinen Neustart aus. Mit `options.livereload` überwacht der Watcher auch diese und sagt dem Browser, dass er neu laden soll.\n\nJede Änderung gibt eine Zeile aus (`ADD`, `UPD`, `REM`) und startet die App neu. Das Event `ON('watcher', process)` läuft im Watcher-Prozess; `ON('debug_start')` und `ON('debug_restart')` laufen in der App (siehe [Zeitplanung und Events](../scheduling-and-events/)).\n\n## Die Ladereihenfolge\n\nBeim Start des Servers liest das Framework die folgenden Verzeichnisse in dieser Reihenfolge. Jedes Verzeichnis hat einen Schlüssel `CONF.directory_*` (siehe [Konfiguration](../configuration/)), und Skripte in Unterverzeichnissen werden ebenfalls geladen.\n\n| # | Verzeichnis | Was geladen wird |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | JSON-Schemas als `*.json` und `*.txt` |\n| 2 | `/modules/` | Module, verfügbar über `MODULE()` und `MODS` |\n| 3 | `/packages/` | `.package`-Dateien oder -Verzeichnisse |\n| 4 | `/models/` | Modelle, verfügbar über `MODEL()` |\n| 5 | `/schemas/` | Schemas (siehe [Schemas](../schemas/)) |\n| 6 | `/actions/` | Actions |\n| 7 | `/tasks/` | Tasks |\n| 8 | `/operations/` | Operations (siehe [Operations und Tasks](../operations-and-tasks/)) |\n| 9 | `/themes/` | Jedes Unterverzeichnis ist ein Theme, sein `index.js` wird installiert |\n| 10 | `/definitions/` | Definitionen: globaler Code, Delegates, `AUTH()` |\n| 11 | `/controllers/` | Controller mit Routen |\n| 12 | `/components/` | `.html`-Komponenten |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | `.build`- und `.url`-Dateien von UI Builder |\n| 15 | `/extensions/` | Erweiterungen, über `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` und `plugins/{name}.html` |\n| 17 | `/flowstreams/` | `.flow`-Dateien (siehe [FlowStream](../flowstream/)) |\n\nDie Reihenfolge ist die Reihenfolge der Installation, nicht nur die von `require()`. Alles, was du in einer Definition deklarierst, sieht bereits die Modelle, Schemas und Operations. Wenn alle Dateien installiert sind, sortiert das Framework die Routen, lädt die Einstellungen und gibt `load` und `ready` aus.\n\nEin Plugin ist eine kleine Anwendung innerhalb von `plugins/{name}/`. Neben seinem `index.js` lädt das Framework seine eigenen Verzeichnisse `definitions`, `operations`, `actions`, `schemas`, `tasks` und `flowstreams`.\n\nEinige Dateien werden immer übersprungen: Namen, die mit einem Punkt beginnen, und Namen, die auf `-bk.js` oder `_bk.js` enden. Verwende diese Suffixe, um eine alte Kopie neben der neuen zu behalten.\n\n## exports.install\n\nJede Datei kann `install(options)` exportieren. Das Framework ruft es einmal auf, direkt nach `require()`. Das Argument ist der Konfigurationsschlüssel `{type}_{name}`, zum Beispiel `module_mail` für `/modules/mail.js`:\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nNach der Installation gibt das Framework `ON('install', type, name, module)` aus.\n\n## Installierten Code verwenden\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundles\n\nEin Bundle ist eine `.bundle`-Datei, die eine ganze Anwendung oder einen Teil davon enthält. Lege Bundles in `/bundles/` ab. Beim Start entpackt das Framework jedes Bundle in das versteckte Verzeichnis `/.src/`, kopiert dann die Dateien der Anwendung darüber und führt die Anwendung aus `/.src/` aus.\n\n- Dateien der Anwendung haben Vorrang vor Dateien des Bundles, sodass du eine einzelne View oder ein Skript überschreiben kannst.\n- `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` und `.resource`-Dateien werden zusammengeführt, nicht ersetzt.\n- Eine Datei, deren Name mit `--` beginnt, wird an die Datei ohne das Präfix angehängt: `/public/css/--custom.css` wird an `/public/css/custom.css` angehängt.\n- Bestehende Dateien in `/databases/` und `/updates/` werden nie überschrieben.\n- Eine `.url`-Datei in `/bundles/` enthält eine URL; das Bundle wird von dort heruntergeladen.\n- `.bundleignore` im Stammverzeichnis listet Pfade auf, die nicht kopiert werden.\n\nErstelle ein Bundle über die Kommandozeile: `total4 bundle app.bundle`. Entpacke eines mit `total4 extract app.bundle`.\n\n## Pakete\n\nEin Paket ist eine `.package`-Datei (oder ein Verzeichnis namens `name.package`) in `/packages/`. Es wird in das temporäre Verzeichnis entpackt, und sein `index.js` wird installiert. Lies seine Dateien mit `PATH.package('name/file.txt')`.\n\n## Laden ohne Server\n\n`LOAD()` installiert die Anwendung, ohne den HTTP-Server zu starten. Verwende es in Skripten, Workern und Tests:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Worker\n\n`/workers/` enthält Skripte, die in einem eigenen Prozess (`WORKER()`, `NEWFORK()`) oder in einem Worker-Thread (`NEWTHREAD()`) laufen. Sie werden beim Start nicht installiert.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnJ61zA60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Estructura de la aplicación y modos","summary":"Qué directorios carga Total.js 4 y en qué orden, los modos debug y release, bundles, paquetes y workers.","markdown":"---\ntitle: \"Estructura de la aplicación y modos\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Estructura de la aplicación y modos\n\n> Qué directorios carga Total.js 4 y en qué orden, los modos debug y release, bundles, paquetes y workers.\n\nUna aplicación Total.js 4 es un directorio. No registras archivos: el framework lee directorios conocidos al arrancar, hace `require()` de cada script que encuentra y llama a su `exports.install()`. Esta página explica qué directorios se leen y en qué orden, en qué se diferencian los modos debug y release, cómo funcionan los bundles y los paquetes, y cómo probar la aplicación.\n\n## Arrancar la aplicación\n\nEl script de arranque (normalmente `index.js`) carga `total4/debug` o `total4/release` y le pasa un objeto de opciones. Ambos módulos exportan una función:\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nPara producción, usa `require('total4/release')(options)`. Un argumento libre de la línea de comandos se lee como el puerto (`node index.js 8001`), como `http://ip:port` o, si no, como la ruta de un socket Unix.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Proceso | Un proceso watcher hace fork de la aplicación | La aplicación se ejecuta en el mismo proceso, salvo que se defina `--watcher` u `options.watcher` |\n| Reinicio | En cada cambio en los directorios vigilados | Solo cuando la aplicación termina o pide un reinicio |\n| Archivos `*-debug.js` | Se cargan | Se omiten |\n| Archivos `*-release.js` | Se omiten | Se cargan |\n| Source maps | Se generan (salvo con `CONF.nosourcemap`) | No se generan |\n\nAmbos modos escriben un archivo `.pid` con el nombre del script de arranque (`index.pid`). Bórralo y el proceso termina en unos cuatro segundos. Es una forma sencilla de que un script de despliegue detenga la aplicación.\n\n## Qué vigila el watcher\n\nEn modo debug el watcher revisa cada pocos segundos los archivos `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` y `.url`, los `jsonschemas/*.json` y los archivos de configuración de la raíz (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). Lee los directorios `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` y `plugins`, además de los directorios de `options.watch`. Las vistas y los archivos públicos no provocan un reinicio. Con `options.livereload` el watcher también los vigila y le dice al navegador que recargue.\n\nCada cambio imprime una línea (`ADD`, `UPD`, `REM`) y reinicia la aplicación. El evento `ON('watcher', process)` se ejecuta en el proceso watcher; `ON('debug_start')` y `ON('debug_restart')` se ejecutan en la aplicación (consulta [Programación y eventos](../scheduling-and-events/)).\n\n## El orden de carga\n\nCuando el servidor arranca, el framework lee los directorios siguientes en este orden. Cada directorio tiene una clave `CONF.directory_*` (consulta [Configuración](../configuration/)), y también se cargan los scripts de los subdirectorios.\n\n| # | Directorio | Qué se carga |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | Esquemas JSON `*.json` y `*.txt` |\n| 2 | `/modules/` | Módulos, disponibles mediante `MODULE()` y `MODS` |\n| 3 | `/packages/` | Archivos o directorios `.package` |\n| 4 | `/models/` | Modelos, disponibles mediante `MODEL()` |\n| 5 | `/schemas/` | Esquemas (consulta [Esquemas](../schemas/)) |\n| 6 | `/actions/` | Acciones |\n| 7 | `/tasks/` | Tareas |\n| 8 | `/operations/` | Operaciones (consulta [Operaciones y tareas](../operations-and-tasks/)) |\n| 9 | `/themes/` | Cada subdirectorio es un tema; se instala su `index.js` |\n| 10 | `/definitions/` | Definiciones: código global, delegados, `AUTH()` |\n| 11 | `/controllers/` | Controladores con rutas |\n| 12 | `/components/` | Componentes `.html` |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | Archivos `.build` y `.url` de UI Builder |\n| 15 | `/extensions/` | Extensiones, mediante `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` y `plugins/{name}.html` |\n| 17 | `/flowstreams/` | Archivos `.flow` (consulta [FlowStream](../flowstream/)) |\n\nEl orden es el orden de instalación, no solo de `require()`. Todo lo que declaras en una definición ya ve los modelos, esquemas y operaciones. Cuando todos los archivos están instalados, el framework ordena las rutas, carga las preferencias y emite `load` y `ready`.\n\nUn plugin es una pequeña aplicación dentro de `plugins/{name}/`. Además de su `index.js`, el framework carga sus propios directorios `definitions`, `operations`, `actions`, `schemas`, `tasks` y `flowstreams`.\n\nAlgunos archivos se omiten siempre: los nombres que empiezan por un punto y los que terminan en `-bk.js` o `_bk.js`. Usa estos sufijos para guardar una copia antigua junto a la nueva.\n\n## exports.install\n\nCada archivo puede exportar `install(options)`. El framework lo llama una vez, justo después de `require()`. El argumento es la clave de configuración `{type}_{name}`, por ejemplo `module_mail` para `/modules/mail.js`:\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nTras la instalación, el framework emite `ON('install', type, name, module)`.\n\n## Usar el código instalado\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundles\n\nUn bundle es un archivo `.bundle` que contiene una aplicación completa o una parte de ella. Pon los bundles en `/bundles/`. Al arrancar, el framework extrae cada bundle en el directorio oculto `/.src/`, luego copia encima los archivos de la aplicación y ejecuta la aplicación desde `/.src/`.\n\n- Los archivos de la aplicación tienen prioridad sobre los del bundle, así que puedes sobrescribir una sola vista o un script.\n- Los archivos `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` y `.resource` se combinan, no se reemplazan.\n- Un archivo cuyo nombre empieza por `--` se añade al final del archivo sin el prefijo: `/public/css/--custom.css` se añade a `/public/css/custom.css`.\n- Los archivos existentes en `/databases/` y `/updates/` nunca se sobrescriben.\n- Un archivo `.url` en `/bundles/` contiene una URL; el bundle se descarga desde ella.\n- `.bundleignore` en la raíz enumera las rutas que no se copian.\n\nCrea un bundle desde la línea de comandos: `total4 bundle app.bundle`. Extrae uno con `total4 extract app.bundle`.\n\n## Paquetes\n\nUn paquete es un archivo `.package` (o un directorio llamado `name.package`) en `/packages/`. Se extrae en el directorio temporal y se instala su `index.js`. Lee sus archivos con `PATH.package('name/file.txt')`.\n\n## Cargar sin servidor\n\n`LOAD()` instala la aplicación sin arrancar el servidor HTTP. Úsalo en scripts, workers y tests:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Workers\n\n`/workers/` contiene scripts que se ejecutan en un proceso separado (`WORKER()`, `NEWFORK()`) o en un hilo worker (`NEWTHREAD()`). No se instalan al arrancar.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnJ61zA60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Structure de l'application et modes","summary":"Quels répertoires Total.js 4 charge et dans quel ordre, les modes debug et release, les bundles, les paquets et les workers.","markdown":"---\ntitle: \"Structure de l'application et modes\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Structure de l'application et modes\n\n> Quels répertoires Total.js 4 charge et dans quel ordre, les modes debug et release, les bundles, les paquets et les workers.\n\nUne application Total.js 4 est un répertoire. Tu n'enregistres pas les fichiers : au démarrage, le framework lit des répertoires bien connus, fait un `require()` de chaque script qu'il trouve et appelle son `exports.install()`. Cette page explique quels répertoires sont lus et dans quel ordre, en quoi les modes debug et release diffèrent, comment fonctionnent les bundles et les paquets, et comment tester l'application.\n\n## Démarrer l'application\n\nLe script de démarrage (généralement `index.js`) charge `total4/debug` ou `total4/release` et lui passe un objet d'options. Les deux modules exportent une fonction :\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nEn production, utilise `require('total4/release')(options)`. Un argument libre de la ligne de commande est lu comme le port (`node index.js 8001`), comme `http://ip:port`, ou sinon comme le chemin d'un socket Unix.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Processus | Un processus watcher lance l'application par fork | L'application s'exécute dans le même processus, sauf si `--watcher` ou `options.watcher` est défini |\n| Redémarrage | À chaque modification dans les répertoires surveillés | Seulement quand l'application se termine ou demande un redémarrage |\n| Fichiers `*-debug.js` | Chargés | Ignorés |\n| Fichiers `*-release.js` | Ignorés | Chargés |\n| Source maps | Générées (sauf avec `CONF.nosourcemap`) | Non générées |\n\nLes deux modes écrivent un fichier `.pid` nommé comme le script de démarrage (`index.pid`). Supprime-le et le processus se termine en quatre secondes environ. C'est un moyen simple pour un script de déploiement d'arrêter l'application.\n\n## Ce que surveille le watcher\n\nEn mode debug, le watcher examine toutes les quelques secondes les fichiers `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` et `.url`, les fichiers `jsonschemas/*.json` et les fichiers de configuration à la racine (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). Il lit les répertoires `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` et `plugins`, ainsi que les répertoires de `options.watch`. Les vues et les fichiers publics ne provoquent pas de redémarrage. Avec `options.livereload`, le watcher les surveille aussi et demande au navigateur de recharger la page.\n\nChaque modification affiche une ligne (`ADD`, `UPD`, `REM`) et redémarre l'application. L'événement `ON('watcher', process)` s'exécute dans le processus watcher ; `ON('debug_start')` et `ON('debug_restart')` s'exécutent dans l'application (voir [Planification et événements](../scheduling-and-events/)).\n\n## L'ordre de chargement\n\nAu démarrage du serveur, le framework lit les répertoires ci-dessous dans cet ordre. Chaque répertoire a une clé `CONF.directory_*` (voir [Configuration](../configuration/)), et les scripts des sous-répertoires sont aussi chargés.\n\n| # | Répertoire | Ce qui est chargé |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | Schémas JSON `*.json` et `*.txt` |\n| 2 | `/modules/` | Modules, disponibles via `MODULE()` et `MODS` |\n| 3 | `/packages/` | Fichiers ou répertoires `.package` |\n| 4 | `/models/` | Modèles, disponibles via `MODEL()` |\n| 5 | `/schemas/` | Schémas (voir [Schémas](../schemas/)) |\n| 6 | `/actions/` | Actions |\n| 7 | `/tasks/` | Tâches |\n| 8 | `/operations/` | Opérations (voir [Opérations et tâches](../operations-and-tasks/)) |\n| 9 | `/themes/` | Chaque sous-répertoire est un thème, son `index.js` est installé |\n| 10 | `/definitions/` | Définitions : code global, délégués, `AUTH()` |\n| 11 | `/controllers/` | Contrôleurs avec leurs routes |\n| 12 | `/components/` | Composants `.html` |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | Fichiers `.build` et `.url` de UI Builder |\n| 15 | `/extensions/` | Extensions, via `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` et `plugins/{name}.html` |\n| 17 | `/flowstreams/` | Fichiers `.flow` (voir [FlowStream](../flowstream/)) |\n\nL'ordre est celui de l'installation, pas seulement celui du `require()`. Tout ce que tu déclares dans une définition voit déjà les modèles, les schémas et les opérations. Quand tous les fichiers sont installés, le framework trie les routes, charge les préférences et émet `load` et `ready`.\n\nUn plugin est une petite application dans `plugins/{name}/`. En plus de son `index.js`, le framework charge ses propres répertoires `definitions`, `operations`, `actions`, `schemas`, `tasks` et `flowstreams`.\n\nCertains fichiers sont toujours ignorés : les noms qui commencent par un point, et les noms qui se terminent par `-bk.js` ou `_bk.js`. Utilise ces suffixes pour garder une ancienne copie à côté de la nouvelle.\n\n## exports.install\n\nChaque fichier peut exporter `install(options)`. Le framework l'appelle une seule fois, juste après le `require()`. L'argument est la clé de configuration `{type}_{name}`, par exemple `module_mail` pour `/modules/mail.js` :\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nAprès l'installation, le framework émet `ON('install', type, name, module)`.\n\n## Utiliser le code installé\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundles\n\nUn bundle est un fichier `.bundle` unique qui contient une application entière ou une partie de celle-ci. Place les bundles dans `/bundles/`. Au démarrage, le framework extrait chaque bundle dans le répertoire caché `/.src/`, copie ensuite par-dessus les fichiers de l'application, et exécute l'application depuis `/.src/`.\n\n- Les fichiers de l'application l'emportent sur ceux du bundle ; tu peux donc remplacer une seule vue ou un seul script.\n- `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` et les fichiers `.resource` sont fusionnés, pas remplacés.\n- Un fichier dont le nom commence par `--` est ajouté à la fin du fichier sans ce préfixe : `/public/css/--custom.css` est ajouté à `/public/css/custom.css`.\n- Les fichiers existants dans `/databases/` et `/updates/` ne sont jamais écrasés.\n- Un fichier `.url` dans `/bundles/` contient une URL ; le bundle est téléchargé depuis celle-ci.\n- `.bundleignore` à la racine liste les chemins qui ne sont pas copiés.\n\nCrée un bundle en ligne de commande : `total4 bundle app.bundle`. Extrais-en un avec `total4 extract app.bundle`.\n\n## Paquets\n\nUn paquet est un fichier `.package` (ou un répertoire nommé `name.package`) dans `/packages/`. Il est extrait dans le répertoire temporaire et son `index.js` est installé. Lis ses fichiers avec `PATH.package('name/file.txt')`.\n\n## Charger sans serveur\n\n`LOAD()` installe l'application sans démarrer le serveur HTTP. Utilise-le dans les scripts, les workers et les tests :\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Workers\n\n`/workers/` contient des scripts qui s'exécutent dans un processus séparé (`WORKER()`, `NEWFORK()`) ou dans un worker thread (`NEWTHREAD()`). Ils ne sont pas installés au démarrage.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnJ61zA60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Struttura dell'applicazione e modalità","summary":"Quali directory carica Total.js 4 e in quale ordine, le modalità debug e release, bundle, pacchetti e worker.","markdown":"---\ntitle: \"Struttura dell'applicazione e modalità\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Struttura dell'applicazione e modalità\n\n> Quali directory carica Total.js 4 e in quale ordine, le modalità debug e release, bundle, pacchetti e worker.\n\nUn'applicazione Total.js 4 è una directory. Non registri i file: il framework legge directory ben note all'avvio, esegue `require()` su ogni script che trova e chiama il suo `exports.install()`. Questa pagina spiega quali directory vengono lette e in quale ordine, in cosa differiscono le modalità debug e release, come funzionano bundle e pacchetti e come testare l'applicazione.\n\n## Avviare l'applicazione\n\nLo script di avvio (di solito `index.js`) carica `total4/debug` o `total4/release` e passa un oggetto di opzioni. Entrambi i moduli esportano una funzione:\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nPer la produzione, usa `require('total4/release')(options)`. Un argomento libero della riga di comando viene letto come porta (`node index.js 8001`), come `http://ip:port`, oppure altrimenti come percorso di un socket Unix.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Processo | Un processo watcher esegue il fork dell'app | L'app viene eseguita nello stesso processo, a meno che non sia impostato `--watcher` o `options.watcher` |\n| Riavvio | A ogni modifica nelle directory osservate | Solo quando l'app termina o chiede un riavvio |\n| File `*-debug.js` | Caricati | Ignorati |\n| File `*-release.js` | Ignorati | Caricati |\n| Source map | Generate (a meno di `CONF.nosourcemap`) | Non generate |\n\nEntrambe le modalità scrivono un file `.pid` con lo stesso nome dello script di avvio (`index.pid`). Eliminalo e il processo termina entro circa quattro secondi. È un modo semplice con cui uno script di deploy può fermare l'app.\n\n## Cosa osserva il watcher\n\nIn modalità debug il watcher controlla ogni pochi secondi i file `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` e `.url`, i file `jsonschemas/*.json` e i file di configurazione nella root (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). Legge le directory `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` e `plugins`, più le directory in `options.watch`. Le viste e i file pubblici non causano un riavvio. Con `options.livereload` il watcher osserva anche questi e dice al browser di ricaricare.\n\nOgni modifica stampa una riga (`ADD`, `UPD`, `REM`) e riavvia l'app. L'evento `ON('watcher', process)` viene eseguito nel processo watcher; `ON('debug_start')` e `ON('debug_restart')` vengono eseguiti nell'app (vedi [Pianificazione ed eventi](../scheduling-and-events/)).\n\n## L'ordine di caricamento\n\nAll'avvio del server, il framework legge le directory qui sotto in questo ordine. Ogni directory ha una chiave `CONF.directory_*` (vedi [Configurazione](../configuration/)), e vengono caricati anche gli script nelle sottodirectory.\n\n| # | Directory | Cosa viene caricato |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | Schemi JSON `*.json` e `*.txt` |\n| 2 | `/modules/` | Moduli, disponibili tramite `MODULE()` e `MODS` |\n| 3 | `/packages/` | File o directory `.package` |\n| 4 | `/models/` | Modelli, disponibili tramite `MODEL()` |\n| 5 | `/schemas/` | Schemi (vedi [Schemi](../schemas/)) |\n| 6 | `/actions/` | Azioni |\n| 7 | `/tasks/` | Task |\n| 8 | `/operations/` | Operazioni (vedi [Operazioni e task](../operations-and-tasks/)) |\n| 9 | `/themes/` | Ogni sottodirectory è un tema, viene installato il suo `index.js` |\n| 10 | `/definitions/` | Definizioni: codice globale, delegati, `AUTH()` |\n| 11 | `/controllers/` | Controller con le route |\n| 12 | `/components/` | Componenti `.html` |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | File `.build` e `.url` di UI Builder |\n| 15 | `/extensions/` | Estensioni, tramite `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` e `plugins/{name}.html` |\n| 17 | `/flowstreams/` | File `.flow` (vedi [FlowStream](../flowstream/)) |\n\nL'ordine è l'ordine di installazione, non solo di `require()`. Tutto ciò che dichiari in una definizione vede già i modelli, gli schemi e le operazioni. Quando tutti i file sono installati, il framework ordina le route, carica le preferenze ed emette `load` e `ready`.\n\nUn plugin è una piccola applicazione dentro `plugins/{name}/`. Oltre al suo `index.js`, il framework carica le sue directory `definitions`, `operations`, `actions`, `schemas`, `tasks` e `flowstreams`.\n\nAlcuni file vengono sempre ignorati: i nomi che iniziano con un punto e i nomi che finiscono con `-bk.js` o `_bk.js`. Usa questi suffissi per tenere una vecchia copia accanto a quella nuova.\n\n## exports.install\n\nOgni file può esportare `install(options)`. Il framework lo chiama una volta, subito dopo `require()`. L'argomento è la chiave di configurazione `{type}_{name}`, per esempio `module_mail` per `/modules/mail.js`:\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nDopo l'installazione il framework emette `ON('install', type, name, module)`.\n\n## Usare il codice installato\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundle\n\nUn bundle è un singolo file `.bundle` che contiene un'intera applicazione o una sua parte. Metti i bundle in `/bundles/`. All'avvio il framework estrae ogni bundle nella directory nascosta `/.src/`, poi vi copia sopra i file dell'applicazione ed esegue l'applicazione da `/.src/`.\n\n- I file dell'applicazione prevalgono sui file del bundle, così puoi sovrascrivere una singola vista o uno script.\n- `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` e i file `.resource` vengono uniti, non sostituiti.\n- Un file il cui nome inizia con `--` viene accodato al file senza il prefisso: `/public/css/--custom.css` viene accodato a `/public/css/custom.css`.\n- I file esistenti in `/databases/` e `/updates/` non vengono mai sovrascritti.\n- Un file `.url` in `/bundles/` contiene un URL; il bundle viene scaricato da lì.\n- `.bundleignore` nella root elenca i percorsi che non vengono copiati.\n\nCrea un bundle dalla riga di comando: `total4 bundle app.bundle`. Estrailo con `total4 extract app.bundle`.\n\n## Pacchetti\n\nUn pacchetto è un file `.package` (o una directory chiamata `name.package`) in `/packages/`. Viene estratto nella directory temporanea e il suo `index.js` viene installato. Leggi i suoi file con `PATH.package('name/file.txt')`.\n\n## Caricare senza server\n\n`LOAD()` installa l'applicazione senza avviare il server HTTP. Usalo in script, worker e test:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Worker\n\n`/workers/` contiene script che vengono eseguiti in un processo separato (`WORKER()`, `NEWFORK()`) o in un worker thread (`NEWTHREAD()`). Non vengono installati all'avvio.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnJ61zA60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/application-structure/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Štruktúra aplikácie a režimy","summary":"Ktoré adresáre Total.js 4 načítava a v akom poradí, režimy debug a release, bundly, balíky a workery.","markdown":"---\ntitle: \"Štruktúra aplikácie a režimy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/application-structure/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Štruktúra aplikácie a režimy\n\n> Ktoré adresáre Total.js 4 načítava a v akom poradí, režimy debug a release, bundly, balíky a workery.\n\nAplikácia Total.js 4 je adresár. Súbory neregistruješ: framework pri štarte prečíta známe adresáre, zavolá `require()` na každý skript, ktorý nájde, a zavolá jeho `exports.install()`. Táto stránka vysvetľuje, ktoré adresáre sa čítajú a v akom poradí, ako sa líšia režimy debug a release, ako fungujú bundly a balíky a ako aplikáciu testovať.\n\n## Spustenie aplikácie\n\nŠtartovací skript (zvyčajne `index.js`) načíta `total4/debug` alebo `total4/release` a odovzdá objekt s voľbami. Oba moduly exportujú funkciu:\n\n```js\nvar options = {};\n// options.port = 8000;\n// options.ip = '127.0.0.1';\n// options.watch = ['adminer'];\n// options.livereload = true;\nrequire('total4/debug')(options);\n```\n\nNa produkciu použi `require('total4/release')(options)`. Voľný argument príkazového riadku sa číta ako port (`node index.js 8001`), ako `http://ip:port` alebo inak ako cesta k Unix socketu.\n\n| | `total4/debug` | `total4/release` |\n| --- | --- | --- |\n| `DEBUG` / `RELEASE` | `true` / `false` | `false` / `true` |\n| Proces | Proces watchera forkuje aplikáciu | Aplikácia beží v tom istom procese, pokiaľ nie je nastavené `--watcher` alebo `options.watcher` |\n| Reštart | Pri každej zmene v sledovaných adresároch | Len keď aplikácia skončí alebo požiada o reštart |\n| Súbory `*-debug.js` | Načítajú sa | Preskočia sa |\n| Súbory `*-release.js` | Preskočia sa | Načítajú sa |\n| Source mapy | Generujú sa (pokiaľ nie je `CONF.nosourcemap`) | Negenerujú sa |\n\nOba režimy zapíšu súbor `.pid` pomenovaný podľa štartovacieho skriptu (`index.pid`). Vymaž ho a proces skončí asi do štyroch sekúnd. Je to jednoduchý spôsob, ako môže deployovací skript aplikáciu zastaviť.\n\n## Čo watcher sleduje\n\nV režime debug sa watcher každých pár sekúnd pozrie na súbory `.js`, `.ts`, `.resource`, `.package`, `.bundle`, `.build`, `.flow` a `.url`, na `jsonschemas/*.json` a na konfiguračné súbory v koreni (`config`, `config-debug`, `config-release`, `versions`, `sitemap`, `bundles.debug`). Číta adresáre `components`, `controllers`, `definitions`, `operations`, `extensions`, `modules`, `models`, `builds`, `jsonschemas`, `schemas`, `actions`, `tasks`, `resources`, `source`, `workers`, `packages`, `themes`, `middleware`, `configs`, `bundles`, `flowstreams`, `startup`, `threads` a `plugins` a k tomu adresáre v `options.watch`. Pohľady a verejné súbory reštart nespôsobia. S `options.livereload` ich watcher sleduje tiež a povie prehliadaču, aby stránku znovu načítal.\n\nKaždá zmena vypíše riadok (`ADD`, `UPD`, `REM`) a reštartuje aplikáciu. Udalosť `ON('watcher', process)` beží v procese watchera; `ON('debug_start')` a `ON('debug_restart')` bežia v aplikácii (pozri [Plánovanie a udalosti](../scheduling-and-events/)).\n\n## Poradie načítania\n\nPri štarte servera framework číta adresáre uvedené nižšie v tomto poradí. Každý adresár má kľúč `CONF.directory_*` (pozri [Konfigurácia](../configuration/)) a načítajú sa aj skripty v podadresároch.\n\n| # | Adresár | Čo sa načíta |\n| --- | --- | --- |\n| 1 | `/jsonschemas/` | JSON schémy `*.json` a `*.txt` |\n| 2 | `/modules/` | Moduly, dostupné cez `MODULE()` a `MODS` |\n| 3 | `/packages/` | Súbory alebo adresáre `.package` |\n| 4 | `/models/` | Modely, dostupné cez `MODEL()` |\n| 5 | `/schemas/` | Schémy (pozri [Schémy](../schemas/)) |\n| 6 | `/actions/` | Akcie |\n| 7 | `/tasks/` | Úlohy |\n| 8 | `/operations/` | Operácie (pozri [Operácie a úlohy](../operations-and-tasks/)) |\n| 9 | `/themes/` | Každý podadresár je téma, nainštaluje sa jej `index.js` |\n| 10 | `/definitions/` | Definície: globálny kód, delegáty, `AUTH()` |\n| 11 | `/controllers/` | Kontroléry s trasami |\n| 12 | `/components/` | Komponenty `.html` |\n| 13 | `/middleware/` | Middleware |\n| 14 | `/builds/` | Súbory `.build` a `.url` z UI Builder |\n| 15 | `/extensions/` | Rozšírenia, cez `NEWEXTENSION()` |\n| 16 | `/plugins/` | `plugins/{name}/index.js` a `plugins/{name}.html` |\n| 17 | `/flowstreams/` | Súbory `.flow` (pozri [FlowStream](../flowstream/)) |\n\nPoradie je poradím inštalácie, nielen poradím `require()`. Všetko, čo deklaruješ v definícii, už vidí modely, schémy a operácie. Keď sú všetky súbory nainštalované, framework zoradí trasy, načíta preferencie a vyšle `load` a `ready`.\n\nPlugin je malá aplikácia vnútri `plugins/{name}/`. Okrem jeho `index.js` framework načíta aj jeho vlastné adresáre `definitions`, `operations`, `actions`, `schemas`, `tasks` a `flowstreams`.\n\nNiektoré súbory sa vždy preskočia: názvy, ktoré začínajú bodkou, a názvy, ktoré končia na `-bk.js` alebo `_bk.js`. Tieto prípony použi, keď chceš mať starú kópiu vedľa novej.\n\n## exports.install\n\nKaždý súbor môže exportovať `install(options)`. Framework ho zavolá raz, hneď po `require()`. Argumentom je konfiguračný kľúč `{type}_{name}`, napríklad `module_mail` pre `/modules/mail.js`:\n\n```js\n// /modules/mail.js\nexports.install = function(options) {\n\t// options === CONF.module_mail\n};\n\nexports.send = function(to, subject, body) {\n\t// ...\n};\n```\n\nPo inštalácii framework vyšle `ON('install', type, name, module)`.\n\n## Použitie nainštalovaného kódu\n\n```js\n// A module\nMODULE('mail').send('info@example.com', 'Hello', 'Body');\nMODS.mail.send('info@example.com', 'Hello', 'Body');\n\n// A model\nvar Product = MODEL('product');\n\n// A plugin\nPLUGINS.dashboard.id; // 'dashboard'\n\n// A source file (/source/helpers.js), loaded the first time you ask for it\nvar helpers = INCLUDE('helpers');\n\n// Any script relative to the application directory\nvar tools = REQUIRE('lib/tools.js');\n```\n\n## Bundly\n\nBundle je jeden súbor `.bundle`, ktorý obsahuje celú aplikáciu alebo jej časť. Bundly daj do `/bundles/`. Pri štarte framework rozbalí každý bundle do skrytého adresára `/.src/`, potom cez neho skopíruje súbory aplikácie a aplikáciu spustí z `/.src/`.\n\n- Súbory aplikácie majú prednosť pred súbormi bundlu, takže môžeš prepísať jeden pohľad alebo skript.\n- `config`, `config-debug`, `config-release`, `sitemap`, `versions`, `workflows`, `dependencies` a súbory `.resource` sa zlučujú, nenahrádzajú.\n- Súbor, ktorého názov začína na `--`, sa pripojí k súboru bez tejto predpony: `/public/css/--custom.css` sa pripojí k `/public/css/custom.css`.\n- Existujúce súbory v `/databases/` a `/updates/` sa nikdy neprepíšu.\n- Súbor `.url` v `/bundles/` obsahuje URL; bundle sa z nej stiahne.\n- `.bundleignore` v koreni uvádza cesty, ktoré sa nekopírujú.\n\nBundle vytvoríš v príkazovom riadku: `total4 bundle app.bundle`. Rozbalíš ho cez `total4 extract app.bundle`.\n\n## Balíky\n\nBalík je súbor `.package` (alebo adresár s názvom `name.package`) v `/packages/`. Rozbalí sa do dočasného adresára a nainštaluje sa jeho `index.js`. Jeho súbory čítaš cez `PATH.package('name/file.txt')`.\n\n## Načítanie bez servera\n\n`LOAD()` nainštaluje aplikáciu bez spustenia HTTP servera. Použi ho v skriptoch, workeroch a testoch:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,models,schemas,operations', function() {\n\t// the code is installed\n});\n```\n\n## Workery\n\n`/workers/` obsahuje skripty, ktoré bežia v samostatnom procese (`WORKER()`, `NEWFORK()`) alebo vo worker vlákne (`NEWTHREAD()`). Pri štarte sa neinštalujú.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Testing","summary":"Run groups of tests with TESTER() and send virtual requests to your routes with TEST() and ACTION().","markdown":"---\ntitle: Testing\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Testing\n\n> Run groups of tests with TESTER() and send virtual requests to your routes with TEST() and ACTION().\n\nThere are two tools. `TESTER()` runs groups of tests in order and stops at the first failure. `TEST()` sends virtual requests to your routes with `ACTION()`, without any HTTP connection:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` collects many requests and reports the result as an object, as JSON or as an HTML page.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Tests","summary":"Führe Testgruppen mit TESTER() aus und sende mit TEST() und ACTION() virtuelle Requests an deine Routen.","markdown":"---\ntitle: Tests\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tests\n\n> Führe Testgruppen mit TESTER() aus und sende mit TEST() und ACTION() virtuelle Requests an deine Routen.\n\nEs gibt zwei Werkzeuge. `TESTER()` führt Gruppen von Tests nacheinander aus und stoppt beim ersten Fehlschlag. `TEST()` sendet virtuelle Requests an deine Routen mit `ACTION()`, ganz ohne HTTP-Verbindung:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` sammelt viele Requests und meldet das Ergebnis als Objekt, als JSON oder als HTML-Seite.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Pruebas","summary":"Ejecuta grupos de pruebas con TESTER() y envía peticiones virtuales a tus rutas con TEST() y ACTION().","markdown":"---\ntitle: Pruebas\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Pruebas\n\n> Ejecuta grupos de pruebas con TESTER() y envía peticiones virtuales a tus rutas con TEST() y ACTION().\n\nHay dos herramientas. `TESTER()` ejecuta grupos de tests en orden y se detiene en el primer fallo. `TEST()` envía peticiones virtuales a tus rutas con `ACTION()`, sin ninguna conexión HTTP:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` reúne muchas peticiones e informa del resultado como un objeto, como JSON o como una página HTML.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Tests","summary":"Exécute des groupes de tests avec TESTER() et envoie des requêtes virtuelles à tes routes avec TEST() et ACTION().","markdown":"---\ntitle: Tests\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tests\n\n> Exécute des groupes de tests avec TESTER() et envoie des requêtes virtuelles à tes routes avec TEST() et ACTION().\n\nIl existe deux outils. `TESTER()` exécute des groupes de tests dans l'ordre et s'arrête au premier échec. `TEST()` envoie des requêtes virtuelles à tes routes avec `ACTION()`, sans aucune connexion HTTP :\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` rassemble de nombreuses requêtes et présente le résultat sous forme d'objet, de JSON ou de page HTML.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Test","summary":"Esegui gruppi di test con TESTER() e invia richieste virtuali alle tue route con TEST() e ACTION().","markdown":"---\ntitle: Test\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Test\n\n> Esegui gruppi di test con TESTER() e invia richieste virtuali alle tue route con TEST() e ACTION().\n\nCi sono due strumenti. `TESTER()` esegue gruppi di test in ordine e si ferma al primo fallimento. `TEST()` invia richieste virtuali alle tue route con `ACTION()`, senza alcuna connessione HTTP:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` raccoglie molte richieste e riporta il risultato come oggetto, come JSON o come pagina HTML.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JafRo11cd61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/testing/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Testovanie","summary":"Spúšťaj skupiny testov pomocou TESTER() a posielaj virtuálne požiadavky na svoje trasy pomocou TEST() a ACTION().","markdown":"---\ntitle: Testovanie\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/testing/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Testovanie\n\n> Spúšťaj skupiny testov pomocou TESTER() a posielaj virtuálne požiadavky na svoje trasy pomocou TEST() a ACTION().\n\nSú dva nástroje. `TESTER()` spúšťa skupiny testov po poradí a zastaví sa pri prvom zlyhaní. `TEST()` posiela virtuálne požiadavky na tvoje trasy cez `ACTION()`, bez akéhokoľvek HTTP spojenia:\n\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\t\tgroup('Products', function(test) {\n\t\t\ttest('List', function(next) {\n\t\t\t\tACTION('GET /api/products/', function(err, response) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\t\t});\n\t\tstart();\n\t});\n});\n```\n\n`TEST()` zhromaždí veľa požiadaviek a výsledok vráti ako objekt, ako JSON alebo ako HTML stránku.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafj6X6Yu61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"LDAP","summary":"Read entries from an LDAP server such as Active Directory with LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Read entries from an LDAP server such as Active Directory with LDAP().\n\n`LDAP(opt, [callback])` reads entries from an LDAP server such as Active Directory. It binds with a user and a password, then searches a base DN for entries of one `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Option | Meaning |\n| --- | --- |\n| `ldap` | `{ host, port }`, the port defaults to `389` |\n| `user`, `password` | The account used to bind |\n| `type` | `person`, `group` or `profile` |\n| `dn` | The base DN of the search |\n| `login` | The `sAMAccountName` searched by the `profile` type |\n| `noauth` | `true` searches without binding |\n\nEach entry is a plain object with attribute names as keys. When an attribute has more values (for example `memberOf`), its value is an array. The `profile` type returns one object or `null`. Without a callback the function returns a Promise:\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nThe connection is not encrypted (plain LDAP), so use it in a trusted network.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafj6X6Yu61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"LDAP","summary":"Lies Einträge aus einem LDAP-Server wie Active Directory mit LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Lies Einträge aus einem LDAP-Server wie Active Directory mit LDAP().\n\n`LDAP(opt, [callback])` liest Einträge von einem LDAP-Server wie Active Directory. Es meldet sich mit einem Benutzer und einem Passwort an (Bind) und durchsucht dann eine Basis-DN nach Einträgen einer `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Option | Bedeutung |\n| --- | --- |\n| `ldap` | `{ host, port }`, der Port ist standardmäßig `389` |\n| `user`, `password` | Das Konto für den Bind |\n| `type` | `person`, `group` oder `profile` |\n| `dn` | Die Basis-DN der Suche |\n| `login` | Der `sAMAccountName`, nach dem der Typ `profile` sucht |\n| `noauth` | `true` sucht ohne Bind |\n\nJeder Eintrag ist ein einfaches Objekt mit Attributnamen als Schlüsseln. Hat ein Attribut mehrere Werte (zum Beispiel `memberOf`), ist sein Wert ein Array. Der Typ `profile` gibt ein Objekt oder `null` zurück. Ohne Callback gibt die Funktion eine Promise zurück:\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nDie Verbindung ist nicht verschlüsselt (einfaches LDAP), also nutze sie in einem vertrauenswürdigen Netzwerk.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafj6X6Yu61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"LDAP","summary":"Lee entradas de un servidor LDAP como Active Directory con LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Lee entradas de un servidor LDAP como Active Directory con LDAP().\n\n`LDAP(opt, [callback])` lee entradas de un servidor LDAP como Active Directory. Se autentica con un usuario y una contraseña y después busca en un DN base las entradas de un `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Opción | Significado |\n| --- | --- |\n| `ldap` | `{ host, port }`, el puerto por defecto es `389` |\n| `user`, `password` | La cuenta usada para autenticarse |\n| `type` | `person`, `group` o `profile` |\n| `dn` | El DN base de la búsqueda |\n| `login` | El `sAMAccountName` que busca el tipo `profile` |\n| `noauth` | `true` busca sin autenticarse |\n\nCada entrada es un objeto plano con los nombres de los atributos como claves. Cuando un atributo tiene varios valores (por ejemplo `memberOf`), su valor es un array. El tipo `profile` devuelve un objeto o `null`. Sin callback, la función devuelve una promesa:\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nLa conexión no está cifrada (LDAP plano), así que úsala en una red de confianza.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafj6X6Yu61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"LDAP","summary":"Lis des entrées depuis un serveur LDAP comme Active Directory avec LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Lis des entrées depuis un serveur LDAP comme Active Directory avec LDAP().\n\n`LDAP(opt, [callback])` lit des entrées depuis un serveur LDAP tel qu'Active Directory. Il se connecte (bind) avec un utilisateur et un mot de passe, puis recherche dans un DN de base les entrées d'un `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Option | Signification |\n| --- | --- |\n| `ldap` | `{ host, port }`, le port vaut `389` par défaut |\n| `user`, `password` | Le compte utilisé pour le bind |\n| `type` | `person`, `group` ou `profile` |\n| `dn` | Le DN de base de la recherche |\n| `login` | Le `sAMAccountName` recherché par le type `profile` |\n| `noauth` | `true` effectue la recherche sans bind |\n\nChaque entrée est un objet simple dont les clés sont les noms d'attributs. Lorsqu'un attribut a plusieurs valeurs (par exemple `memberOf`), sa valeur est un tableau. Le type `profile` renvoie un objet ou `null`. Sans callback, la fonction renvoie une Promise :\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nLa connexion n'est pas chiffrée (LDAP simple) ; utilise-la donc dans un réseau de confiance.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafj6X6Yu61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"LDAP","summary":"Leggi voci da un server LDAP come Active Directory con LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Leggi voci da un server LDAP come Active Directory con LDAP().\n\n`LDAP(opt, [callback])` legge voci da un server LDAP come Active Directory. Effettua il bind con un utente e una password, poi cerca in un DN di base le voci di un `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Opzione | Significato |\n| --- | --- |\n| `ldap` | `{ host, port }`, la porta predefinita è `389` |\n| `user`, `password` | L'account usato per il bind |\n| `type` | `person`, `group` o `profile` |\n| `dn` | Il DN di base della ricerca |\n| `login` | Il `sAMAccountName` cercato dal tipo `profile` |\n| `noauth` | `true` cerca senza effettuare il bind |\n\nOgni voce è un semplice oggetto con i nomi degli attributi come chiavi. Quando un attributo ha più valori (ad esempio `memberOf`), il suo valore è un array. Il tipo `profile` restituisce un oggetto oppure `null`. Senza callback la funzione restituisce una Promise:\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nLa connessione non è cifrata (LDAP semplice), quindi usala in una rete affidabile.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafj6X6Yu61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/ldap/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"LDAP","summary":"Čítaj záznamy z LDAP servera, napríklad Active Directory, pomocou LDAP().","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/ldap/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# LDAP\n\n> Čítaj záznamy z LDAP servera, napríklad Active Directory, pomocou LDAP().\n\n`LDAP(opt, [callback])` načíta záznamy z LDAP servera, napríklad z Active Directory. Prihlási sa (bind) používateľom a heslom a potom v základnom DN vyhľadá záznamy jednej `objectClass`.\n\n```js\nLDAP({\n\tldap: { host: '10.0.0.5', port: 389 },\n\tuser: 'CN=reader,OU=Services,DC=company,DC=local',\n\tpassword: CONF.ldap_password,\n\ttype: 'person',\n\tdn: 'OU=Users,DC=company,DC=local'\n}, function(err, users) {\n\tif (err)\n\t\treturn;\n\tfor (var user of users)\n\t\tconsole.log(user.sAMAccountName, user.mail);\n});\n```\n\n| Voľba | Význam |\n| --- | --- |\n| `ldap` | `{ host, port }`, port je predvolene `389` |\n| `user`, `password` | Účet použitý na bind |\n| `type` | `person`, `group` alebo `profile` |\n| `dn` | Základné DN vyhľadávania |\n| `login` | `sAMAccountName`, ktoré hľadá typ `profile` |\n| `noauth` | `true` vyhľadáva bez bindu |\n\nKaždý záznam je jednoduchý objekt s názvami atribútov ako kľúčmi. Keď má atribút viac hodnôt (napríklad `memberOf`), jeho hodnota je pole. Typ `profile` vráti jeden objekt alebo `null`. Bez callbacku funkcia vráti Promise:\n\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5' }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\n```\n\nSpojenie nie je šifrované (čisté LDAP), preto ho používaj v dôveryhodnej sieti.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjFu47060f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Markdown","summary":"Convert Markdown to HTML with String.markdown() and choose what it produces with its options.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Convert Markdown to HTML with String.markdown() and choose what it produces with its options.\n\nEvery string has the method `markdown([opt])`, which returns HTML:\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nThe parser supports headlines (`#` to `#####`), lists with `-`, `*` or `+` and ordered lists (`1.` or `a.`), task lists (`- [x] done`), tables with alignment, code blocks with a language, blockquotes (`> `), sections (`< `), collapsible blocks between `:::` lines, horizontal lines (`---`, `***`), images (`![alt](url)`, `![+alt](url)` without the responsive class, `![-alt](url)` for a gallery), links, footnotes (`[1](#1)` and `#1: text`), keywords (`{text}(type)`), icons (`:ti-home:` or `:fa fa-home:`), and links detected in plain text. Links to an e-mail address or a phone number become `mailto:` and `tel:` links.\n\nHTML in the source is always encoded, so the output is safe to put into a page. Every block has the class `markdown-line` and its line number, which helps you style the output and map it back to the source.\n\nOptions change the output:\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nEvery feature can be turned off with `false`: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` and `emptynewline`. The `custom` function changes each raw line before formatting, so you can add your own syntax.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjFu47060f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Markdown","summary":"Wandle Markdown mit String.markdown() in HTML um und bestimme mit seinen Optionen, was es erzeugt.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Wandle Markdown mit String.markdown() in HTML um und bestimme mit seinen Optionen, was es erzeugt.\n\nJeder String hat die Methode `markdown([opt])`, die HTML zurückgibt:\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nDer Parser unterstützt Überschriften (`#` bis `#####`), Listen mit `-`, `*` oder `+` und nummerierte Listen (`1.` oder `a.`), Aufgabenlisten (`- [x] done`), Tabellen mit Ausrichtung, Codeblöcke mit Sprache, Zitate (`> `), Abschnitte (`< `), einklappbare Blöcke zwischen `:::`-Zeilen, horizontale Linien (`---`, `***`), Bilder (`![alt](url)`, `![+alt](url)` ohne die responsive Klasse, `![-alt](url)` für eine Galerie), Links, Fußnoten (`[1](#1)` und `#1: text`), Schlüsselwörter (`{text}(type)`), Icons (`:ti-home:` oder `:fa fa-home:`) und Links, die im reinen Text erkannt werden. Links zu einer E-Mail-Adresse oder einer Telefonnummer werden zu `mailto:`- und `tel:`-Links.\n\nHTML im Quelltext wird immer kodiert, daher kannst du die Ausgabe sicher in eine Seite einfügen. Jeder Block hat die Klasse `markdown-line` und seine Zeilennummer, was dir hilft, die Ausgabe zu stylen und sie dem Quelltext zuzuordnen.\n\nOptionen ändern die Ausgabe:\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nJede Funktion lässt sich mit `false` abschalten: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` und `emptynewline`. Die Funktion `custom` ändert jede Rohzeile vor der Formatierung, sodass du deine eigene Syntax hinzufügen kannst.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjFu47060f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Markdown","summary":"Convierte Markdown en HTML con String.markdown() y elige lo que produce con sus opciones.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Convierte Markdown en HTML con String.markdown() y elige lo que produce con sus opciones.\n\nTodo string tiene el método `markdown([opt])`, que devuelve HTML:\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nEl parser admite títulos (`#` a `#####`), listas con `-`, `*` o `+` y listas ordenadas (`1.` o `a.`), listas de tareas (`- [x] done`), tablas con alineación, bloques de código con lenguaje, citas (`> `), secciones (`< `), bloques plegables entre líneas `:::`, líneas horizontales (`---`, `***`), imágenes (`![alt](url)`, `![+alt](url)` sin la clase responsive, `![-alt](url)` para una galería), enlaces, notas al pie (`[1](#1)` y `#1: text`), palabras clave (`{text}(type)`), iconos (`:ti-home:` o `:fa fa-home:`) y enlaces detectados en texto plano. Los enlaces a una dirección de e-mail o a un número de teléfono se convierten en enlaces `mailto:` y `tel:`.\n\nEl HTML del código fuente siempre se codifica, así que la salida es segura para insertarla en una página. Cada bloque tiene la clase `markdown-line` y su número de línea, lo que te ayuda a dar estilo a la salida y a relacionarla con el código fuente.\n\nLas opciones cambian la salida:\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nCada funcionalidad se puede desactivar con `false`: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` y `emptynewline`. La función `custom` modifica cada línea sin procesar antes del formateo, así que puedes añadir tu propia sintaxis.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjFu47060f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Markdown","summary":"Convertis du Markdown en HTML avec String.markdown() et choisis ce qu'il produit avec ses options.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Convertis du Markdown en HTML avec String.markdown() et choisis ce qu'il produit avec ses options.\n\nChaque chaîne possède la méthode `markdown([opt])`, qui renvoie du HTML :\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nLe parseur prend en charge les titres (`#` à `#####`), les listes avec `-`, `*` ou `+` et les listes numérotées (`1.` ou `a.`), les listes de tâches (`- [x] done`), les tableaux avec alignement, les blocs de code avec un langage, les citations (`> `), les sections (`< `), les blocs repliables entre des lignes `:::`, les lignes horizontales (`---`, `***`), les images (`![alt](url)`, `![+alt](url)` sans la classe responsive, `![-alt](url)` pour une galerie), les liens, les notes de bas de page (`[1](#1)` et `#1: text`), les mots-clés (`{text}(type)`), les icônes (`:ti-home:` ou `:fa fa-home:`), et les liens détectés dans le texte brut. Les liens vers une adresse e-mail ou un numéro de téléphone deviennent des liens `mailto:` et `tel:`.\n\nLe HTML de la source est toujours encodé, la sortie peut donc être insérée sans risque dans une page. Chaque bloc a la classe `markdown-line` et son numéro de ligne, ce qui t'aide à styliser la sortie et à la faire correspondre à la source.\n\nLes options modifient la sortie :\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nChaque fonctionnalité peut être désactivée avec `false` : `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` et `emptynewline`. La fonction `custom` modifie chaque ligne brute avant le formatage, ce qui te permet d'ajouter ta propre syntaxe.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjFu47060f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Markdown","summary":"Converti Markdown in HTML con String.markdown() e scegli cosa produce con le sue opzioni.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Converti Markdown in HTML con String.markdown() e scegli cosa produce con le sue opzioni.\n\nOgni stringa ha il metodo `markdown([opt])`, che restituisce HTML:\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nIl parser supporta titoli (da `#` a `#####`), elenchi con `-`, `*` o `+` ed elenchi ordinati (`1.` o `a.`), elenchi di attività (`- [x] done`), tabelle con allineamento, blocchi di codice con un linguaggio, citazioni (`> `), sezioni (`< `), blocchi comprimibili tra righe `:::`, linee orizzontali (`---`, `***`), immagini (`![alt](url)`, `![+alt](url)` senza la classe responsive, `![-alt](url)` per una galleria), link, note a piè di pagina (`[1](#1)` e `#1: text`), parole chiave (`{text}(type)`), icone (`:ti-home:` o `:fa fa-home:`) e link riconosciuti nel testo semplice. I link a un indirizzo e-mail o a un numero di telefono diventano link `mailto:` e `tel:`.\n\nL'HTML nel sorgente viene sempre codificato, quindi l'output è sicuro da inserire in una pagina. Ogni blocco ha la classe `markdown-line` e il suo numero di riga, il che ti aiuta a dare stile all'output e a ricollegarlo al sorgente.\n\nLe opzioni cambiano l'output:\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nOgni funzionalità può essere disattivata con `false`: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` ed `emptynewline`. La funzione `custom` modifica ogni riga grezza prima della formattazione, così puoi aggiungere una tua sintassi.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjFu47060f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/markdown/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Markdown","summary":"Preveď Markdown na HTML pomocou String.markdown() a jeho voľbami urči, čo vytvorí.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/markdown/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Markdown\n\n> Preveď Markdown na HTML pomocou String.markdown() a jeho voľbami urči, čo vytvorí.\n\nKaždý reťazec má metódu `markdown([opt])`, ktorá vráti HTML:\n\n```js\nvar html = '# Hello\\n\\nThis is **bold**, _underlined_ and `code`.\\n\\n- one\\n- two\\n\\t- nested'.markdown();\n```\n\nParser podporuje nadpisy (`#` až `#####`), zoznamy s `-`, `*` alebo `+` a číslované zoznamy (`1.` alebo `a.`), zoznamy úloh (`- [x] done`), tabuľky so zarovnaním, bloky kódu s jazykom, citácie (`> `), sekcie (`< `), rozbaľovacie bloky medzi riadkami `:::`, vodorovné čiary (`---`, `***`), obrázky (`![alt](url)`, `![+alt](url)` bez responzívnej triedy, `![-alt](url)` pre galériu), odkazy, poznámky pod čiarou (`[1](#1)` a `#1: text`), kľúčové slová (`{text}(type)`), ikony (`:ti-home:` alebo `:fa fa-home:`) a odkazy rozpoznané v obyčajnom texte. Odkazy na e-mailovú adresu alebo telefónne číslo sa stanú odkazmi `mailto:` a `tel:`.\n\nHTML v zdroji sa vždy kóduje, takže výstup môžeš bezpečne vložiť do stránky. Každý blok má triedu `markdown-line` a číslo svojho riadku, čo ti pomôže výstup štýlovať a priradiť ho späť k zdroju.\n\nVoľby menia výstup:\n\n```js\nvar html = text.markdown({\n\twrap: false,          // no <div class=\"markdown markdown-container\">\n\tlinetag: 'div',       // tag of normal lines (default 'p')\n\tbookmarks: true,      // id=\"...\" for headlines (default true)\n\tprefix: 'help-',      // prefix of those ids\n\ttables: false,        // turn off a feature\n\thtml: function(line, type) {\n\t\treturn type === '#' ? line.toUpperCase() : line;\n\t}\n});\n```\n\nKaždú funkciu môžeš vypnúť hodnotou `false`: `headlines`, `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` a `emptynewline`. Funkcia `custom` mení každý surový riadok pred formátovaním, takže môžeš pridať vlastnú syntax.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"HTML parser","summary":"Parse HTML on the server into a tree of nodes that you can search and change.","markdown":"---\ntitle: HTML parser\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTML parser\n\n> Parse HTML on the server into a tree of nodes that you can search and change.\n\n`String.parseHTML([trim])` turns HTML into a tree of nodes. It is a small parser for reading and editing documents on the server, not a full browser DOM.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` supports tag names, `*`, `#id`, `.class`, `[attr=\"value\"]`, descendants (`ul li`), direct children (`ul > li`) and more selectors separated by commas. `closest()` searches the ancestors. The result is an array with a few extra methods (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` and `html()`) that apply to all found elements.\n\nA node has `tagName` (upper case), `attrs`, `children`, `parentNode` and, for text nodes, `textContent`. You can change it with `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` and `remove()`, and serialize it with `html([formatted])`. `text()` returns the text without tags and with decoded entities:\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nComments are removed and `<!DOCTYPE>` is skipped.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"HTML-Parser","summary":"Parse HTML auf dem Server in einen Baum von Knoten, den du durchsuchen und ändern kannst.","markdown":"---\ntitle: HTML-Parser\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTML-Parser\n\n> Parse HTML auf dem Server in einen Baum von Knoten, den du durchsuchen und ändern kannst.\n\n`String.parseHTML([trim])` wandelt HTML in einen Baum aus Knoten um. Es ist ein kleiner Parser zum Lesen und Bearbeiten von Dokumenten auf dem Server, kein vollständiges Browser-DOM.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` unterstützt Tag-Namen, `*`, `#id`, `.class`, `[attr=\"value\"]`, Nachfahren (`ul li`), direkte Kinder (`ul > li`) und mehrere durch Kommas getrennte Selektoren. `closest()` durchsucht die Vorfahren. Das Ergebnis ist ein Array mit einigen zusätzlichen Methoden (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` und `html()`), die auf alle gefundenen Elemente wirken.\n\nEin Knoten hat `tagName` (in Großbuchstaben), `attrs`, `children`, `parentNode` und, bei Textknoten, `textContent`. Du kannst ihn mit `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` und `remove()` ändern und mit `html([formatted])` serialisieren. `text()` gibt den Text ohne Tags und mit dekodierten Entities zurück:\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nKommentare werden entfernt, und `<!DOCTYPE>` wird übersprungen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Parser de HTML","summary":"Analiza HTML en el servidor en un árbol de nodos que puedes buscar y modificar.","markdown":"---\ntitle: Parser de HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Parser de HTML\n\n> Analiza HTML en el servidor en un árbol de nodos que puedes buscar y modificar.\n\n`String.parseHTML([trim])` convierte HTML en un árbol de nodos. Es un parser pequeño para leer y editar documentos en el servidor, no un DOM de navegador completo.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` admite nombres de etiqueta, `*`, `#id`, `.class`, `[attr=\"value\"]`, descendientes (`ul li`), hijos directos (`ul > li`) y varios selectores separados por comas. `closest()` busca en los ancestros. El resultado es un array con algunos métodos adicionales (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` y `html()`) que se aplican a todos los elementos encontrados.\n\nUn nodo tiene `tagName` (en mayúsculas), `attrs`, `children`, `parentNode` y, para los nodos de texto, `textContent`. Puedes modificarlo con `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` y `remove()`, y serializarlo con `html([formatted])`. `text()` devuelve el texto sin etiquetas y con las entidades decodificadas:\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nLos comentarios se eliminan y `<!DOCTYPE>` se omite.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Parseur HTML","summary":"Analyse du HTML sur le serveur en un arbre de nœuds que tu peux parcourir et modifier.","markdown":"---\ntitle: Parseur HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Parseur HTML\n\n> Analyse du HTML sur le serveur en un arbre de nœuds que tu peux parcourir et modifier.\n\n`String.parseHTML([trim])` transforme du HTML en un arbre de nœuds. C'est un petit parseur pour lire et modifier des documents sur le serveur, pas un DOM complet de navigateur.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` prend en charge les noms de balises, `*`, `#id`, `.class`, `[attr=\"value\"]`, les descendants (`ul li`), les enfants directs (`ul > li`) et plusieurs sélecteurs séparés par des virgules. `closest()` recherche parmi les ancêtres. Le résultat est un tableau doté de quelques méthodes supplémentaires (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` et `html()`) qui s'appliquent à tous les éléments trouvés.\n\nUn nœud possède `tagName` (en majuscules), `attrs`, `children`, `parentNode` et, pour les nœuds texte, `textContent`. Tu peux le modifier avec `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` et `remove()`, et le sérialiser avec `html([formatted])`. `text()` renvoie le texte sans les balises et avec les entités décodées :\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nLes commentaires sont supprimés et `<!DOCTYPE>` est ignoré.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Parser HTML","summary":"Analizza HTML sul server in un albero di nodi che puoi cercare e modificare.","markdown":"---\ntitle: Parser HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Parser HTML\n\n> Analizza HTML sul server in un albero di nodi che puoi cercare e modificare.\n\n`String.parseHTML([trim])` trasforma l'HTML in un albero di nodi. È un piccolo parser per leggere e modificare documenti sul server, non un DOM completo da browser.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` supporta nomi di tag, `*`, `#id`, `.class`, `[attr=\"value\"]`, discendenti (`ul li`), figli diretti (`ul > li`) e più selettori separati da virgole. `closest()` cerca tra gli antenati. Il risultato è un array con alcuni metodi in più (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` e `html()`) che si applicano a tutti gli elementi trovati.\n\nUn nodo ha `tagName` (in maiuscolo), `attrs`, `children`, `parentNode` e, per i nodi di testo, `textContent`. Puoi modificarlo con `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` e `remove()`, e serializzarlo con `html([formatted])`. `text()` restituisce il testo senza tag e con le entità decodificate:\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nI commenti vengono rimossi e `<!DOCTYPE>` viene ignorato.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjPA4sX61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/html-parser/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"HTML parser","summary":"Parsuj HTML na serveri do stromu uzlov, ktorý môžeš prehľadávať a meniť.","markdown":"---\ntitle: HTML parser\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/html-parser/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# HTML parser\n\n> Parsuj HTML na serveri do stromu uzlov, ktorý môžeš prehľadávať a meniť.\n\n`String.parseHTML([trim])` premení HTML na strom uzlov. Je to malý parser na čítanie a úpravu dokumentov na serveri, nie plnohodnotný DOM prehliadača.\n\n```js\nvar dom = '<ul class=\"menu\"><li><a href=\"/\">Home</a></li><li><a href=\"https://www.totaljs.com\">Total.js</a></li></ul>'.parseHTML(true);\n\nvar links = dom.find('a');\nfor (var a of links) {\n\tif (a.attr('href').indexOf('http') === 0)\n\t\ta.attr('target', '_blank').aclass('external');\n}\n\nconsole.log(dom.html());\n```\n\n`find()` podporuje názvy tagov, `*`, `#id`, `.class`, `[attr=\"value\"]`, potomkov (`ul li`), priame deti (`ul > li`) a viac selektorov oddelených čiarkami. `closest()` hľadá v predkoch. Výsledkom je pole s niekoľkými metódami navyše (`aclass()`, `rclass()`, `tclass()`, `attr()`, `attrd()` a `html()`), ktoré sa použijú na všetky nájdené elementy.\n\nUzol má `tagName` (veľkými písmenami), `attrs`, `children`, `parentNode` a pri textových uzloch `textContent`. Meniť ho môžeš cez `attr()`, `attrd()`, `aclass()`, `rclass()`, `tclass()`, `css()`, `append()`, `prepend()` a `remove()` a serializovať cez `html([formatted])`. `text()` vráti text bez tagov a s dekódovanými entitami:\n\n```js\nvar dom = '<article><h1>News &amp; updates</h1><p>Text</p><script>track();</script></article>'.parseHTML();\n\nfor (var script of dom.find('script'))\n\tscript.remove();\n\nvar title = dom.find('h1')[0].text(); // News & updates\nvar clean = dom.html(true);\n```\n\nKomentáre sa odstránia a `<!DOCTYPE>` sa preskočí.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafjRc6SX61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Macros","summary":"Compile a small rule language into a function with NEWMACRO(), for rules that users write.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Macros\n\n> Compile a small rule language into a function with NEWMACRO(), for rules that users write.\n\n`NEWMACRO(str, [nocompile], [isasync])` compiles a small rule language into a function. It is useful when users write rules in your application (prices, discounts, validations) and you do not want to run their JavaScript.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nThe language has `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, the values `TRUE`, `FALSE`, `YES`, `NO`, `OK` and `NULL`, quoted values, comments with `//` and private variables with `#`:\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nNames are converted to lower case, so properties of the model and names of helpers must be lower case. Avoid property names that contain the words `if` or `else`, because the compiler replaces them as keywords. With `isasync` the helpers can be async functions and the macro returns a Promise. With `nocompile` you get the generated JavaScript, which helps when you debug a rule.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjRc6SX61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Makros","summary":"Kompiliere mit NEWMACRO() eine kleine Regelsprache in eine Funktion, für Regeln, die Benutzer schreiben.","markdown":"---\ntitle: Makros\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Makros\n\n> Kompiliere mit NEWMACRO() eine kleine Regelsprache in eine Funktion, für Regeln, die Benutzer schreiben.\n\n`NEWMACRO(str, [nocompile], [isasync])` kompiliert eine kleine Regelsprache in eine Funktion. Das ist nützlich, wenn Benutzer in deiner Anwendung Regeln schreiben (Preise, Rabatte, Validierungen) und du ihr JavaScript nicht ausführen willst.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nDie Sprache hat `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, die Werte `TRUE`, `FALSE`, `YES`, `NO`, `OK` und `NULL`, Werte in Anführungszeichen, Kommentare mit `//` und private Variablen mit `#`:\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nNamen werden in Kleinbuchstaben umgewandelt, also müssen Eigenschaften des Modells und Namen von Helpern kleingeschrieben sein. Vermeide Eigenschaftsnamen, die die Wörter `if` oder `else` enthalten, weil der Compiler sie als Schlüsselwörter ersetzt. Mit `isasync` können die Helper asynchrone Funktionen sein, und das Makro gibt eine Promise zurück. Mit `nocompile` erhältst du das erzeugte JavaScript, was beim Debuggen einer Regel hilft.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjRc6SX61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Macros","summary":"Compila un pequeño lenguaje de reglas en una función con NEWMACRO(), para reglas que escriben los usuarios.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Macros\n\n> Compila un pequeño lenguaje de reglas en una función con NEWMACRO(), para reglas que escriben los usuarios.\n\n`NEWMACRO(str, [nocompile], [isasync])` compila un pequeño lenguaje de reglas en una función. Es útil cuando los usuarios escriben reglas en tu aplicación (precios, descuentos, validaciones) y no quieres ejecutar su JavaScript.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nEl lenguaje tiene `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, los valores `TRUE`, `FALSE`, `YES`, `NO`, `OK` y `NULL`, valores entre comillas, comentarios con `//` y variables privadas con `#`:\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nLos nombres se convierten a minúsculas, así que las propiedades del modelo y los nombres de los helpers deben estar en minúsculas. Evita nombres de propiedades que contengan las palabras `if` o `else`, porque el compilador las sustituye como palabras clave. Con `isasync` los helpers pueden ser funciones async y la macro devuelve una promesa. Con `nocompile` obtienes el JavaScript generado, lo que ayuda cuando depuras una regla.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjRc6SX61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Macros","summary":"Compile un petit langage de règles en une fonction avec NEWMACRO(), pour des règles que les utilisateurs écrivent.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Macros\n\n> Compile un petit langage de règles en une fonction avec NEWMACRO(), pour des règles que les utilisateurs écrivent.\n\n`NEWMACRO(str, [nocompile], [isasync])` compile un petit langage de règles en une fonction. C'est utile lorsque les utilisateurs écrivent des règles dans ton application (prix, remises, validations) et que tu ne veux pas exécuter leur JavaScript.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nLe langage comporte `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, les valeurs `TRUE`, `FALSE`, `YES`, `NO`, `OK` et `NULL`, des valeurs entre guillemets, des commentaires avec `//` et des variables privées avec `#` :\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nLes noms sont convertis en minuscules ; les propriétés du modèle et les noms des helpers doivent donc être en minuscules. Évite les noms de propriétés contenant les mots `if` ou `else`, car le compilateur les remplace comme des mots-clés. Avec `isasync`, les helpers peuvent être des fonctions async et la macro renvoie une Promise. Avec `nocompile`, tu obtiens le JavaScript généré, ce qui aide à déboguer une règle.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjRc6SX61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Macro","summary":"Compila un piccolo linguaggio di regole in una funzione con NEWMACRO(), per regole scritte dagli utenti.","markdown":"---\ntitle: Macro\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Macro\n\n> Compila un piccolo linguaggio di regole in una funzione con NEWMACRO(), per regole scritte dagli utenti.\n\n`NEWMACRO(str, [nocompile], [isasync])` compila un piccolo linguaggio di regole in una funzione. È utile quando gli utenti scrivono regole nella tua applicazione (prezzi, sconti, validazioni) e non vuoi eseguire il loro JavaScript.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nIl linguaggio ha `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, i valori `TRUE`, `FALSE`, `YES`, `NO`, `OK` e `NULL`, valori tra virgolette, commenti con `//` e variabili private con `#`:\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nI nomi vengono convertiti in minuscolo, quindi le proprietà del modello e i nomi degli helper devono essere in minuscolo. Evita nomi di proprietà che contengono le parole `if` o `else`, perché il compilatore li sostituisce come parole chiave. Con `isasync` gli helper possono essere funzioni async e la macro restituisce una Promise. Con `nocompile` ottieni il JavaScript generato, che ti aiuta quando fai il debug di una regola.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjRc6SX61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/macros/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Makrá","summary":"Skompiluj malý jazyk pravidiel do funkcie pomocou NEWMACRO(), pre pravidlá, ktoré píšu používatelia.","markdown":"---\ntitle: \"Makrá\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/macros/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Makrá\n\n> Skompiluj malý jazyk pravidiel do funkcie pomocou NEWMACRO(), pre pravidlá, ktoré píšu používatelia.\n\n`NEWMACRO(str, [nocompile], [isasync])` skompiluje malý jazyk pravidiel do funkcie. Hodí sa, keď používatelia vo tvojej aplikácii píšu pravidlá (ceny, zľavy, validácie) a nechceš spúšťať ich JavaScript.\n\n```js\nvar macro = NEWMACRO([\n\t'// discount rule',\n\t'IF total > 1000 AND vip',\n\t'\tRETURN discount(total, 15)',\n\t'ELSE IF total > 500',\n\t'\tRETURN discount(total, 5)',\n\t'FI',\n\t'RETURN total'\n].join('\\n'));\n\nvar helpers = {};\nhelpers.discount = function(value, percentage) {\n\treturn value - (value / 100 * percentage);\n};\n\nmacro({ total: 1200, vip: true }, helpers); // 1020\n```\n\nJazyk má `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, hodnoty `TRUE`, `FALSE`, `YES`, `NO`, `OK` a `NULL`, hodnoty v úvodzovkách, komentáre s `//` a súkromné premenné s `#`:\n\n```js\nvar macro = NEWMACRO('#price = price * count\\nIF #price > 100\\nRETURN \"big\"\\nFI\\nRETURN \"small\"');\n```\n\nNázvy sa prevádzajú na malé písmená, takže vlastnosti modelu a názvy pomocných funkcií musia byť malými písmenami. Vyhni sa názvom vlastností, ktoré obsahujú slová `if` alebo `else`, pretože kompilátor ich nahrádza ako kľúčové slová. S `isasync` môžu byť pomocné funkcie asynchrónne a makro vráti Promise. S `nocompile` dostaneš vygenerovaný JavaScript, čo pomáha pri ladení pravidla.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"CMS compiler","summary":"Compile pages made with the Total.js CMS editor and render them with their widgets.","markdown":"---\ntitle: CMS compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# CMS compiler\n\n> Compile pages made with the Total.js CMS editor and render them with their widgets.\n\n`CMSCOMPILER(html, widgets, [used])` compiles a page made with the Total.js CMS editor. Widgets in the HTML are marked with `data-cms=\"id__config\"`. The compiler removes the editor markup, keeps static parts as strings and prepares widgets for rendering, so one page can be compiled once and rendered many times.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` calls the widgets and builds the HTML. A widget calls `next(html, [replace], [cache])`; with `cache` its output is stored in the compiled page and reused. A layout is a compiled page with an element `id=\"CMS\"`; pass it as the second argument and the page is inserted into it. Navigations (`<script type=\"text/navigation\" name=\"...\">`) and breadcrumbs (`<script type=\"text/breadcrumb\">`) are Tangular templates that read `meta.navigation(id)` and `meta.breadcrumb`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"CMS-Compiler","summary":"Kompiliere Seiten aus dem CMS-Editor von Total.js und rendere sie mit ihren Widgets.","markdown":"---\ntitle: CMS-Compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# CMS-Compiler\n\n> Kompiliere Seiten aus dem CMS-Editor von Total.js und rendere sie mit ihren Widgets.\n\n`CMSCOMPILER(html, widgets, [used])` kompiliert eine mit dem Total.js-CMS-Editor erstellte Seite. Widgets im HTML sind mit `data-cms=\"id__config\"` markiert. Der Compiler entfernt das Editor-Markup, behält statische Teile als Strings und bereitet Widgets für das Rendern vor, sodass eine Seite einmal kompiliert und viele Male gerendert werden kann.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` ruft die Widgets auf und baut das HTML. Ein Widget ruft `next(html, [replace], [cache])` auf; mit `cache` wird seine Ausgabe in der kompilierten Seite gespeichert und wiederverwendet. Ein Layout ist eine kompilierte Seite mit einem Element `id=\"CMS\"`; übergib es als zweites Argument, und die Seite wird darin eingefügt. Navigationen (`<script type=\"text/navigation\" name=\"...\">`) und Breadcrumbs (`<script type=\"text/breadcrumb\">`) sind Tangular-Templates, die `meta.navigation(id)` und `meta.breadcrumb` lesen.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Compilador de CMS","summary":"Compila páginas hechas con el editor del CMS de Total.js y renderízalas con sus widgets.","markdown":"---\ntitle: Compilador de CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Compilador de CMS\n\n> Compila páginas hechas con el editor del CMS de Total.js y renderízalas con sus widgets.\n\n`CMSCOMPILER(html, widgets, [used])` compila una página creada con el editor de Total.js CMS. Los widgets del HTML se marcan con `data-cms=\"id__config\"`. El compilador elimina el marcado del editor, mantiene las partes estáticas como strings y prepara los widgets para el renderizado, de modo que una página se puede compilar una vez y renderizar muchas veces.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` llama a los widgets y construye el HTML. Un widget llama a `next(html, [replace], [cache])`; con `cache` su salida se guarda en la página compilada y se reutiliza. Una plantilla (layout) es una página compilada con un elemento `id=\"CMS\"`; pásala como segundo argumento y la página se inserta en ella. Las navegaciones (`<script type=\"text/navigation\" name=\"...\">`) y las migas de pan (`<script type=\"text/breadcrumb\">`) son plantillas de Tangular que leen `meta.navigation(id)` y `meta.breadcrumb`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Compilateur CMS","summary":"Compile des pages créées avec l'éditeur CMS de Total.js et rends-les avec leurs widgets.","markdown":"---\ntitle: Compilateur CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Compilateur CMS\n\n> Compile des pages créées avec l'éditeur CMS de Total.js et rends-les avec leurs widgets.\n\n`CMSCOMPILER(html, widgets, [used])` compile une page créée avec l'éditeur Total.js CMS. Les widgets dans le HTML sont marqués avec `data-cms=\"id__config\"`. Le compilateur supprime le balisage de l'éditeur, conserve les parties statiques sous forme de chaînes et prépare les widgets pour le rendu ; une page peut ainsi être compilée une fois et rendue de nombreuses fois.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` appelle les widgets et construit le HTML. Un widget appelle `next(html, [replace], [cache])` ; avec `cache`, son résultat est stocké dans la page compilée et réutilisé. Un layout est une page compilée contenant un élément `id=\"CMS\"` ; passe-le comme deuxième argument et la page y est insérée. Les navigations (`<script type=\"text/navigation\" name=\"...\">`) et les fils d'Ariane (`<script type=\"text/breadcrumb\">`) sont des templates Tangular qui lisent `meta.navigation(id)` et `meta.breadcrumb`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Compilatore CMS","summary":"Compila le pagine create con l'editor CMS di Total.js e renderizzale con i loro widget.","markdown":"---\ntitle: Compilatore CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Compilatore CMS\n\n> Compila le pagine create con l'editor CMS di Total.js e renderizzale con i loro widget.\n\n`CMSCOMPILER(html, widgets, [used])` compila una pagina creata con l'editor di Total.js CMS. I widget nell'HTML sono contrassegnati con `data-cms=\"id__config\"`. Il compilatore rimuove il markup dell'editor, mantiene le parti statiche come stringhe e prepara i widget per il rendering, così una pagina può essere compilata una volta e renderizzata molte volte.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` chiama i widget e costruisce l'HTML. Un widget chiama `next(html, [replace], [cache])`; con `cache` il suo output viene memorizzato nella pagina compilata e riutilizzato. Un layout è una pagina compilata con un elemento `id=\"CMS\"`; passalo come secondo argomento e la pagina viene inserita al suo interno. Le navigazioni (`<script type=\"text/navigation\" name=\"...\">`) e i breadcrumb (`<script type=\"text/breadcrumb\">`) sono template Tangular che leggono `meta.navigation(id)` e `meta.breadcrumb`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JafjVp2e761f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/cms/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"CMS kompilátor","summary":"Skompiluj stránky vytvorené v CMS editore Total.js a vykresli ich s ich widgetmi.","markdown":"---\ntitle: \"CMS kompilátor\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/cms/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# CMS kompilátor\n\n> Skompiluj stránky vytvorené v CMS editore Total.js a vykresli ich s ich widgetmi.\n\n`CMSCOMPILER(html, widgets, [used])` skompiluje stránku vytvorenú v editore Total.js CMS. Widgety v HTML sú označené cez `data-cms=\"id__config\"`. Kompilátor odstráni značky editora, statické časti ponechá ako reťazce a pripraví widgety na renderovanie, takže jednu stránku môžeš skompilovať raz a renderovať mnohokrát.\n\n```js\nvar widgets = [];\n\nwidgets.push({\n\tid: 'contact',\n\tcss: '.contact{padding:20px}',\n\trender: function(opt, next) {\n\t\t// opt.config is the widget configuration from the editor\n\t\tnext('<a href=\"mailto:' + opt.config.email + '\">' + opt.config.email + '</a>');\n\t}\n});\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs().importmeta('<title>Contact</title>');\n\nexports.install = function() {\n\tROUTE('GET /contact/', function() {\n\t\tvar $ = this;\n\t\tpage.render({ url: $.url }, function(err, html) {\n\t\t\t$.html(html);\n\t\t});\n\t});\n};\n```\n\n`render(meta, [layout], [callback])` zavolá widgety a zostaví HTML. Widget zavolá `next(html, [replace], [cache])`; s `cache` sa jeho výstup uloží do skompilovanej stránky a znova sa použije. Layout je skompilovaná stránka s elementom `id=\"CMS\"`; odovzdaj ho ako druhý argument a stránka sa doň vloží. Navigácie (`<script type=\"text/navigation\" name=\"...\">`) a drobčekové navigácie (`<script type=\"text/breadcrumb\">`) sú šablóny Tangular, ktoré čítajú `meta.navigation(id)` a `meta.breadcrumb`.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jafjad47760f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"UI Builder compiler","summary":"Prepare a schema of the UI Builder designer for production with F.uibuildercompiler().","markdown":"---\ntitle: UI Builder compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# UI Builder compiler\n\n> Prepare a schema of the UI Builder designer for production with F.uibuildercompiler().\n\n`F.uibuildercompiler(opt, [callback])` prepares a schema from the UI Builder designer for production. It finds the components used in the schema, resolves their URLs, and with `download: true` embeds their HTML, so the client does not need to download them.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nUse `local: true` when the components are already available on the client; then only the list of used components is returned.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjad47760f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"UI-Builder-Compiler","summary":"Bereite ein Schema aus dem UI-Builder-Designer mit F.uibuildercompiler() für die Produktion vor.","markdown":"---\ntitle: UI-Builder-Compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# UI-Builder-Compiler\n\n> Bereite ein Schema aus dem UI-Builder-Designer mit F.uibuildercompiler() für die Produktion vor.\n\n`F.uibuildercompiler(opt, [callback])` bereitet ein Schema aus dem UI-Builder-Designer für die Produktion vor. Es findet die im Schema verwendeten Komponenten, löst ihre URLs auf und bettet mit `download: true` ihr HTML ein, sodass der Client sie nicht herunterladen muss.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nNutze `local: true`, wenn die Komponenten auf dem Client bereits verfügbar sind; dann wird nur die Liste der verwendeten Komponenten zurückgegeben.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjad47760f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Compilador de UI Builder","summary":"Prepara un esquema del diseñador UI Builder para producción con F.uibuildercompiler().","markdown":"---\ntitle: Compilador de UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Compilador de UI Builder\n\n> Prepara un esquema del diseñador UI Builder para producción con F.uibuildercompiler().\n\n`F.uibuildercompiler(opt, [callback])` prepara un esquema del diseñador UI Builder para producción. Encuentra los componentes usados en el esquema, resuelve sus URL y, con `download: true`, incrusta su HTML, así el cliente no necesita descargarlos.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nUsa `local: true` cuando los componentes ya están disponibles en el cliente; entonces solo se devuelve la lista de componentes usados.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjad47760f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Compilateur UI Builder","summary":"Prépare un schéma du designer UI Builder pour la production avec F.uibuildercompiler().","markdown":"---\ntitle: Compilateur UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Compilateur UI Builder\n\n> Prépare un schéma du designer UI Builder pour la production avec F.uibuildercompiler().\n\n`F.uibuildercompiler(opt, [callback])` prépare pour la production un schéma issu du designer UI Builder. Il trouve les composants utilisés dans le schéma, résout leurs URL et, avec `download: true`, intègre leur HTML ; le client n'a donc pas besoin de les télécharger.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nUtilise `local: true` lorsque les composants sont déjà disponibles côté client ; seule la liste des composants utilisés est alors renvoyée.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjad47760f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Compilatore UI Builder","summary":"Prepara uno schema del designer UI Builder per la produzione con F.uibuildercompiler().","markdown":"---\ntitle: Compilatore UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Compilatore UI Builder\n\n> Prepara uno schema del designer UI Builder per la produzione con F.uibuildercompiler().\n\n`F.uibuildercompiler(opt, [callback])` prepara per la produzione uno schema del designer UI Builder. Trova i componenti usati nello schema, risolve i loro URL e, con `download: true`, ne incorpora l'HTML, così il client non deve scaricarli.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nUsa `local: true` quando i componenti sono già disponibili sul client; in quel caso viene restituito solo l'elenco dei componenti usati.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjad47760f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"UI Builder kompilátor","summary":"Priprav schému z návrhára UI Builder na produkciu pomocou F.uibuildercompiler().","markdown":"---\ntitle: \"UI Builder kompilátor\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/ui-builder-compiler/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# UI Builder kompilátor\n\n> Priprav schému z návrhára UI Builder na produkciu pomocou F.uibuildercompiler().\n\n`F.uibuildercompiler(opt, [callback])` pripraví schému z návrhára UI Builder na produkciu. Nájde komponenty použité v schéme, vyrieši ich URL a s `download: true` vloží ich HTML, takže klient ich nemusí sťahovať.\n\n```js\nexports.install = function() {\n\tROUTE('POST /api/apps/', async function() {\n\t\tvar $ = this;\n\t\tvar app = await F.uibuildercompiler({ schema: $.body.schema, download: true });\n\t\t$.json(app);\n\t});\n};\n```\n\nPouži `local: true`, keď sú komponenty na klientovi už dostupné; potom sa vráti iba zoznam použitých komponentov.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Tangular","summary":"The Tangular template engine: compile and render templates and use its helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> The Tangular template engine: compile and render templates and use its helpers.\n\nTangular is the template engine of Total.js client libraries, and the framework loads it at start as the globals `Tangular` and `Ta`. The CMS compiler uses it for navigation templates, and you can use it for e-mails, small fragments or text files.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Syntax | Meaning |\n| --- | --- |\n| `{{ name }}` | Writes an encoded value of the model |\n| `{{ value \\| helper(args) }}` | Pipes the value through helpers |\n| `{{ $.key }}` | Reads the second argument (repository) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Condition |\n| `{{ foreach m in items }}...{{ end }}` | Loop over an array or the keys of an object, `$index` is the index |\n| `{{ break }}`, `{{ continue }}` | Loop control |\n\nBuilt-in helpers are `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) and `currency`. Register your own with `Tangular.register(name, fn)`, or pass private helpers as the third argument of the compiled function:\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nValues are encoded by default; use `raw` only for HTML you trust.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Tangular","summary":"Die Template-Engine Tangular: Templates kompilieren und rendern und ihre Helfer verwenden.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> Die Template-Engine Tangular: Templates kompilieren und rendern und ihre Helfer verwenden.\n\nTangular ist die Template-Engine der Total.js-Client-Bibliotheken, und das Framework lädt sie beim Start als die Globals `Tangular` und `Ta`. Der CMS-Compiler nutzt sie für Navigations-Templates, und du kannst sie für E-Mails, kleine Fragmente oder Textdateien nutzen.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Syntax | Bedeutung |\n| --- | --- |\n| `{{ name }}` | Schreibt einen kodierten Wert des Modells |\n| `{{ value \\| helper(args) }}` | Leitet den Wert durch Helper |\n| `{{ $.key }}` | Liest das zweite Argument (Repository) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Bedingung |\n| `{{ foreach m in items }}...{{ end }}` | Schleife über ein Array oder die Schlüssel eines Objekts, `$index` ist der Index |\n| `{{ break }}`, `{{ continue }}` | Schleifensteuerung |\n\nEingebaute Helper sind `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) und `currency`. Registriere eigene mit `Tangular.register(name, fn)` oder übergib private Helper als drittes Argument der kompilierten Funktion:\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nWerte werden standardmäßig kodiert; nutze `raw` nur für HTML, dem du vertraust.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Tangular","summary":"El motor de plantillas Tangular: compila y renderiza plantillas y usa sus helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> El motor de plantillas Tangular: compila y renderiza plantillas y usa sus helpers.\n\nTangular es el motor de plantillas de las librerías de cliente de Total.js, y el framework lo carga al arrancar como las globales `Tangular` y `Ta`. El compilador de CMS lo usa para las plantillas de navegación, y tú puedes usarlo para e-mails, fragmentos pequeños o archivos de texto.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Sintaxis | Significado |\n| --- | --- |\n| `{{ name }}` | Escribe un valor codificado del modelo |\n| `{{ value \\| helper(args) }}` | Pasa el valor por helpers |\n| `{{ $.key }}` | Lee el segundo argumento (repositorio) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Condición |\n| `{{ foreach m in items }}...{{ end }}` | Bucle sobre un array o las claves de un objeto, `$index` es el índice |\n| `{{ break }}`, `{{ continue }}` | Control del bucle |\n\nLos helpers integrados son `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) y `currency`. Registra los tuyos con `Tangular.register(name, fn)`, o pasa helpers privados como tercer argumento de la función compilada:\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nLos valores se codifican por defecto; usa `raw` solo para HTML de confianza.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Tangular","summary":"Le moteur de templates Tangular : compile et rends des templates et utilise ses helpers.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> Le moteur de templates Tangular : compile et rends des templates et utilise ses helpers.\n\nTangular est le moteur de templates des bibliothèques client de Total.js, et le framework le charge au démarrage sous les variables globales `Tangular` et `Ta`. Le compilateur CMS l'utilise pour les templates de navigation, et tu peux l'utiliser pour des e-mails, de petits fragments ou des fichiers texte.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Syntaxe | Signification |\n| --- | --- |\n| `{{ name }}` | Écrit une valeur encodée du modèle |\n| `{{ value \\| helper(args) }}` | Fait passer la valeur par des helpers |\n| `{{ $.key }}` | Lit le deuxième argument (repository) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Condition |\n| `{{ foreach m in items }}...{{ end }}` | Boucle sur un tableau ou sur les clés d'un objet, `$index` est l'index |\n| `{{ break }}`, `{{ continue }}` | Contrôle de boucle |\n\nLes helpers intégrés sont `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) et `currency`. Enregistre les tiens avec `Tangular.register(name, fn)`, ou passe des helpers privés comme troisième argument de la fonction compilée :\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nLes valeurs sont encodées par défaut ; utilise `raw` uniquement pour du HTML de confiance.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Tangular","summary":"Il motore di template Tangular: compila e renderizza i template e usa i suoi helper.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> Il motore di template Tangular: compila e renderizza i template e usa i suoi helper.\n\nTangular è il motore di template delle librerie client di Total.js, e il framework lo carica all'avvio come variabili globali `Tangular` e `Ta`. Il compilatore CMS lo usa per i template di navigazione, e tu puoi usarlo per e-mail, piccoli frammenti o file di testo.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Sintassi | Significato |\n| --- | --- |\n| `{{ name }}` | Scrive un valore codificato del modello |\n| `{{ value \\| helper(args) }}` | Passa il valore attraverso degli helper |\n| `{{ $.key }}` | Legge il secondo argomento (repository) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Condizione |\n| `{{ foreach m in items }}...{{ end }}` | Ciclo su un array o sulle chiavi di un oggetto, `$index` è l'indice |\n| `{{ break }}`, `{{ continue }}` | Controllo del ciclo |\n\nGli helper integrati sono `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) e `currency`. Registra i tuoi con `Tangular.register(name, fn)`, oppure passa helper privati come terzo argomento della funzione compilata:\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nI valori vengono codificati per impostazione predefinita; usa `raw` solo per HTML di cui ti fidi.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjei2Lg60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/tangular/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Tangular","summary":"Šablónovací engine Tangular: kompiluj a vykresľuj šablóny a používaj jeho helpery.","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/tangular/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Tangular\n\n> Šablónovací engine Tangular: kompiluj a vykresľuj šablóny a používaj jeho helpery.\n\nTangular je šablónovací engine klientskych knižníc Total.js a framework ho pri štarte načíta ako globálne `Tangular` a `Ta`. CMS kompilátor ho používa pre šablóny navigácie a ty ho môžeš použiť pre e-maily, malé fragmenty alebo textové súbory.\n\n```js\nvar template = Tangular.compile('<h2>{{ title }}</h2>{{ if items.length }}<ul>{{ foreach m in items }}<li>{{ $index + 1 }}. {{ m.name }} - {{ m.price | format(2) }}</li>{{ end }}</ul>{{ else }}<p>Empty</p>{{ fi }}');\n\nvar html = template({ title: 'Products', items: [{ name: 'Mug', price: 9.5 }] });\n```\n\n| Syntax | Význam |\n| --- | --- |\n| `{{ name }}` | Vypíše zakódovanú hodnotu z modelu |\n| `{{ value \\| helper(args) }}` | Pošle hodnotu cez pomocné funkcie |\n| `{{ $.key }}` | Načíta druhý argument (repository) |\n| `{{ if cond }}...{{ else if cond }}...{{ else }}...{{ fi }}` | Podmienka |\n| `{{ foreach m in items }}...{{ end }}` | Cyklus cez pole alebo kľúče objektu, `$index` je index |\n| `{{ break }}`, `{{ continue }}` | Riadenie cyklu |\n\nVstavané pomocné funkcie sú `encode`, `raw`, `format`, `pluralize`, `empty` (`def`) a `currency`. Vlastné zaregistruješ cez `Tangular.register(name, fn)` alebo odovzdáš súkromné pomocné funkcie ako tretí argument skompilovanej funkcie:\n\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nvar fn = Tangular.compile('{{ name | upper }} {{ name | stars }}');\nfn({ name: 'peter' }, null, { stars: function(value) { return '*' + value + '*'; } });\n```\n\nHodnoty sa predvolene zakódujú; `raw` používaj iba pre HTML, ktorému dôveruješ.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"en","title":"Command line (total4)","summary":"The total4 command-line tool: creating projects, serving a folder, bundles, minifying and localization resources.","markdown":"---\ntitle: Command line (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Command line (total4)\n\n> The total4 command-line tool: creating projects, serving a folder, bundles, minifying and localization resources.\n\nThe `total4` package installs a small command-line tool, also called `total4`. It lists the official project templates, serves a folder over HTTP, makes and extracts bundles and packages, minifies files and works with localization resources.\n\n## Installation\n\nThe tool is the `bin` entry of the `total4` package. Install the package globally to get the command everywhere:\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nEvery run prints a header box with the Total.js version first, then the result of the command. Without a command the tool prints `Use \"total4 help\" to list all commands.`; an unknown command prints an error with the same advice.\n\n## Writing commands\n\nA command is the first argument. Each command accepts three spellings: `bundle`, `-bundle` and `--bundle` are the same (the tool removes one leading dash from `--name`). Some commands also have a short alias:\n\n| Command | Aliases |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (and their `--` forms) |\n| `edit` | `-e` |\n\nPaths are resolved from the current directory, and every output file is written there or next to the input file.\n\n## Serving a folder\n\nA number as the first argument starts a static web server for the current directory:\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nThe server runs in debug mode on all interfaces (`0.0.0.0`) and the given port. A request for a directory returns its `index.html`; when there is none, the server renders a simple directory listing with links to subdirectories and files and their sizes. Files are sent as they are: HTML, scripts and styles are not compiled, and `.less` files are served as `text/less`. The temporary files of the server go to the temporary directory of the system, so the folder stays clean. Stop the server with `Ctrl+C`.\n\n## Templates\n\n`total4 templates` downloads the list of official project templates and prints the name and description of each one:\n\n```bash\ntotal4 templates\n```\n\n## Bundles and packages\n\nA bundle is one `.bundle` file with a whole application or a part of it. The framework extracts bundles from `/bundles/` when the application starts; [Application structure](../../guides/application-structure/) explains how bundles are merged. Make a bundle from the current directory:\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nThe tool prints the directory, the file name and then the number of files and the size. The default name is `app.bundle`; give your own name with the `.bundle` extension. These paths are never included: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (and their `.json` and `.pid` files), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` and the bundle file itself.\n\n`total4 package <filename>` makes a `.package` file in the same way (default `noname.package`; give your own name with the `.package` extension). Its list of excluded paths is shorter: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` and `/.git/`. Copy the result to `/packages/` of an application.\n\n`total4 extract <filename>` writes all files of a bundle or a package into the current directory:\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nExisting files with the same path are overwritten, so extract into an empty directory.\n\n## Minifying files\n\n`total4 minify <filename>` minifies one `.js`, `.css` or `.html` file with the framework's own minifiers and writes `<name>.min.<extension>` next to it:\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nThe file name is always the last argument. Files with other extensions are not written.\n\n## Localization\n\nThe translation commands produce resource files for the framework's localization, see [Localization](../../guides/localization/). A resource line is `key : text`; the keys of texts from views are `T` followed by a hash of the text in base 36.\n\n`total4 translate`, run in the root of the application, reads every `.html` and `.js` file (and every file with `sitemap` in its path) of the current directory and all its subdirectories. It collects:\n\n- every `@(text)` marker; texts that start with `#` followed by a non-space character are skipped,\n- in `.js` files, error keys used as `$.invalid('key')`, `.error('key')` and `.err('key')`; their key is the text itself.\n\nThe result is `translate.resource` in the current directory, grouped by a `// filename` comment:\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nCopy it to `/resources/` under the name of a language, for example `sk.resource`, and translate the texts.\n\n`total4 translate \"Text\"` prints the resource line for one text, so you can add it to a resource by hand. When the argument is an existing file, `total4 translate <filename>` creates `translate.resource` with one key for each non-empty line of that file.\n\n## CSV for translators\n\n`total4 translatecsv` reads the same files as `translate` (only `@(text)` markers) and writes `translate.csv` with the columns `Hash;Text;Translation`.\n\n## Maintaining resources\n\n| Command | Output | What it does |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Lists keys of `source` missing in `target` (\"Add\") and keys of `target` missing in `source` (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Copies `target` and replaces each text with the text from `source` when `source` has the key |\n| `clean <source>` | `<source>-cleaned.txt` | Aligns all keys to one column and keeps comments and empty lines |\n| `translate4 <source>` | `<source>` with `-new` before the first dot | Converts old numeric keys (`T123`, `T-123`) to the base-36 keys of Total.js 4 |\n\nThe output file names drop the `.resource` extension: `total4 diff default.resource sk.resource` writes `sk-diff.txt`. `translate4` inserts `-new` before the first dot of the argument: `total4 translate4 sk.resource` writes `sk-new.resource`.\n\nA typical update of a translation after new texts appear in the views:\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` connects the current directory to a project in the Total.js Code Editor over WebSocket. The URL is the address of the project, for example `https://code.example.com/?id=myproject`; `http` is changed to `ws` automatically. The editor can then browse, read, create, save, rename, upload and remove the files of the directory and read its logs. The tool prints the directory and a welcome line with the name of the project, reconnects every 10 seconds, prints `404 project not found` while the project does not exist and stops with `409 project is already open` when another client has the project open.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"de","title":"Kommandozeile (total4)","summary":"Das Kommandozeilenwerkzeug total4: Projekte erstellen, einen Ordner bereitstellen, Bundles, Minifizieren und Lokalisierungsressourcen.","markdown":"---\ntitle: Kommandozeile (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Kommandozeile (total4)\n\n> Das Kommandozeilenwerkzeug total4: Projekte erstellen, einen Ordner bereitstellen, Bundles, Minifizieren und Lokalisierungsressourcen.\n\nDas Paket `total4` installiert ein kleines Kommandozeilenwerkzeug, das ebenfalls `total4` heißt. Es listet die offiziellen Projektvorlagen auf, stellt einen Ordner über HTTP bereit, erstellt und entpackt Bundles und Pakete, minifiziert Dateien und arbeitet mit Lokalisierungsressourcen.\n\n## Installation\n\nDas Werkzeug ist der `bin`-Eintrag des Pakets `total4`. Installiere das Paket global, um den Befehl überall zu haben:\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nJeder Aufruf gibt zuerst einen Kopfkasten mit der Total.js-Version aus, dann das Ergebnis des Befehls. Ohne Befehl gibt das Werkzeug `Use \"total4 help\" to list all commands.` aus; ein unbekannter Befehl gibt einen Fehler mit demselben Hinweis aus.\n\n## Befehle schreiben\n\nEin Befehl ist das erste Argument. Jeder Befehl akzeptiert drei Schreibweisen: `bundle`, `-bundle` und `--bundle` sind gleich (das Werkzeug entfernt einen führenden Bindestrich von `--name`). Manche Befehle haben auch einen kurzen Alias:\n\n| Befehl | Aliase |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (und ihre `--`-Formen) |\n| `edit` | `-e` |\n\nPfade werden vom aktuellen Verzeichnis aus aufgelöst, und jede Ausgabedatei wird dort oder neben die Eingabedatei geschrieben.\n\n## Einen Ordner bereitstellen\n\nEine Zahl als erstes Argument startet einen statischen Webserver für das aktuelle Verzeichnis:\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nDer Server läuft im Debug-Modus auf allen Schnittstellen (`0.0.0.0`) und dem angegebenen Port. Ein Request auf ein Verzeichnis gibt dessen `index.html` zurück; gibt es keine, rendert der Server eine einfache Verzeichnisliste mit Links zu Unterverzeichnissen und Dateien und deren Größen. Dateien werden so gesendet, wie sie sind: HTML, Skripte und Styles werden nicht kompiliert, und `.less`-Dateien werden als `text/less` ausgeliefert. Die temporären Dateien des Servers landen im temporären Verzeichnis des Systems, sodass der Ordner sauber bleibt. Halte den Server mit `Ctrl+C` an.\n\n## Vorlagen\n\n`total4 templates` lädt die Liste der offiziellen Projektvorlagen herunter und gibt Name und Beschreibung jeder Vorlage aus:\n\n```bash\ntotal4 templates\n```\n\n## Bundles und Pakete\n\nEin Bundle ist eine einzelne `.bundle`-Datei mit einer ganzen Anwendung oder einem Teil davon. Das Framework entpackt Bundles aus `/bundles/`, wenn die Anwendung startet; [Anwendungsstruktur](../../guides/application-structure/) erklärt, wie Bundles zusammengeführt werden. Erstelle ein Bundle aus dem aktuellen Verzeichnis:\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nDas Werkzeug gibt das Verzeichnis, den Dateinamen und dann die Anzahl der Dateien und die Größe aus. Der Standardname ist `app.bundle`; gib deinen eigenen Namen mit der Endung `.bundle` an. Diese Pfade werden nie aufgenommen: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (und ihre `.json`- und `.pid`-Dateien), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` und die Bundle-Datei selbst.\n\n`total4 package <filename>` erstellt auf dieselbe Weise eine `.package`-Datei (Standard `noname.package`; gib deinen eigenen Namen mit der Endung `.package` an). Ihre Liste ausgeschlossener Pfade ist kürzer: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` und `/.git/`. Kopiere das Ergebnis nach `/packages/` einer Anwendung.\n\n`total4 extract <filename>` schreibt alle Dateien eines Bundles oder Pakets in das aktuelle Verzeichnis:\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nVorhandene Dateien mit demselben Pfad werden überschrieben, also entpacke in ein leeres Verzeichnis.\n\n## Dateien minifizieren\n\n`total4 minify <filename>` minifiziert eine `.js`-, `.css`- oder `.html`-Datei mit den eigenen Minifiern des Frameworks und schreibt `<name>.min.<extension>` daneben:\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nDer Dateiname ist immer das letzte Argument. Dateien mit anderen Endungen werden nicht geschrieben.\n\n## Lokalisierung\n\nDie Übersetzungsbefehle erzeugen Ressourcendateien für die Lokalisierung des Frameworks, siehe [Lokalisierung](../../guides/localization/). Eine Ressourcenzeile ist `key : text`; die Schlüssel von Texten aus Views sind `T`, gefolgt von einem Hash des Textes in Basis 36.\n\n`total4 translate`, im Wurzelverzeichnis der Anwendung ausgeführt, liest jede `.html`- und `.js`-Datei (und jede Datei mit `sitemap` im Pfad) des aktuellen Verzeichnisses und aller seiner Unterverzeichnisse. Es sammelt:\n\n- jede `@(text)`-Markierung; Texte, die mit `#` gefolgt von einem Nicht-Leerzeichen beginnen, werden übersprungen,\n- in `.js`-Dateien Fehlerschlüssel, die als `$.invalid('key')`, `.error('key')` und `.err('key')` verwendet werden; ihr Schlüssel ist der Text selbst.\n\nDas Ergebnis ist `translate.resource` im aktuellen Verzeichnis, gruppiert nach einem `// filename`-Kommentar:\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nKopiere es unter dem Namen einer Sprache nach `/resources/`, zum Beispiel `sk.resource`, und übersetze die Texte.\n\n`total4 translate \"Text\"` gibt die Ressourcenzeile für einen Text aus, sodass du sie von Hand zu einer Ressource hinzufügen kannst. Ist das Argument eine vorhandene Datei, erstellt `total4 translate <filename>` eine `translate.resource` mit einem Schlüssel für jede nicht leere Zeile dieser Datei.\n\n## CSV für Übersetzer\n\n`total4 translatecsv` liest dieselben Dateien wie `translate` (nur `@(text)`-Markierungen) und schreibt `translate.csv` mit den Spalten `Hash;Text;Translation`.\n\n## Ressourcen pflegen\n\n| Befehl | Ausgabe | Was er tut |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Listet Schlüssel von `source` auf, die in `target` fehlen (\"Add\"), und Schlüssel von `target`, die in `source` fehlen (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Kopiert `target` und ersetzt jeden Text durch den Text aus `source`, wenn `source` den Schlüssel hat |\n| `clean <source>` | `<source>-cleaned.txt` | Richtet alle Schlüssel an einer Spalte aus und behält Kommentare und leere Zeilen |\n| `translate4 <source>` | `<source>` mit `-new` vor dem ersten Punkt | Wandelt alte numerische Schlüssel (`T123`, `T-123`) in die Basis-36-Schlüssel von Total.js 4 um |\n\nDie Namen der Ausgabedateien lassen die Endung `.resource` weg: `total4 diff default.resource sk.resource` schreibt `sk-diff.txt`. `translate4` fügt `-new` vor dem ersten Punkt des Arguments ein: `total4 translate4 sk.resource` schreibt `sk-new.resource`.\n\nEine typische Aktualisierung einer Übersetzung, nachdem neue Texte in den Views auftauchen:\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` verbindet das aktuelle Verzeichnis über WebSocket mit einem Projekt im Total.js Code Editor. Die URL ist die Adresse des Projekts, zum Beispiel `https://code.example.com/?id=myproject`; `http` wird automatisch zu `ws` geändert. Der Editor kann dann die Dateien des Verzeichnisses durchsuchen, lesen, erstellen, speichern, umbenennen, hochladen und entfernen sowie seine Logs lesen. Das Werkzeug gibt das Verzeichnis und eine Begrüßungszeile mit dem Namen des Projekts aus, verbindet sich alle 10 Sekunden neu, gibt `404 project not found` aus, solange das Projekt nicht existiert, und hält mit `409 project is already open` an, wenn ein anderer Client das Projekt geöffnet hat.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"es","title":"Línea de comandos (total4)","summary":"La herramienta de línea de comandos total4: crear proyectos, servir una carpeta, bundles, minificar y recursos de localización.","markdown":"---\ntitle: \"Línea de comandos (total4)\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Línea de comandos (total4)\n\n> La herramienta de línea de comandos total4: crear proyectos, servir una carpeta, bundles, minificar y recursos de localización.\n\nEl paquete `total4` instala una pequeña herramienta de línea de comandos, también llamada `total4`. Lista las plantillas oficiales de proyecto, sirve una carpeta por HTTP, crea y extrae bundles y paquetes, minifica archivos y trabaja con recursos de localización.\n\n## Instalación\n\nLa herramienta es la entrada `bin` del paquete `total4`. Instala el paquete de forma global para tener el comando en todas partes:\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nCada ejecución imprime primero un recuadro de cabecera con la versión de Total.js y después el resultado del comando. Sin comando, la herramienta imprime `Use \"total4 help\" to list all commands.`; un comando desconocido imprime un error con el mismo consejo.\n\n## Escribir comandos\n\nUn comando es el primer argumento. Cada comando acepta tres formas: `bundle`, `-bundle` y `--bundle` son lo mismo (la herramienta quita un guion inicial de `--name`). Algunos comandos también tienen un alias corto:\n\n| Comando | Alias |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (y sus formas con `--`) |\n| `edit` | `-e` |\n\nLas rutas se resuelven desde el directorio actual, y cada archivo de salida se escribe ahí o junto al archivo de entrada.\n\n## Servir una carpeta\n\nUn número como primer argumento inicia un servidor web estático para el directorio actual:\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nEl servidor se ejecuta en modo debug en todas las interfaces (`0.0.0.0`) y en el puerto indicado. Una petición a un directorio devuelve su `index.html`; si no lo hay, el servidor renderiza un listado sencillo del directorio con enlaces a los subdirectorios y archivos y sus tamaños. Los archivos se envían tal cual: el HTML, los scripts y los estilos no se compilan, y los archivos `.less` se sirven como `text/less`. Los archivos temporales del servidor van al directorio temporal del sistema, así que la carpeta queda limpia. Detén el servidor con `Ctrl+C`.\n\n## Plantillas\n\n`total4 templates` descarga la lista de plantillas oficiales de proyecto e imprime el nombre y la descripción de cada una:\n\n```bash\ntotal4 templates\n```\n\n## Bundles y paquetes\n\nUn bundle es un archivo `.bundle` con una aplicación completa o una parte de ella. El framework extrae los bundles de `/bundles/` cuando se inicia la aplicación; [Estructura de la aplicación](../../guides/application-structure/) explica cómo se fusionan los bundles. Crea un bundle a partir del directorio actual:\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nLa herramienta imprime el directorio, el nombre del archivo y después el número de archivos y el tamaño. El nombre por defecto es `app.bundle`; da tu propio nombre con la extensión `.bundle`. Estas rutas nunca se incluyen: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (y sus archivos `.json` y `.pid`), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` y el propio archivo del bundle.\n\n`total4 package <filename>` crea un archivo `.package` de la misma forma (por defecto `noname.package`; da tu propio nombre con la extensión `.package`). Su lista de rutas excluidas es más corta: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` y `/.git/`. Copia el resultado en `/packages/` de una aplicación.\n\n`total4 extract <filename>` escribe todos los archivos de un bundle o de un paquete en el directorio actual:\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nLos archivos existentes con la misma ruta se sobrescriben, así que extrae en un directorio vacío.\n\n## Minificar archivos\n\n`total4 minify <filename>` minifica un archivo `.js`, `.css` o `.html` con los minificadores propios del framework y escribe `<name>.min.<extension>` a su lado:\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nEl nombre del archivo es siempre el último argumento. Los archivos con otras extensiones no se escriben.\n\n## Localización\n\nLos comandos de traducción generan archivos de recursos para la localización del framework; consulta [Localización](../../guides/localization/). Una línea de recurso es `key : text`; las claves de los textos de las vistas son `T` seguida de un hash del texto en base 36.\n\n`total4 translate`, ejecutado en la raíz de la aplicación, lee cada archivo `.html` y `.js` (y cada archivo con `sitemap` en su ruta) del directorio actual y de todos sus subdirectorios. Recoge:\n\n- cada marcador `@(text)`; se omiten los textos que empiezan por `#` seguido de un carácter que no es un espacio,\n- en los archivos `.js`, las claves de error usadas como `$.invalid('key')`, `.error('key')` y `.err('key')`; su clave es el propio texto.\n\nEl resultado es `translate.resource` en el directorio actual, agrupado por un comentario `// filename`:\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nCópialo en `/resources/` con el nombre de un idioma, por ejemplo `sk.resource`, y traduce los textos.\n\n`total4 translate \"Text\"` imprime la línea de recurso de un texto, para que puedas añadirla a mano a un recurso. Cuando el argumento es un archivo existente, `total4 translate <filename>` crea `translate.resource` con una clave por cada línea no vacía de ese archivo.\n\n## CSV para traductores\n\n`total4 translatecsv` lee los mismos archivos que `translate` (solo los marcadores `@(text)`) y escribe `translate.csv` con las columnas `Hash;Text;Translation`.\n\n## Mantener los recursos\n\n| Comando | Salida | Qué hace |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Lista las claves de `source` que faltan en `target` (\"Add\") y las claves de `target` que faltan en `source` (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Copia `target` y sustituye cada texto por el texto de `source` cuando `source` tiene la clave |\n| `clean <source>` | `<source>-cleaned.txt` | Alinea todas las claves en una columna y conserva los comentarios y las líneas vacías |\n| `translate4 <source>` | `<source>` con `-new` antes del primer punto | Convierte las claves numéricas antiguas (`T123`, `T-123`) en las claves en base 36 de Total.js 4 |\n\nLos nombres de los archivos de salida pierden la extensión `.resource`: `total4 diff default.resource sk.resource` escribe `sk-diff.txt`. `translate4` inserta `-new` antes del primer punto del argumento: `total4 translate4 sk.resource` escribe `sk-new.resource`.\n\nUna actualización típica de una traducción después de que aparezcan textos nuevos en las vistas:\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` conecta el directorio actual con un proyecto de Total.js Code Editor mediante WebSocket. La URL es la dirección del proyecto, por ejemplo `https://code.example.com/?id=myproject`; `http` se cambia a `ws` automáticamente. El editor puede entonces explorar, leer, crear, guardar, renombrar, subir y eliminar los archivos del directorio y leer sus logs. La herramienta imprime el directorio y una línea de bienvenida con el nombre del proyecto, se reconecta cada 10 segundos, imprime `404 project not found` mientras el proyecto no existe y se detiene con `409 project is already open` cuando otro cliente tiene el proyecto abierto.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"fr","title":"Ligne de commande (total4)","summary":"L'outil en ligne de commande total4 : créer des projets, servir un dossier, les bundles, la minification et les ressources de localisation.","markdown":"---\ntitle: Ligne de commande (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Ligne de commande (total4)\n\n> L'outil en ligne de commande total4 : créer des projets, servir un dossier, les bundles, la minification et les ressources de localisation.\n\nLe paquet `total4` installe un petit outil en ligne de commande, également appelé `total4`. Il liste les templates de projet officiels, sert un dossier en HTTP, crée et extrait des bundles et des paquets, minifie des fichiers et travaille avec les ressources de localisation.\n\n## Installation\n\nL'outil est l'entrée `bin` du paquet `total4`. Installe le paquet globalement pour disposer de la commande partout :\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nChaque exécution affiche d'abord un encadré d'en-tête avec la version de Total.js, puis le résultat de la commande. Sans commande, l'outil affiche `Use \"total4 help\" to list all commands.` ; une commande inconnue affiche une erreur avec le même conseil.\n\n## Écrire les commandes\n\nUne commande est le premier argument. Chaque commande accepte trois graphies : `bundle`, `-bundle` et `--bundle` sont identiques (l'outil retire un tiret initial de `--name`). Certaines commandes ont aussi un alias court :\n\n| Commande | Alias |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (et leurs formes `--`) |\n| `edit` | `-e` |\n\nLes chemins sont résolus depuis le répertoire courant, et chaque fichier de sortie est écrit à cet endroit ou à côté du fichier d'entrée.\n\n## Servir un dossier\n\nUn nombre comme premier argument démarre un serveur web statique pour le répertoire courant :\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nLe serveur s'exécute en mode debug sur toutes les interfaces (`0.0.0.0`) et sur le port indiqué. Une requête vers un répertoire renvoie son `index.html` ; s'il n'y en a pas, le serveur génère un simple listing du répertoire avec des liens vers les sous-répertoires et les fichiers, et leurs tailles. Les fichiers sont envoyés tels quels : le HTML, les scripts et les styles ne sont pas compilés, et les fichiers `.less` sont servis en `text/less`. Les fichiers temporaires du serveur vont dans le répertoire temporaire du système, le dossier reste donc propre. Arrête le serveur avec `Ctrl+C`.\n\n## Templates\n\n`total4 templates` télécharge la liste des templates de projet officiels et affiche le nom et la description de chacun :\n\n```bash\ntotal4 templates\n```\n\n## Bundles et paquets\n\nUn bundle est un fichier `.bundle` unique contenant une application entière ou une partie de celle-ci. Le framework extrait les bundles de `/bundles/` au démarrage de l'application ; [Structure de l'application](../../guides/application-structure/) explique comment les bundles sont fusionnés. Crée un bundle à partir du répertoire courant :\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nL'outil affiche le répertoire, le nom du fichier, puis le nombre de fichiers et la taille. Le nom par défaut est `app.bundle` ; donne ton propre nom avec l'extension `.bundle`. Ces chemins ne sont jamais inclus : `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (et leurs fichiers `.json` et `.pid`), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` et le fichier bundle lui-même.\n\n`total4 package <filename>` crée un fichier `.package` de la même manière (par défaut `noname.package` ; donne ton propre nom avec l'extension `.package`). Sa liste de chemins exclus est plus courte : `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` et `/.git/`. Copie le résultat dans `/packages/` d'une application.\n\n`total4 extract <filename>` écrit tous les fichiers d'un bundle ou d'un paquet dans le répertoire courant :\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nLes fichiers existants ayant le même chemin sont écrasés, extrais donc dans un répertoire vide.\n\n## Minifier des fichiers\n\n`total4 minify <filename>` minifie un fichier `.js`, `.css` ou `.html` avec les minificateurs du framework et écrit `<name>.min.<extension>` à côté :\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nLe nom du fichier est toujours le dernier argument. Les fichiers ayant d'autres extensions ne sont pas écrits.\n\n## Localisation\n\nLes commandes de traduction produisent des fichiers de ressources pour la localisation du framework, voir [Localisation](../../guides/localization/). Une ligne de ressource est `key : text` ; les clés des textes issus des vues sont `T` suivi d'un hash du texte en base 36.\n\n`total4 translate`, exécutée à la racine de l'application, lit chaque fichier `.html` et `.js` (et chaque fichier dont le chemin contient `sitemap`) du répertoire courant et de tous ses sous-répertoires. Elle collecte :\n\n- chaque marqueur `@(text)` ; les textes qui commencent par `#` suivi d'un caractère autre qu'un espace sont ignorés,\n- dans les fichiers `.js`, les clés d'erreur utilisées sous la forme `$.invalid('key')`, `.error('key')` et `.err('key')` ; leur clé est le texte lui-même.\n\nLe résultat est `translate.resource` dans le répertoire courant, regroupé par un commentaire `// filename` :\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nCopie-le dans `/resources/` sous le nom d'une langue, par exemple `sk.resource`, et traduis les textes.\n\n`total4 translate \"Text\"` affiche la ligne de ressource pour un seul texte, pour que tu puisses l'ajouter à la main à une ressource. Lorsque l'argument est un fichier existant, `total4 translate <filename>` crée `translate.resource` avec une clé pour chaque ligne non vide de ce fichier.\n\n## CSV pour les traducteurs\n\n`total4 translatecsv` lit les mêmes fichiers que `translate` (uniquement les marqueurs `@(text)`) et écrit `translate.csv` avec les colonnes `Hash;Text;Translation`.\n\n## Maintenir les ressources\n\n| Commande | Sortie | Ce qu'elle fait |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Liste les clés de `source` absentes de `target` (\"Add\") et les clés de `target` absentes de `source` (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Copie `target` et remplace chaque texte par celui de `source` lorsque `source` possède la clé |\n| `clean <source>` | `<source>-cleaned.txt` | Aligne toutes les clés sur une colonne et conserve les commentaires et les lignes vides |\n| `translate4 <source>` | `<source>` avec `-new` avant le premier point | Convertit les anciennes clés numériques (`T123`, `T-123`) en clés base 36 de Total.js 4 |\n\nLes noms des fichiers de sortie perdent l'extension `.resource` : `total4 diff default.resource sk.resource` écrit `sk-diff.txt`. `translate4` insère `-new` avant le premier point de l'argument : `total4 translate4 sk.resource` écrit `sk-new.resource`.\n\nUne mise à jour typique d'une traduction après l'apparition de nouveaux textes dans les vues :\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` connecte le répertoire courant à un projet du Total.js Code Editor via WebSocket. L'URL est l'adresse du projet, par exemple `https://code.example.com/?id=myproject` ; `http` est automatiquement remplacé par `ws`. L'éditeur peut alors parcourir, lire, créer, enregistrer, renommer, téléverser et supprimer les fichiers du répertoire et lire ses logs. L'outil affiche le répertoire et une ligne de bienvenue avec le nom du projet, se reconnecte toutes les 10 secondes, affiche `404 project not found` tant que le projet n'existe pas et s'arrête avec `409 project is already open` lorsqu'un autre client a ouvert le projet.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"it","title":"Riga di comando (total4)","summary":"Lo strumento da riga di comando total4: creare progetti, servire una cartella, bundle, minificazione e risorse di localizzazione.","markdown":"---\ntitle: Riga di comando (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Riga di comando (total4)\n\n> Lo strumento da riga di comando total4: creare progetti, servire una cartella, bundle, minificazione e risorse di localizzazione.\n\nIl pacchetto `total4` installa un piccolo strumento da riga di comando, chiamato anch'esso `total4`. Elenca i template di progetto ufficiali, serve una cartella via HTTP, crea ed estrae bundle e pacchetti, minifica file e lavora con le risorse di localizzazione.\n\n## Installazione\n\nLo strumento è la voce `bin` del pacchetto `total4`. Installa il pacchetto globalmente per avere il comando ovunque:\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nOgni esecuzione stampa prima un riquadro di intestazione con la versione di Total.js, poi il risultato del comando. Senza un comando lo strumento stampa `Use \"total4 help\" to list all commands.`; un comando sconosciuto stampa un errore con lo stesso suggerimento.\n\n## Scrivere i comandi\n\nUn comando è il primo argomento. Ogni comando accetta tre grafie: `bundle`, `-bundle` e `--bundle` sono la stessa cosa (lo strumento rimuove un trattino iniziale da `--name`). Alcuni comandi hanno anche un alias breve:\n\n| Comando | Alias |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (e le loro forme con `--`) |\n| `edit` | `-e` |\n\nI percorsi vengono risolti a partire dalla directory corrente, e ogni file di output viene scritto lì o accanto al file di input.\n\n## Servire una cartella\n\nUn numero come primo argomento avvia un server web statico per la directory corrente:\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nIl server gira in modalità debug su tutte le interfacce (`0.0.0.0`) e sulla porta indicata. Una richiesta per una directory restituisce il suo `index.html`; quando non c'è, il server genera un semplice elenco della directory con i link alle sottodirectory e ai file e le loro dimensioni. I file vengono inviati così come sono: HTML, script e stili non vengono compilati, e i file `.less` vengono serviti come `text/less`. I file temporanei del server finiscono nella directory temporanea del sistema, così la cartella resta pulita. Ferma il server con `Ctrl+C`.\n\n## Template\n\n`total4 templates` scarica l'elenco dei template di progetto ufficiali e stampa il nome e la descrizione di ciascuno:\n\n```bash\ntotal4 templates\n```\n\n## Bundle e pacchetti\n\nUn bundle è un unico file `.bundle` con un'intera applicazione o una sua parte. Il framework estrae i bundle da `/bundles/` all'avvio dell'applicazione; [Struttura dell'applicazione](../../guides/application-structure/) spiega come vengono uniti i bundle. Crea un bundle dalla directory corrente:\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nLo strumento stampa la directory, il nome del file e poi il numero di file e la dimensione. Il nome predefinito è `app.bundle`; indica un tuo nome con l'estensione `.bundle`. Questi percorsi non vengono mai inclusi: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (e i loro file `.json` e `.pid`), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` e il file del bundle stesso.\n\n`total4 package <filename>` crea un file `.package` allo stesso modo (predefinito `noname.package`; indica un tuo nome con l'estensione `.package`). Il suo elenco di percorsi esclusi è più breve: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` e `/.git/`. Copia il risultato in `/packages/` di un'applicazione.\n\n`total4 extract <filename>` scrive tutti i file di un bundle o di un pacchetto nella directory corrente:\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nI file esistenti con lo stesso percorso vengono sovrascritti, quindi estrai in una directory vuota.\n\n## Minificare i file\n\n`total4 minify <filename>` minifica un file `.js`, `.css` o `.html` con i minificatori propri del framework e scrive `<name>.min.<extension>` accanto ad esso:\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nIl nome del file è sempre l'ultimo argomento. I file con altre estensioni non vengono scritti.\n\n## Localizzazione\n\nI comandi di traduzione producono file di risorse per la localizzazione del framework, vedi [Localizzazione](../../guides/localization/). Una riga di risorsa è `key : text`; le chiavi dei testi delle viste sono `T` seguito da un hash del testo in base 36.\n\n`total4 translate`, eseguito nella radice dell'applicazione, legge ogni file `.html` e `.js` (e ogni file con `sitemap` nel percorso) della directory corrente e di tutte le sue sottodirectory. Raccoglie:\n\n- ogni marcatore `@(text)`; i testi che iniziano con `#` seguito da un carattere diverso da uno spazio vengono saltati,\n- nei file `.js`, le chiavi di errore usate come `$.invalid('key')`, `.error('key')` e `.err('key')`; la loro chiave è il testo stesso.\n\nIl risultato è `translate.resource` nella directory corrente, raggruppato da un commento `// filename`:\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nCopialo in `/resources/` con il nome di una lingua, per esempio `sk.resource`, e traduci i testi.\n\n`total4 translate \"Text\"` stampa la riga di risorsa per un singolo testo, così puoi aggiungerla a mano a una risorsa. Quando l'argomento è un file esistente, `total4 translate <filename>` crea `translate.resource` con una chiave per ogni riga non vuota di quel file.\n\n## CSV per i traduttori\n\n`total4 translatecsv` legge gli stessi file di `translate` (solo i marcatori `@(text)`) e scrive `translate.csv` con le colonne `Hash;Text;Translation`.\n\n## Gestire le risorse\n\n| Comando | Output | Cosa fa |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Elenca le chiavi di `source` mancanti in `target` (\"Add\") e le chiavi di `target` mancanti in `source` (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Copia `target` e sostituisce ogni testo con quello di `source` quando `source` ha la chiave |\n| `clean <source>` | `<source>-cleaned.txt` | Allinea tutte le chiavi su una colonna e mantiene commenti e righe vuote |\n| `translate4 <source>` | `<source>` con `-new` prima del primo punto | Converte le vecchie chiavi numeriche (`T123`, `T-123`) nelle chiavi in base 36 di Total.js 4 |\n\nI nomi dei file di output perdono l'estensione `.resource`: `total4 diff default.resource sk.resource` scrive `sk-diff.txt`. `translate4` inserisce `-new` prima del primo punto dell'argomento: `total4 translate4 sk.resource` scrive `sk-new.resource`.\n\nUn tipico aggiornamento di una traduzione dopo la comparsa di nuovi testi nelle viste:\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` collega la directory corrente a un progetto nel Total.js Code Editor tramite WebSocket. L'URL è l'indirizzo del progetto, per esempio `https://code.example.com/?id=myproject`; `http` viene cambiato automaticamente in `ws`. L'editor può quindi sfogliare, leggere, creare, salvare, rinominare, caricare e rimuovere i file della directory e leggerne i log. Lo strumento stampa la directory e una riga di benvenuto con il nome del progetto, si riconnette ogni 10 secondi, stampa `404 project not found` finché il progetto non esiste e si ferma con `409 project is already open` quando un altro client ha il progetto aperto.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabj7S1cN61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/command-line/","project":"total-js-v4","version":"0-0-99","section":"guides","language":"sk","title":"Príkazový riadok (total4)","summary":"Nástroj príkazového riadku total4: vytváranie projektov, obsluha priečinka, bundly, minifikácia a lokalizačné zdroje.","markdown":"---\ntitle: \"Príkazový riadok (total4)\"\nproject: Total.js V4\nversion: 0.0.99\nsection: guides\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/guides/command-line/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Príkazový riadok (total4)\n\n> Nástroj príkazového riadku total4: vytváranie projektov, obsluha priečinka, bundly, minifikácia a lokalizačné zdroje.\n\nBalík `total4` inštaluje malý nástroj príkazového riadku, ktorý sa tiež volá `total4`. Vypíše oficiálne šablóny projektov, obslúži priečinok cez HTTP, vytvára a rozbaľuje bundly a balíky, minifikuje súbory a pracuje s lokalizačnými zdrojmi.\n\n## Inštalácia\n\nNástroj je položka `bin` balíka `total4`. Nainštaluj balík globálne, aby si mal príkaz dostupný všade:\n\n```bash\nnpm install -g total4\ntotal4 help\n```\n\nKaždé spustenie najprv vypíše hlavičku s verziou Total.js a potom výsledok príkazu. Bez príkazu nástroj vypíše `Use \"total4 help\" to list all commands.`; neznámy príkaz vypíše chybu s tou istou radou.\n\n## Zápis príkazov\n\nPríkaz je prvý argument. Každý príkaz prijíma tri zápisy: `bundle`, `-bundle` a `--bundle` sú to isté (nástroj z `--name` odstráni jednu úvodnú pomlčku). Niektoré príkazy majú aj krátky alias:\n\n| Príkaz | Aliasy |\n| --- | --- |\n| `help` | `h`, `-h`, `--help` |\n| `version` | `-v`, `--version` |\n| `translate` | `-t` |\n| `translatecsv` | `-c` |\n| `translate4` | `-4` |\n| `minify` | `-compress`, `-compile` (a ich formy s `--`) |\n| `edit` | `-e` |\n\nCesty sa určujú od aktuálneho adresára a každý výstupný súbor sa zapíše tam alebo vedľa vstupného súboru.\n\n## Obsluha priečinka\n\nČíslo ako prvý argument spustí statický webový server pre aktuálny adresár:\n\n```bash\ncd ~/www/landing\ntotal4 8000\n```\n\nServer beží v režime debug na všetkých rozhraniach (`0.0.0.0`) a na zadanom porte. Požiadavka na adresár vráti jeho `index.html`; keď neexistuje, server vykreslí jednoduchý výpis adresára s odkazmi na podadresáre a súbory a ich veľkosťami. Súbory sa posielajú tak, ako sú: HTML, skripty a štýly sa nekompilujú a súbory `.less` sa posielajú ako `text/less`. Dočasné súbory servera idú do dočasného adresára systému, takže priečinok zostane čistý. Server zastavíš cez `Ctrl+C`.\n\n## Šablóny\n\n`total4 templates` stiahne zoznam oficiálnych šablón projektov a vypíše názov a popis každej z nich:\n\n```bash\ntotal4 templates\n```\n\n## Bundly a balíky\n\nBundle je jeden súbor `.bundle` s celou aplikáciou alebo jej časťou. Framework rozbaľuje bundly z `/bundles/` pri štarte aplikácie; [Štruktúra aplikácie](../../guides/application-structure/) vysvetľuje, ako sa bundly zlučujú. Vytvor bundle z aktuálneho adresára:\n\n```bash\ncd ~/projects/eshop\ntotal4 bundle eshop.bundle\n```\n\nNástroj vypíše adresár, názov súboru a potom počet súborov a veľkosť. Predvolený názov je `app.bundle`; vlastný názov zadaj s príponou `.bundle`. Tieto cesty sa nikdy nezahrnú: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` (a ich súbory `.json` a `.pid`), `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` a samotný súbor bundlu.\n\n`total4 package <filename>` vytvorí rovnakým spôsobom súbor `.package` (predvolene `noname.package`; vlastný názov zadaj s príponou `.package`). Jeho zoznam vylúčených ciest je kratší: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/` a `/.git/`. Výsledok skopíruj do `/packages/` aplikácie.\n\n`total4 extract <filename>` zapíše všetky súbory bundlu alebo balíka do aktuálneho adresára:\n\n```bash\nmkdir restored && cd restored\ntotal4 extract ../eshop.bundle\n```\n\nExistujúce súbory s rovnakou cestou sa prepíšu, preto rozbaľuj do prázdneho adresára.\n\n## Minifikácia súborov\n\n`total4 minify <filename>` minifikuje jeden súbor `.js`, `.css` alebo `.html` vlastnými minifikátormi frameworku a vedľa neho zapíše `<name>.min.<extension>`:\n\n```bash\ntotal4 minify public/js/app.js\n# Minified: .../public/js/app.min.js\n```\n\nNázov súboru je vždy posledný argument. Súbory s inými príponami sa nezapíšu.\n\n## Lokalizácia\n\nPrekladové príkazy vytvárajú súbory zdrojov pre lokalizáciu frameworku, pozri [Lokalizácia](../../guides/localization/). Riadok zdroja má tvar `key : text`; kľúče textov z view sú `T` nasledované hashom textu v sústave so základom 36.\n\n`total4 translate`, spustený v koreni aplikácie, prečíta každý súbor `.html` a `.js` (a každý súbor so `sitemap` v ceste) aktuálneho adresára a všetkých jeho podadresárov. Zozbiera:\n\n- každú značku `@(text)`; texty, ktoré začínajú `#` nasledovaným znakom, ktorý nie je medzera, sa preskočia,\n- v súboroch `.js` chybové kľúče použité ako `$.invalid('key')`, `.error('key')` a `.err('key')`; ich kľúčom je samotný text.\n\nVýsledkom je `translate.resource` v aktuálnom adresári, zoskupený podľa komentára `// filename`:\n\n```bash\ncd ~/projects/eshop\ntotal4 translate\n# Translation has been created successfully (128 texts)\n```\n\nSkopíruj ho do `/resources/` pod názvom jazyka, napríklad `sk.resource`, a prelož texty.\n\n`total4 translate \"Text\"` vypíše riadok zdroja pre jeden text, takže ho môžeš pridať do zdroja ručne. Keď je argumentom existujúci súbor, `total4 translate <filename>` vytvorí `translate.resource` s jedným kľúčom pre každý neprázdny riadok tohto súboru.\n\n## CSV pre prekladateľov\n\n`total4 translatecsv` číta tie isté súbory ako `translate` (len značky `@(text)`) a zapíše `translate.csv` so stĺpcami `Hash;Text;Translation`.\n\n## Údržba zdrojov\n\n| Príkaz | Výstup | Čo robí |\n| --- | --- | --- |\n| `diff <source> <target>` | `<target>-diff.txt` | Vypíše kľúče zo `source`, ktoré chýbajú v `target` (\"Add\"), a kľúče z `target`, ktoré chýbajú v `source` (\"Remove\") |\n| `merge <source> <target>` | `<target>-merged.txt` | Skopíruje `target` a nahradí každý text textom zo `source`, keď `source` má daný kľúč |\n| `clean <source>` | `<source>-cleaned.txt` | Zarovná všetky kľúče do jedného stĺpca a ponechá komentáre a prázdne riadky |\n| `translate4 <source>` | `<source>` s `-new` pred prvou bodkou | Prevedie staré číselné kľúče (`T123`, `T-123`) na kľúče Total.js 4 v sústave so základom 36 |\n\nNázvy výstupných súborov vynechávajú príponu `.resource`: `total4 diff default.resource sk.resource` zapíše `sk-diff.txt`. `translate4` vloží `-new` pred prvú bodku argumentu: `total4 translate4 sk.resource` zapíše `sk-new.resource`.\n\nTypická aktualizácia prekladu po tom, ako sa vo view objavia nové texty:\n\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# add the keys from resources/sk-diff.txt and translate them\ntotal4 clean resources/sk.resource\n```\n\n## Total.js Code Editor\n\n`total4 edit <url>` pripojí aktuálny adresár k projektu v Total.js Code Editor cez WebSocket. URL je adresa projektu, napríklad `https://code.example.com/?id=myproject`; `http` sa automaticky zmení na `ws`. Editor potom môže prechádzať, čítať, vytvárať, ukladať, premenovávať, nahrávať a odstraňovať súbory adresára a čítať jeho logy. Nástroj vypíše adresár a uvítací riadok s názvom projektu, každých 10 sekúnd sa znova pripojí, vypisuje `404 project not found`, kým projekt neexistuje, a skončí s `409 project is already open`, keď má projekt otvorený iný klient.\n","entries":[],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabOqg1cF61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Routing","summary":"The ROUTE() function: every way to declare a route in Total.js 4.","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> The ROUTE() function: every way to declare a route in Total.js 4.\n\nRoutes are declared with `ROUTE()`, usually in `exports.install` of a controller. The guide [Routing](../../guides/routing/) explains each part with examples; this page is the exact reference.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDeclares a route: a page, a REST endpoint, an API operation, a file handler or a WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Method, URL, schema operations, roles, middleware and flags in one line. An array of URLs declares the same route several times. |\n| `action` | `Function|String` | no |  | The action, run with the controller as `this` and the dynamic parameters as arguments; or the name of a view. Without it, the route renders the view named after the URL, or runs the schema operations. |\n| `flags` | `Array` | no |  | Flags (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, origins, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), a number with the timeout in milliseconds, or an object with options. A number here is taken as the length. |\n| `length` | `Number` | no | `10` | Maximum size of the request body in kilobytes (`default_request_maxlength` in the config). |\n\nReturns: `Object` The route that was created.\n\nThe first argument describes the whole route in one line:\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` only signed-in requests, `-` only the others; a `@role` implies `+`.\n- `METHOD`: `GET` (default), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, several separated by commas, or `API` for an API route.\n- `{param}`: a dynamic part, optionally typed: `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. A `*` at the end matches the rest of the path.\n- `*Schema --> operations`: validates the body with the schema and runs its operations; `--> operation` runs an operation without a schema. `(response)` after an operation chooses whose result is returned.\n- `[subdomain]` before the URL limits the route to a subdomain.\n\nA URL that starts with `FILE` creates a file route, and one that starts with `SOCKET`, `WS` or `WSS` a WebSocket route. `ROUTE(url, null)` removes the route.\n\nExample: Pages and REST endpoints\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: API routes\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Upload with a timeout and a bigger body\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nAdds the same flags, and a URL prefix, to every route declared inside a function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flags for every route of the group. |\n| `prefix` | `String` | no |  | A URL prefix, like `'/api/'`. |\n| `declaration` | `Function` | yes |  | The function that declares the routes. |\n\nReturns: `undefined` Nothing.\n\nThe arguments can come in any order. An array, or a string without `/` (`'authorize,json'`), is a list of flags. A string with `/` is a prefix; a trailing slash is removed. The function is called right away, with the framework as `this`.\n\nThe flags are added to every `ROUTE()`, `WEBSOCKET()` and `FILE()` inside the function, without duplicates. The prefix is added only to the URLs of `ROUTE()` HTTP routes, not to `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` or `FILE()`.\n\nGroups do not nest: the end of an inner `GROUP()` clears the flags and the prefix of the outer one.\n\nExample: Prefix and flags\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOqg1cF61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Routing","summary":"Die Funktion ROUTE(): jede Möglichkeit, in Total.js 4 eine Route zu deklarieren.","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> Die Funktion ROUTE(): jede Möglichkeit, in Total.js 4 eine Route zu deklarieren.\n\nRouten werden mit `ROUTE()` deklariert, meist in `exports.install` eines Controllers. Der Leitfaden [Routing](../../guides/routing/) erklärt jeden Teil mit Beispielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDeklariert eine Route: eine Seite, einen REST-Endpunkt, eine API-Operation, einen Datei-Handler oder einen WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Methode, URL, Schema-Operationen, Rollen, Middleware und Flags in einer Zeile. Ein Array von URLs deklariert dieselbe Route mehrmals. |\n| `action` | `Function|String` | no |  | Die Aktion, ausgeführt mit dem Controller als `this` und den dynamischen Parametern als Argumente; oder der Name einer View. Ohne sie rendert die Route die View, die nach der URL benannt ist, oder führt die Schema-Operationen aus. |\n| `flags` | `Array` | no |  | Flags (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, Origins, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), eine Zahl mit dem Timeout in Millisekunden oder ein Objekt mit Optionen. Eine Zahl an dieser Stelle wird als Länge interpretiert. |\n| `length` | `Number` | no | `10` | Maximale Größe des Bodys der Anfrage in Kilobyte (`default_request_maxlength` in der Konfiguration). |\n\nReturns: `Object` Die erstellte Route.\n\nDas erste Argument beschreibt die ganze Route in einer Zeile:\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` nur angemeldete Anfragen, `-` nur die anderen; eine `@role` setzt `+` voraus.\n- `METHOD`: `GET` (Standard), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, mehrere durch Kommas getrennt, oder `API` für eine API-Route.\n- `{param}`: ein dynamischer Teil, optional typisiert: `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. Ein `*` am Ende passt auf den Rest des Pfads.\n- `*Schema --> operations`: validiert den Body mit dem Schema und führt seine Operationen aus; `--> operation` führt eine Operation ohne Schema aus. `(response)` nach einer Operation wählt, wessen Ergebnis zurückgegeben wird.\n- `[subdomain]` vor der URL beschränkt die Route auf eine Subdomain.\n\nEine URL, die mit `FILE` beginnt, erstellt eine Datei-Route, und eine, die mit `SOCKET`, `WS` oder `WSS` beginnt, eine WebSocket-Route. `ROUTE(url, null)` entfernt die Route.\n\nExample: Seiten und REST-Endpunkte\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: API-Routen\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Upload mit Timeout und größerem Body\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nFügt jeder Route, die innerhalb einer Funktion deklariert wird, dieselben Flags und ein URL-Präfix hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flags für jede Route der Gruppe. |\n| `prefix` | `String` | no |  | Ein URL-Präfix, etwa `'/api/'`. |\n| `declaration` | `Function` | yes |  | Die Funktion, die die Routen deklariert. |\n\nReturns: `undefined` Nichts.\n\nDie Argumente können in beliebiger Reihenfolge kommen. Ein Array oder ein String ohne `/` (`'authorize,json'`) ist eine Liste von Flags. Ein String mit `/` ist ein Präfix; ein abschließender Schrägstrich wird entfernt. Die Funktion wird sofort aufgerufen, mit dem Framework als `this`.\n\nDie Flags werden jedem `ROUTE()`, `WEBSOCKET()` und `FILE()` innerhalb der Funktion hinzugefügt, ohne Duplikate. Das Präfix wird nur den URLs von HTTP-Routen mit `ROUTE()` hinzugefügt, nicht `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` oder `FILE()`.\n\nGruppen lassen sich nicht verschachteln: Das Ende eines inneren `GROUP()` löscht die Flags und das Präfix des äußeren.\n\nExample: Präfix und Flags\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOqg1cF61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Enrutamiento","summary":"La función ROUTE(): todas las formas de declarar una ruta en Total.js 4.","markdown":"---\ntitle: Enrutamiento\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Enrutamiento\n\n> La función ROUTE(): todas las formas de declarar una ruta en Total.js 4.\n\nLas rutas se declaran con `ROUTE()`, normalmente en `exports.install` de un controlador. La guía [Enrutamiento](../../guides/routing/) explica cada parte con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDeclara una ruta: una página, un endpoint REST, una operación API, un manejador de archivos o un WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Método, URL, operaciones de esquema, roles, middleware y flags en una línea. Un array de URLs declara la misma ruta varias veces. |\n| `action` | `Function|String` | no |  | La acción, que se ejecuta con el controlador como `this` y los parámetros dinámicos como argumentos; o el nombre de una vista. Sin ella, la ruta renderiza la vista con el nombre de la URL o ejecuta las operaciones del esquema. |\n| `flags` | `Array` | no |  | Flags (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, orígenes, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), un número con el tiempo de espera en milisegundos, o un objeto con opciones. Un número aquí se toma como la longitud. |\n| `length` | `Number` | no | `10` | Tamaño máximo del cuerpo de la petición en kilobytes (`default_request_maxlength` en la configuración). |\n\nReturns: `Object` La ruta creada.\n\nEl primer argumento describe toda la ruta en una línea:\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` solo peticiones autenticadas, `-` solo las demás; un `@role` implica `+`.\n- `METHOD`: `GET` (por defecto), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, varios separados por comas, o `API` para una ruta API.\n- `{param}`: una parte dinámica, opcionalmente con tipo: `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. Un `*` al final coincide con el resto de la ruta.\n- `*Schema --> operations`: valida el cuerpo con el esquema y ejecuta sus operaciones; `--> operation` ejecuta una operación sin esquema. `(response)` después de una operación elige qué resultado se devuelve.\n- `[subdomain]` antes de la URL limita la ruta a un subdominio.\n\nUna URL que empieza por `FILE` crea una ruta de archivos, y una que empieza por `SOCKET`, `WS` o `WSS`, una ruta WebSocket. `ROUTE(url, null)` elimina la ruta.\n\nExample: Páginas y endpoints REST\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: Rutas API\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Subida de archivos con tiempo de espera y un cuerpo más grande\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nAñade los mismos flags, y un prefijo de URL, a cada ruta declarada dentro de una función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flags para cada ruta del grupo. |\n| `prefix` | `String` | no |  | Un prefijo de URL, como `'/api/'`. |\n| `declaration` | `Function` | yes |  | La función que declara las rutas. |\n\nReturns: `undefined` Nada.\n\nLos argumentos pueden ir en cualquier orden. Un array, o un string sin `/` (`'authorize,json'`), es una lista de flags. Un string con `/` es un prefijo; se elimina la barra final. La función se llama de inmediato, con el framework como `this`.\n\nLos flags se añaden a cada `ROUTE()`, `WEBSOCKET()` y `FILE()` dentro de la función, sin duplicados. El prefijo solo se añade a las URLs de las rutas HTTP de `ROUTE()`, no a `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` ni `FILE()`.\n\nLos grupos no se anidan: el final de un `GROUP()` interior borra los flags y el prefijo del exterior.\n\nExample: Prefijo y flags\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOqg1cF61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Routage","summary":"La fonction ROUTE() : toutes les façons de déclarer une route dans Total.js 4.","markdown":"---\ntitle: Routage\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routage\n\n> La fonction ROUTE() : toutes les façons de déclarer une route dans Total.js 4.\n\nLes routes sont déclarées avec `ROUTE()`, généralement dans `exports.install` d'un contrôleur. Le guide [Routage](../../guides/routing/) explique chaque partie avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDéclare une route : une page, un endpoint REST, une opération API, un gestionnaire de fichiers ou un WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Méthode, URL, opérations de schéma, rôles, middleware et flags en une ligne. Un tableau d'URL déclare la même route plusieurs fois. |\n| `action` | `Function|String` | no |  | L'action, exécutée avec le contrôleur comme `this` et les paramètres dynamiques en arguments ; ou le nom d'une vue. Sans elle, la route affiche la vue nommée d'après l'URL, ou exécute les opérations du schéma. |\n| `flags` | `Array` | no |  | Flags (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, origines, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), un nombre avec le délai d'expiration en millisecondes, ou un objet d'options. Un nombre à cette position est interprété comme la taille. |\n| `length` | `Number` | no | `10` | Taille maximale du corps de la requête en kilooctets (`default_request_maxlength` dans la configuration). |\n\nReturns: `Object` La route créée.\n\nLe premier argument décrit toute la route en une ligne :\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` uniquement les requêtes connectées, `-` uniquement les autres ; un `@role` implique `+`.\n- `METHOD` : `GET` (par défaut), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, plusieurs séparées par des virgules, ou `API` pour une route API.\n- `{param}` : une partie dynamique, typée en option : `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. Un `*` à la fin correspond au reste du chemin.\n- `*Schema --> operations` : valide le corps avec le schéma et exécute ses opérations ; `--> operation` exécute une opération sans schéma. `(response)` après une opération choisit quel résultat est renvoyé.\n- `[subdomain]` avant l'URL limite la route à un sous-domaine.\n\nUne URL qui commence par `FILE` crée une route de fichiers, et une URL qui commence par `SOCKET`, `WS` ou `WSS` une route WebSocket. `ROUTE(url, null)` supprime la route.\n\nExample: Pages et endpoints REST\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: Routes API\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Upload avec un délai d'expiration et un corps plus grand\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nAjoute les mêmes flags, et un préfixe d'URL, à toutes les routes déclarées dans une fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flags pour toutes les routes du groupe. |\n| `prefix` | `String` | no |  | Un préfixe d'URL, comme `'/api/'`. |\n| `declaration` | `Function` | yes |  | La fonction qui déclare les routes. |\n\nReturns: `undefined` Rien.\n\nLes arguments peuvent être passés dans n'importe quel ordre. Un tableau, ou une chaîne sans `/` (`'authorize,json'`), est une liste de flags. Une chaîne avec `/` est un préfixe ; une barre oblique finale est supprimée. La fonction est appelée immédiatement, avec le framework comme `this`.\n\nLes flags sont ajoutés à chaque `ROUTE()`, `WEBSOCKET()` et `FILE()` de la fonction, sans doublons. Le préfixe n'est ajouté qu'aux URL des routes HTTP `ROUTE()`, pas à `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` ni `FILE()`.\n\nLes groupes ne s'imbriquent pas : la fin d'un `GROUP()` interne efface les flags et le préfixe du groupe externe.\n\nExample: Préfixe et flags\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOqg1cF61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Routing","summary":"La funzione ROUTE(): tutti i modi per dichiarare una route in Total.js 4.","markdown":"---\ntitle: Routing\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Routing\n\n> La funzione ROUTE(): tutti i modi per dichiarare una route in Total.js 4.\n\nLe route si dichiarano con `ROUTE()`, di solito in `exports.install` di un controller. La guida [Routing](../../guides/routing/) spiega ogni parte con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDichiara una route: una pagina, un endpoint REST, un'operazione API, un gestore di file o un WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metodo, URL, operazioni di schema, ruoli, middleware e flag in una riga. Un array di URL dichiara la stessa route più volte. |\n| `action` | `Function|String` | no |  | L'azione, eseguita con il controller come `this` e i parametri dinamici come argomenti; oppure il nome di una vista. Senza di essa, la route renderizza la vista che ha il nome dell'URL, oppure esegue le operazioni di schema. |\n| `flags` | `Array` | no |  | Flag (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, origini, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), un numero con il timeout in millisecondi, oppure un oggetto con opzioni. Un numero qui viene interpretato come lunghezza. |\n| `length` | `Number` | no | `10` | Dimensione massima del corpo della richiesta in kilobyte (`default_request_maxlength` nella configurazione). |\n\nReturns: `Object` La route creata.\n\nIl primo argomento descrive l'intera route in una riga:\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` solo richieste autenticate, `-` solo le altre; un `@role` implica `+`.\n- `METHOD`: `GET` (predefinito), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, più metodi separati da virgole, oppure `API` per una route API.\n- `{param}`: una parte dinamica, facoltativamente tipizzata: `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. Un `*` alla fine corrisponde al resto del percorso.\n- `*Schema --> operations`: valida il corpo con lo schema ed esegue le sue operazioni; `--> operation` esegue un'operazione senza schema. `(response)` dopo un'operazione sceglie quale risultato viene restituito.\n- `[subdomain]` prima dell'URL limita la route a un sottodominio.\n\nUn URL che inizia con `FILE` crea una route di file, e uno che inizia con `SOCKET`, `WS` o `WSS` una route WebSocket. `ROUTE(url, null)` rimuove la route.\n\nExample: Pagine ed endpoint REST\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: Route API\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Upload con un timeout e un corpo più grande\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nAggiunge gli stessi flag, e un prefisso di URL, a ogni route dichiarata dentro una funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flag per ogni route del gruppo. |\n| `prefix` | `String` | no |  | Un prefisso di URL, come `'/api/'`. |\n| `declaration` | `Function` | yes |  | La funzione che dichiara le route. |\n\nReturns: `undefined` Niente.\n\nGli argomenti possono arrivare in qualsiasi ordine. Un array, o una stringa senza `/` (`'authorize,json'`), è un elenco di flag. Una stringa con `/` è un prefisso; la barra finale viene rimossa. La funzione viene chiamata subito, con il framework come `this`.\n\nI flag vengono aggiunti a ogni `ROUTE()`, `WEBSOCKET()` e `FILE()` dentro la funzione, senza duplicati. Il prefisso viene aggiunto solo agli URL delle route HTTP di `ROUTE()`, non a `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` o `FILE()`.\n\nI gruppi non si annidano: la fine di un `GROUP()` interno azzera i flag e il prefisso di quello esterno.\n\nExample: Prefisso e flag\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabOqg1cF61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/routing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Smerovanie","summary":"Funkcia ROUTE(): všetky spôsoby, ako deklarovať trasu v Total.js 4.","markdown":"---\ntitle: Smerovanie\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/routing/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Smerovanie\n\n> Funkcia ROUTE(): všetky spôsoby, ako deklarovať trasu v Total.js 4.\n\nTrasy sa deklarujú pomocou `ROUTE()`, zvyčajne v `exports.install` kontroléra. Príručka [Smerovanie](../../guides/routing/) vysvetľuje každú časť na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### ROUTE(url, [action], [flags], [length])\n\nType: `method`\n\nDeklaruje trasu: stránku, REST endpoint, API operáciu, obsluhu súborov alebo WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metóda, URL, operácie schémy, roly, middleware a flagy na jednom riadku. Pole URL deklaruje tú istú trasu viackrát. |\n| `action` | `Function|String` | no |  | Akcia, spustená s kontrolérom ako `this` a dynamickými parametrami ako argumentmi; alebo názov view. Bez nej trasa vykreslí view pomenované podľa URL alebo spustí operácie schémy. |\n| `flags` | `Array` | no |  | Flagy (`json`, `upload`, `cors`, `csrf`, `referer`, `mobile`, `robot`, `encrypt`, `delay`, `novalidate`, `xml`, `raw`, pôvody, `credentials`, `#middleware`, `@role`, `// description`, `id:name`), číslo s časovým limitom v milisekundách alebo objekt s možnosťami. Číslo na tomto mieste sa berie ako dĺžka. |\n| `length` | `Number` | no | `10` | Maximálna veľkosť tela požiadavky v kilobajtoch (`default_request_maxlength` v konfigurácii). |\n\nReturns: `Object` Vytvorená trasa.\n\nPrvý argument opisuje celú trasu na jednom riadku:\n\n```text\n[+|-][METHOD] /url/{param}/ [*Schema --> operations] [@role] [#middleware] [flags]\n```\n\n- `+` len prihlásené požiadavky, `-` len ostatné; `@role` predpokladá `+`.\n- `METHOD`: `GET` (predvolená), `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD`, `OPTIONS`, viac oddelených čiarkami, alebo `API` pre API trasu.\n- `{param}`: dynamická časť, voliteľne s typom: `{id:number}`, `{active:boolean}`, `{date:date}`, `{id:uid}`, `{id:guid}`. `*` na konci zodpovedá zvyšku cesty.\n- `*Schema --> operations`: validuje telo schémou a spustí jej operácie; `--> operation` spustí operáciu bez schémy. `(response)` za operáciou určuje, ktorej výsledok sa vráti.\n- `[subdomain]` pred URL obmedzí trasu na subdoménu.\n\nURL, ktorá začína na `FILE`, vytvorí trasu pre súbory, a URL, ktorá začína na `SOCKET`, `WS` alebo `WSS`, trasu pre WebSocket. `ROUTE(url, null)` trasu odstráni.\n\nExample: Stránky a REST endpointy\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n\tROUTE('GET /users/{id}/', user);\n\tROUTE('+POST /api/users/ *Users --> insert');\n\tROUTE('+GET /admin/ @admin', admin);\n};\n\nfunction user(id) {\n\tthis.json({ id: id });\n}\n```\n\nExample: API trasy\n```js\nROUTE('API /api/ -users_list      *Users --> list');\nROUTE('API /api/ -users_read/{id} *Users --> read');\nROUTE('API /api/ +users_save      *Users --> save');\n```\n\nExample: Nahrávanie s časovým limitom a väčším telom\n```js\n// 60 seconds, 5 MB\nROUTE('POST /upload/', upload, ['upload', 60000], 1024 * 5);\n```\n\n### GROUP([flags], [prefix], declaration)\n\nType: `method`\n\nPridá rovnaké flagy a prefix URL každej trase deklarovanej vnútri funkcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `flags` | `String|Array` | no |  | Flagy pre každú trasu skupiny. |\n| `prefix` | `String` | no |  | Prefix URL, napríklad `'/api/'`. |\n| `declaration` | `Function` | yes |  | Funkcia, ktorá deklaruje trasy. |\n\nReturns: `undefined` Nič.\n\nArgumenty môžu byť v ľubovoľnom poradí. Pole alebo reťazec bez `/` (`'authorize,json'`) je zoznam flagov. Reťazec s `/` je prefix; koncová lomka sa odstráni. Funkcia sa zavolá hneď, s frameworkom ako `this`.\n\nFlagy sa pridajú každému `ROUTE()`, `WEBSOCKET()` a `FILE()` vnútri funkcie, bez duplicít. Prefix sa pridá len k URL HTTP trás `ROUTE()`, nie k `ROUTE('SOCKET ...')`, `ROUTE('FILE ...')`, `WEBSOCKET()` ani `FILE()`.\n\nSkupiny sa nevnárajú: koniec vnútorného `GROUP()` vymaže flagy a prefix vonkajšieho.\n\nExample: Prefix a flagy\n```js\nexports.install = function() {\n\tGROUP('/api/', ['authorize'], function() {\n\t\tROUTE('GET  /users/     *Users --> query');   // GET /api/users/\n\t\tROUTE('POST /users/     *Users --> insert');  // POST /api/users/\n\t});\n};\n```\n","entries":[{"type":"method","name":"ROUTE()","signature":"ROUTE(url, [action], [flags], [length])","since":"","deprecated":false},{"type":"method","name":"GROUP()","signature":"GROUP([flags], [prefix], declaration)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Controller","summary":"Properties and methods of the controller, the object that answers a request.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Properties and methods of the controller, the object that answers a request.\n\nThe controller is `this` inside every action of a route. It holds the request data and the methods that answer the request. The guide [Controllers](../../guides/controllers/) explains how to use it with examples; this page is the exact reference.\n\n## API\n\n### controller.body\n\nType: `property`\n\nThe parsed body of the request.\n\nReturns: `Object`\n\nA JSON or URL-encoded body is parsed into an object. Values of a form are strings. A route with a schema replaces it with the validated model. You can also assign a new object.\n\nExample: Read the body\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nThe query string of the URL as an object.\n\nReturns: `Object`\n\nValues are strings: `?page=2` gives `{ page: '2' }`. The object is parsed the first time you read it.\n\nExample: Paging\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nThe dynamic parameters of the URL.\n\nReturns: `Object`\n\nEach `{name}` of the route becomes a key. Parameters declared with a type are converted: `{id:number}` with `parseInt()`, `{active:boolean}` with `parseBoolean()` and `{date:date}` with `parseDate()`. The same values arrive as arguments of the action.\n\nExample: Typed parameter\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nThe uploaded files.\n\nReturns: `Array`\n\nOnly routes with the `upload` flag receive files. Each file has `name` (the form field), `filename`, `type`, `size`, `extension`, `width` and `height`, and the methods `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` and `isAudio()`. `move()`, `copy()` and `read()` return a promise without a callback. The temporary files are removed when the request ends, unless you call `controller.autoclear(false)`.\n\nExample: Save an upload\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nThe signed-in user.\n\nReturns: `Object`\n\nThe object that your `AUTH()` delegate passed to `$.success(user)`. It is `undefined` when nobody is signed in. You can assign it.\n\nExample: Profile\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nThe headers of the request.\n\nReturns: `Object`\n\nHeader names are in lower case.\n\nExample: Read a header\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nThe IP address of the client.\n\nReturns: `String`\n\nBehind a proxy it is the first address of the `X-Forwarded-For` header; otherwise the address of the connection.\n\n### controller.url\n\nType: `property`\n\nThe path of the request URL in lower case.\n\nReturns: `String`\n\nIt has no query string and always ends with `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true` when the client is a mobile device.\n\nReturns: `Boolean`\n\nIt is tested on the `User-Agent` header. You can assign it.\n\n### controller.xhr\n\nType: `property`\n\n`true` when the request was sent by XMLHttpRequest.\n\nReturns: `Boolean`\n\nIt is `true` when the request has the header `X-Requested-With: XMLHttpRequest`.\n\n### controller.language\n\nType: `property`\n\nThe language of the request.\n\nReturns: `String`\n\nIt is the value returned by your localization delegate (`DEF.onLocale`). Views and `controller.mail()` translate texts with it.\n\n### controller.status\n\nType: `property`\n\nThe HTTP status code of the answer.\n\nReturns: `Number`\n\nSet it before you answer. `json()`, `jsonstring()`, `plain()`, `content()` and `html()` use it, and `200` when it is not set. `invalid()` uses a status over `399` for the errors.\n\nExample: Created\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nAn object shared by the view and its layout.\n\nReturns: `Object`\n\nValues you store here before `view()` are available in the view and in the layout as `repository`. The page title and meta tags are stored in it too.\n\nExample: Pass a value to the layout\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nThe problem of an error route.\n\nReturns: `Error|String`\n\nIn a route for an error status (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) it contains the problem passed to `throw404()`, `throw500()` and the others.\n\n### controller.req\n\nType: `property`\n\nThe request object of the framework.\n\nReturns: `Request`\n\nIt extends the Node.js request. The properties of the controller like `body`, `query` and `ip` read from it.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nAnswers with an object serialized as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The value to serialize. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `beautify` | `Boolean` | no | `false` | Formats the JSON with indentation. |\n| `replacer` | `Function` | no |  | A replacer for `JSON.stringify()`. |\n\nReturns: `Controller` The controller.\n\nThe content type is `application/json` and the status is `controller.status` or `200`. An `ErrorBuilder` is answered as its errors with its own status. `beautify` can be the second argument.\n\nExample: An object\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Formatted\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nAnswers with a text that is already JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | The JSON text. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\nUse it when you have the JSON as a string, for example from a cache. The text is sent as it is, with the content type `application/json`.\n\nExample: From a cache\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nAnswers with plain text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | The text. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\nThe content type is `text/plain`. An object is serialized as formatted JSON; `null` gives an empty body.\n\nExample: Text\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nAnswers with HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The HTML. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\nThe same as `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nAnswers with a text and your content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The content. |\n| `type` | `String` | no | `text/plain` | The content type. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\nAn `ErrorBuilder` as `body` is answered as JSON with its own status.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenders a view and answers with it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name of the view without `.html`. |\n| `model` | `Object` | no |  | The model, available in the view as `model`. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `partial` | `Boolean` | no | `false` | Returns the HTML as a string and does not answer. It can be the third argument. |\n\nReturns: `Controller|String` The controller, or the HTML when `partial` is `true`.\n\nThe view is a file `name.html` in `views/`, rendered inside the layout (`layout` by default, see `controller.layout()`). Routes of a controller other than `default` look for views in `views/<controller name>/`. The first character of the name changes where the file is looked up:\n\n| Prefix | Where |\n| --- | --- |\n| `~` | The root of `views/` |\n| `#plugin/view` | The views of a plugin |\n| `=theme/view` | The views of a theme |\n| `@` | A package |\n\nWithout a name, the view is named after the last part of the URL (`index` for `/`). With `partial` set to `true` the method returns the rendered HTML instead of answering.\n\nExample: A page\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: HTML as a string\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nChooses the layout for the next view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the layout view, or an empty string. |\n\nReturns: `Controller` The controller.\n\nThe default layout is `layout` (the `default_layout` config). An empty string renders the view without a layout.\n\nExample: Without a layout\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nSets the title of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The title. |\n\nReturns: `Controller` The controller.\n\nThe layout prints it with `@{title}`. The text is HTML-encoded.\n\nExample: Title\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nSets the meta values of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | The title. |\n| `description` | `String` | no |  | The description. |\n| `keywords` | `String|Array` | no |  | The keywords. |\n| `image` | `String` | no |  | The URL of an image. |\n\nReturns: `Controller` The controller.\n\nThe layout prints them with `@{meta}`. `keywords` can be an array.\n\nExample: Meta tags\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nAnswers with a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The file in `public/`, or `~` and an absolute path. |\n| `download` | `String|Boolean` | no |  | A name for the downloaded file; `true` uses the name of the file. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs when the file is sent. |\n\nReturns: `Controller` The controller.\n\nThe file is read from `public/`. A name that starts with `~` is an absolute path.\n\nExample: Download\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nAnswers with a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The data. |\n| `type` | `String` | yes |  | The content type. |\n| `encoding` | `String` | no |  | A conversion of the data. |\n| `download` | `String` | no |  | A name for the downloaded file. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\n`encoding` converts the buffer before it is sent (`binary`, `utf8`, `ascii`).\n\nExample: An image in memory\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nAnswers with a readable stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | A readable stream. |\n| `type` | `String` | yes |  | The content type. |\n| `download` | `String` | no |  | A name for the downloaded file. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs when the stream is sent. |\n| `nocompress` | `Boolean` | no | `false` | Disables the compression. |\n\nReturns: `Controller` The controller.\n\nThe answer is compressed unless `nocompress` is `true`. The first two arguments can be swapped (`type`, `stream`).\n\nExample: A CSV file\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nRedirects the client to another URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The target URL. |\n| `permanent` | `Boolean` | no | `false` | Sends `301 Moved Permanently`. |\n\nReturns: `Controller` The controller.\n\nThe status is `302`, or `301` when `permanent` is `true`.\n\nExample: After a form\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nAnswers with an empty body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | Extra headers, or a status code. |\n\nReturns: `Controller` The controller.\n\nA number instead of the headers sets the status code. For `204 No Content` use also `controller.nocontent([headers])`.\n\nExample: Accepted\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nAnswers with the JSON `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | The value of `success`. |\n| `value` | `Object` | no |  | A value added as `value`. |\n\nReturns: `Controller` The controller.\n\n`success(value)` answers `{ \"success\": true, \"value\": value }`. `success(false)` answers `{ \"success\": false }`.\n\nExample: With a value\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nAnswers with an error as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | A status code, the name of the error or the error. |\n| `error` | `String` | no |  | The text of the error. |\n\nReturns: `ErrorBuilder` The builder with the errors.\n\nThe errors are answered as a JSON array with the status `400` (the `default_errorbuilder_status` config). A number as the first argument sets the status; an `Error` or an `ErrorBuilder` is answered as it is. The answer is sent in the next tick, so you can still add errors to the returned builder.\n\nExample: Validation\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Another status\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nCreates a callback that answers success or an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` adds the response as `value`; another value is added as `value` itself. |\n\nReturns: `Function` A callback `(err, response)`.\n\nThe callback has the form `(err, response)`. On error it calls `controller.invalid(err)`. Otherwise it answers `{ \"success\": true }`; with `done(true)` the response is added as `value`, and with another value that value is added.\n\nExample: Any callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nCreates a callback that answers the response as JSON or with a view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | The name of a view. |\n\nReturns: `Function` A callback `(err, data)`.\n\nThe callback has the form `(err, data)`. When `err` is an `ErrorBuilder` and you did not pass a view, its errors are answered as JSON. Any other error answers the error page `404`, or `500` when the `ErrorBuilder` contains an `Error`. Without an error it answers `data` as JSON, or renders the view with `data` as the model.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: A view\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nAnswers with the error page 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem, available in the error route as `controller.exception`. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#404` when you declared one; otherwise the framework renders its own error page. The same family answers other statuses: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` and `throw503()`. Each one has an alias named `view400()` … `view503()`. Nothing happens when the request was already answered.\n\nExample: Missing record\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: Your own page\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nAnswers with the error page 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem, available in the error route as `controller.exception`. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#403` when you declared one. Alias: `view403()`.\n\nExample: Only for admins\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nLogs an error and answers with the error page 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | The error. |\n\nReturns: `Controller` The controller.\n\nThe error is logged by the framework (`DEF.onError`). Then the route `#500` runs when you declared one. Alias: `view500()`.\n\nExample: In a promise\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nReads a cookie of the request or writes a cookie to the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the cookie. |\n| `value` | `String` | no |  | The value to write. |\n| `expires` | `String` | no |  | When the cookie expires, for example `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` The value when reading, the controller when writing.\n\nWith one argument it returns the value of the cookie, or an empty string. With a value it adds a `Set-Cookie` header. `expires` is a text such as `'5 days'` or `'2 hours'`; a negative one (`'-1 day'`) removes the cookie. Instead of `expires` you can pass the options object with `expires` inside it.\n\nOptions: `domain`, `path` (default `/`), `secure` (default the `default_cookies_secure` config), `httponly`, and `samesite` (`Lax`, `Strict` or `None`; default `Lax`, the `default_cookies_samesite` config).\n\nExample: Write and read\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Remove\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nSets a header of the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the header. |\n| `value` | `String` | yes |  | The value. |\n\nReturns: `Controller` The controller.\n\nExample: A header\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nDisables the HTTP cache of the answer.\n\nReturns: `Controller` The controller.\n\nExample: Fresh data\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCreates a CSRF token for the current request.\n\nReturns: `String` The token.\n\nRoutes with the `csrf` flag verify the token from the `x-csrf-token` header or from the `?csrf=` argument of the URL. In views the same token is `@{csrf}`.\n\nExample: Send the token\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nKeeps or removes the uploaded files when the request ends.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` keeps the files. |\n\nReturns: `Controller` The controller.\n\n`autoclear(false)` keeps the temporary files of `controller.files` after the answer, for work that continues later. `controller.clear()` removes them immediately.\n\nExample: Process later\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nSends a server-sent event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | The data of the event. |\n| `eventname` | `String` | no |  | The name of the event. |\n| `id` | `String` | no |  | The ID of the event. |\n| `retry` | `Number` | no |  | How long the browser waits before it reconnects, in milliseconds. |\n\nReturns: `Boolean` `false` when the event cannot be sent (the client disconnected or the request was answered).\n\nThe first call answers with the headers of `text/event-stream` and keeps the connection open. An object is serialized as JSON. When `retry` is missing, the first call uses the timeout of the route. The previous event ID sent by the browser is in `controller.sseID`. The stream ends with `controller.close()`.\n\nExample: A clock\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nForwards the request to another URL and answers with its response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | The target URL, or the options. |\n\nReturns: `undefined` Nothing.\n\nThe method, body, query string and headers of the request are sent to the target (except `host`, `connection`, `accept-encoding` and the `x-forwarded-*` headers). The status and the body of the response are answered back. On error it calls `controller.invalid(err)`.\n\nOptions: `url` (required), `method`, `headers`, `timeout` (default `10000` ms) and `callback(err, response)`, which runs before the answer.\n\nExample: Forward an API\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nReads Basic access authentication, or asks the browser for it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | The realm shown by the browser. |\n\nReturns: `Object|null` The credentials without a label; `null` with a label.\n\nWithout an argument it returns `{ user, password, empty }` from the `Authorization` header. With a label it answers `401` with the `WWW-Authenticate` header, so the browser shows a login dialog.\n\nExample: A protected page\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nTells whether the client is still connected.\n\nReturns: `Boolean`\n\nIt is `false` after the client closed the connection or after `controller.close()`. Check it in long work before you answer.\n\nExample: Long work\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nAlways `true` for a controller.\n\nReturns: `Boolean`\n\nUseful to tell a controller from a `$` object in a shared function.\n\nExample: A shared function\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nTells whether the request came over HTTPS.\n\nReturns: `Boolean`\n\nIt is `true` when the protocol is `https:` (or `wss:`). Behind a proxy it depends on the URL the framework sees. Same as `req.secured`.\n\nExample: Force HTTPS\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nThe `Referer` header of the request.\n\nReturns: `String`\n\nAn empty string when the header is missing.\n\nExample: Go back\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nTells whether the user agent looks like a bot.\n\nReturns: `Boolean`\n\nIt tests the `User-Agent` header for words like `bot`, `crawler` and `spider`.\n\nExample: Example\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nThe parsed user agent as a short text with the browser and the system.\n\nReturns: `String`\n\nUse `req.useragent(true)` for an object with the browser, the OS and the device. Same as `req.ua`.\n\nExample: Example\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nThe parsed URL of the request.\n\nReturns: `Object`\n\nAn object of `url.parse()` with `pathname`, `query`, `hostname` and the other parts.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nThe parts of the path of the URL.\n\nReturns: `String[]`\n\n`/products/shoes/` gives `['products', 'shoes']`.\n\nExample: Example\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nThe subdomain of the request as an array.\n\nReturns: `String[]`\n\n`shop.eu.example.com` gives `['shop', 'eu']`; `www` is ignored. It is `null` without a subdomain.\n\nExample: Example\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nThe id of the session of the request.\n\nReturns: `String`\n\nSet by your `AUTH()` delegate or by the session mechanism. Same as `req.sessionid`.\n\nExample: Example\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nThe id of the last event the browser received.\n\nReturns: `String`\n\nThe value of the `Last-Event-ID` header that the browser sends when it reconnects to a server-sent events route, or `null`.\n\nExample: Example\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nThe route that the request matched.\n\nReturns: `Object`\n\nAn internal object of the framework with the URL, the flags, the schema and the options of the route. Read it, do not change it.\n\nExample: Example\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nThe custom options of the route.\n\nReturns: `Object`\n\nThe object that you pass to `ROUTE()` as options.\n\nExample: Example\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nThe flags of the route.\n\nReturns: `String[]`\n\nAn array with the flags of the route, for example `['get', 'json']`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nThe name of the schema of the route.\n\nReturns: `String`\n\nFor a route like `POST /api/users/ *Users --> save` it is `'Users'`. An empty string when the route has no schema.\n\nExample: Example\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nThe name of the controller.\n\nReturns: `String`\n\nThe name of the file in `/controllers/` (without `.js`) that declared the route.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nThe breadcrumb of the current sitemap item.\n\nReturns: `Object[]`\n\nThe items set by `controller.sitemap()`; in views the same list is in `@{sitemap}`.\n\nExample: Example\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nAnswers with JSONP: a call of a JavaScript function with the data.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the JavaScript function. |\n| `obj` | `Object` | yes |  | The data. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `beautify` | `Boolean` | no | `false` | Formats the JSON. |\n| `replacer` | `Function` | no |  | A replacer for `JSON.stringify()`. |\n\nReturns: `Controller` The controller.\n\nThe body is `name(json)` with the content type `application/x-javascript`. Without `name` the function is `callback`. An `ErrorBuilder` is answered as its errors.\n\nExample: Name from the query string\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nAnswers with the error page 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#400` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view400()`.\n\nExample: Answer 400\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nAnswers with the error page 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#401` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view401()`.\n\nExample: Answer 401\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nAnswers with the error page 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#409` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view409()`.\n\nExample: Answer 409\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nAnswers with the error page 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#501` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view501()`.\n\nExample: Answer 501\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nAnswers with the error page 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Controller` The controller.\n\nIt runs the route `#503` when you declared one; otherwise the framework renders its own error page. The problem is in `controller.exception` of the error route. Alias: `controller.view503()`.\n\nExample: Answer 503\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias of `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 400 in the same way.\n\nExample: Same as throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias of `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 401 in the same way.\n\nExample: Same as throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias of `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 403 in the same way.\n\nExample: Same as throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias of `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 404 in the same way.\n\nExample: Same as throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias of `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 409 in the same way.\n\nExample: Same as throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias of `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | The error, logged by the framework. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 500 in the same way.\n\nExample: Same as throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias of `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 501 in the same way.\n\nExample: Same as throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias of `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | The problem. |\n\nReturns: `Controller` The controller.\n\nIt answers the error page 503 in the same way.\n\nExample: Same as throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nAnswers `204 No Content` without a body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Controller` The controller.\n\nExample: Nothing to answer\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nCloses the connection without an answer.\n\nReturns: `Controller` The controller.\n\nThe socket is destroyed. Nothing happens when the request was already answered.\n\nExample: Drop a request\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nEnds the answer, mostly a stream of server-sent events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Calls `res.end()`. |\n\nReturns: `Controller` The controller.\n\nIt ends the response of `controller.sse()` and marks the controller as disconnected. With `end` set to `false` the response is only marked as finished.\n\nExample: Stop a stream\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nMarks the controller as canceled.\n\nReturns: `Controller` The controller.\n\nIt sets `controller.isCanceled` to `true`. Called in a handler of `ON('controller')`, it stops the action of the route from running, so the handler must answer itself.\n\nExample: Stop requests in maintenance\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nRemoves the uploaded files of the request now.\n\nReturns: `Controller` The controller.\n\nThe temporary files of `controller.files` are deleted and `body`, `query` and the cookies of the request are cleared.\n\nExample: After the work\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nLets you answer with the Node.js response yourself.\n\nReturns: `Boolean` `true` when you can answer.\n\nThe framework marks the request as answered and stops waiting for it. Then write to `controller.res` with `writeHead()` and `end()`. It returns `false` when the request was already answered.\n\nExample: Write the response\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nLogs an error with the name of the controller and the URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | The error. |\n\nReturns: `Controller` The controller.\n\nThe error goes to `F.error()` and to `controller.exception`; the request is not answered. An `ErrorBuilder` is answered as JSON instead.\n\nExample: Log and continue\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nCreates a callback that answers the error and passes only the result on.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Runs on success with the results. |\n\nReturns: `Function` A callback `(err, a, b, c)`.\n\nThe returned function has the form `(err, a, b, c)`. On error it calls `controller.invalid(err)`; otherwise it calls `callback(a, b, c)` with the controller as `this`.\n\nExample: Only the success path\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nCreates an absolute URL with the host of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A path to add. |\n\nReturns: `String` The URL, for example `https://example.com/products/`.\n\nThe protocol, the host name and the port of the request with `path` added.\n\nExample: A link for an email\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nAnswers with an image changed by the image processor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The image. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs when the response ends. |\n\nReturns: `Controller` The controller.\n\n`filename` is a file in `/public/` (or a full path with `~` in front) or a stream. `make(image)` changes the image with the methods of `Image` (`resize()`, `quality()`, ...). The result is cached in `/tmp/`. It needs GraphicsMagick or ImageMagick.\n\nExample: A thumbnail\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nCaches the whole answer of an action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key in the cache. |\n| `expire` | `String|Date` | yes |  | How long, for example `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` skips the cache. |\n| `fn` | `Function` | yes |  | Creates the answer; runs with the controller as `this`. |\n| `fnFrom` | `Function` | no |  | Runs before an answer from the cache. |\n\nReturns: `Controller` The controller.\n\nThe first call runs `fn` and stores the answer (a view, JSON or text) under `key` for `expire`. Later calls answer from the cache, and `fnFrom` runs before that. With `disabled` set to `true` the cache is skipped. The theme is added to the key.\n\nExample: Cache the home page\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nSets the meta description of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The description. |\n\nReturns: `Controller` The controller.\n\nIn the layout it is written by `@{meta}`. `controller.keywords()` sets the keywords and `controller.author()` the author the same way.\n\nExample: Meta tags\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nSets the meta keywords of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | The keywords. |\n\nReturns: `Controller` The controller.\n\nAn array is joined with commas. In the layout it is written by `@{meta}`.\n\nExample: Keywords\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nAdds tags into the head of the layout, or reads them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | A file name or an HTML tag. |\n\nReturns: `Controller|String` The controller, or the HTML without arguments.\n\nA `.css` file becomes a `<link>` and a `.js` file a `<script>`; relative names point to `/public/css/` and `/public/js/`. A value that starts with `<` is added as it is. Each value is added once. Without arguments it returns the HTML; in the layout use `@{head}`.\n\nExample: Files for one page\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nAdds content into a named place of the layout, or reads it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the place. |\n| `value` | `String` | no |  | The content. |\n\nReturns: `Controller|String` The controller, or the content with only `name`.\n\nA `.js` value becomes a `<script>` and a `.css` value a `<link>`; other values are added as they are. In the layout use `@{place('name')}`.\n\nExample: Scripts at the end of the page\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nSets the theme of the views of this request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the theme. |\n\nReturns: `Controller` The controller.\n\nViews, layouts and static files are then looked up in `/themes/{name}/` first. The default comes from `CONF.default_theme`.\n\nExample: A theme per customer\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nRenders a component to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the component. |\n| `settings` | `Object` | no |  | The settings of the component. |\n| `model` | `Object` | no |  | The model; the model of the view by default. |\n\nReturns: `String` The HTML, or an empty string for an unknown component.\n\nThe component is a file in `/components/`. Its CSS and JS are added to the head of the layout. In views use `@{component('name')}`.\n\nExample: HTML of a component\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nRuns a view helper from `DEF.helpers`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the helper. |\n| `arg` | `Object` | no |  | Arguments for the helper. |\n\nReturns: `String` The output of the helper.\n\nThe helper runs with the controller as `this`. An unknown helper returns an empty string.\n\nExample: Use a helper in an action\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nCreates the URL of a file in `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n| `path` | `String` | no |  | A path joined to a relative URL. |\n\nReturns: `String` The URL.\n\nIt respects the static URL settings and the theme. The family `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` and `public_download()` does the same for its own directory.\n\nExample: A URL in JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nCreates the URL of a file in the public `js` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n| `tag` | `Boolean` | no | `false` | Returns an HTML tag. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_script`, default `/js/`). With `tag` set to `true` it returns the HTML tag (`<script>` or `<link>`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nCreates the URL of a file in the public `css` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n| `tag` | `Boolean` | no | `false` | Returns an HTML tag. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_style`, default `/css/`). With `tag` set to `true` it returns the HTML tag (`<script>` or `<link>`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nCreates the URL of a file in the public `img` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_image`, default `/img/`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nCreates the URL of a file in the public `videos` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_video`, default `/videos/`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nCreates the URL of a file in the public `fonts` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_font`, default `/fonts/`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nCreates the URL of a file in the public `download` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file. |\n\nReturns: `String` The URL.\n\nThe directory comes from the configuration (`static_url_download`, default `/download/`).\n\nExample: URL of a file\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nAdds a test of a route in the tests of the framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The route to test. |\n| `name` | `String` | no |  | The name of the test. |\n| `callback` | `Function` | no |  | `function(result)` that returns `true` on success. |\n\nReturns: `Object` The test.\n\nThe tests of one controller run one after another. `url` is a route like `'GET /api/products/'` or `'API /api/ products_query'` (then the name of the test is the operation). `callback(result)` gets `{ err, value, response, name }` and returns `true` when the test passes; without it, a test passes when there is no error.\n\nExample: Test routes from a route\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nThe `Host` header of the request.\n\nReturns: `String`\n\nThe host name with the port, for example `example.com:8000`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nTells whether the request came over HTTPS.\n\nReturns: `Boolean`\n\nIt is `true` when the protocol is `https:` or `wss:`.\n\nExample: Example\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nThe result of the authorization.\n\nReturns: `Boolean`\n\nIt is `true` until your `AUTH()` delegate runs, then it is `true` when the delegate accepted the user and `false` when it rejected it.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nTells whether the request asks for a static file.\n\nReturns: `Boolean`\n\nIt is `true` when the URL has a file extension and static files are allowed. Useful in `DEF.onLocale` and middleware.\n\nExample: Example\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nTells whether the request came from JavaScript.\n\nReturns: `Boolean`\n\nIt is `true` when the header `X-Requested-With` is `XMLHttpRequest`.\n\nExample: Example\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nThe IP address of the client.\n\nReturns: `String`\n\nBehind a proxy it is the first address of `X-Forwarded-For`. It can be set.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nThe parsed URL of the request.\n\nReturns: `Object`\n\nAn object of `url.parse()` with `pathname`, `query`, `hostname` and `port`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nThe parts of the path in lower case.\n\nReturns: `String[]`\n\n`/Products/Shoes/` gives `['products', 'shoes']`. `req.split` keeps the original case.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nThe parts of the path of the URL.\n\nReturns: `String[]`\n\nThe parts as they were in the URL. Same as `controller.split`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nThe subdomain as an array, or `null`.\n\nReturns: `String[]`\n\n`www` is ignored. `a.localhost` gives `['a']`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nTells whether the user agent is a mobile device.\n\nReturns: `Boolean`\n\nIt tests the `User-Agent` header. It can be set.\n\nExample: Example\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nTells whether the user agent looks like a bot.\n\nReturns: `Boolean`\n\nIt tests the `User-Agent` header.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nThe parsed user agent as a short text with the browser and the system.\n\nReturns: `String`\n\nThe same as `req.useragent()`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nThe query string as an object.\n\nReturns: `Object`\n\nIt is parsed on the first read and can be set.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nThe parsed body of the request.\n\nReturns: `Object`\n\nA JSON or form body. Same as `controller.body`.\n\nExample: Example\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nThe uploaded files.\n\nReturns: `HttpFile[]`\n\nAn array of `HttpFile` objects for routes with the `upload` flag. Same as `controller.files`.\n\nExample: Example\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nThe user accepted by the `AUTH()` delegate, or `null`.\n\nReturns: `Object`\n\nSame as `controller.user`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nThe session object of the request, or `null`.\n\nReturns: `Object`\n\nSet by your `AUTH()` delegate or the session mechanism. Same as `controller.session`.\n\nExample: Example\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nParses the `User-Agent` header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Returns an object. |\n\nReturns: `String|Object` The user agent.\n\nWithout an argument it returns a short text with the names found in the header, such as the browser and the system. With `true` it returns `{ os, browser, device }`, where `device` is `desktop`, `mobile`, `tablet` or `tv`. The result is cached on the request.\n\nExample: Details of the device\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nReads a cookie of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the cookie. |\n\nReturns: `String` The value.\n\nThe value is decoded. A missing cookie gives an empty string. `controller.cookie(name)` does the same.\n\nExample: Read a cookie in middleware\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nReads the Basic authorization header.\n\nReturns: `Object` `{ user, password, empty }`.\n\nIt decodes `Authorization: Basic ...` to `{ user, password, empty }`. `empty` is `true` when the user or the password is missing.\n\nExample: Basic auth\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nRuns the `AUTH()` delegate for this request yourself.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` The request.\n\n`callback(err, user, isAuthorized)` gets the result of the delegate. Without a delegate `isAuthorized` is `false`. Useful for routes that do not use the authorization flags.\n\nExample: Check a user on a public route\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nRemoves the uploaded files of the request.\n\nReturns: `Request` The request.\n\nSame as `controller.clear()`.\n\nExample: Clear the files\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCreates a CSRF token for the request.\n\nReturns: `String` The token.\n\nSame as `controller.csrf()`; it uses `DEF.onCSRFcreate(req)`.\n\nExample: A token in middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nEncrypts the text answer of this request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `Request` The request.\n\nThe answer is encrypted with `CONF.secret_encryption` and gets the header `X-Encryption: a`. `controller.encrypt([enable])` does the same.\n\nExample: Encrypt one answer\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nCreates an absolute URL with the host of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | A path to add. |\n\nReturns: `String` The URL.\n\nThe protocol, the host name and the port of the request with `path` added. Same as `controller.hostname()`.\n\nExample: Absolute URL\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nDisables the HTTP cache of the answer.\n\nReturns: `Request` The request.\n\nIt calls `res.nocache()`.\n\nExample: In middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nThe controller of the request.\n\nReturns: `Controller`\n\nSet when a controller handles the request.\n\nExample: Example\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nTells whether the response was sent.\n\nReturns: `Boolean`\n\nIt is `true` after the framework answered the request.\n\nExample: Example\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nTurns off the compression of HTML and static files for this response.\n\nReturns: `Boolean`\n\nWith `true` the framework does not minify the HTML and the static files it sends.\n\nExample: Example\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nAnswers with an object as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The value. |\n\nReturns: `Response` The response.\n\nThe status comes from the response options (`200` by default).\n\nExample: JSON from a route with (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nAnswers with a body and a content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | The HTTP status. |\n| `body` | `String` | yes |  | The body. |\n| `type` | `String` | yes |  | The content type. |\n| `compress` | `Boolean` | no |  | Compression. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Response` The response.\n\nBodies over 4 kB are compressed with GZIP.\n\nExample: A CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nAnswers in the style of Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | The HTTP status. |\n| `body` | `String|Object|Number` | yes |  | The body. |\n| `type` | `String` | no |  | The content type. |\n\nReturns: `Response` The response.\n\nA string is `text/html`, a number is answered as the text of that status, an object is JSON and an `ErrorBuilder` is answered as its errors. It is meant for middleware written for Express.\n\nExample: Express style\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nAnswers with a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The data. |\n| `type` | `String` | yes |  | The content type. |\n| `encoding` | `String` | no |  | The encoding of the buffer. |\n| `download` | `String` | no |  | A file name to download. |\n| `headers` | `Object` | no |  | Extra response headers. |\n\nReturns: `Response` The response.\n\n`download` sets the file name of `Content-Disposition`.\n\nExample: A generated file\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nAnswers with a changed image without the cache of `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | The image. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs at the end. |\n\nReturns: `Response` The response.\n\nWorks like `res.image()`, but the result is created for every request.\n\nExample: Image with a timestamp\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nDisables the HTTP cache of the response.\n\nReturns: `Response` The response.\n\nIt removes `If-None-Match` and `If-Modified-Since` from the request and sets `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: In a route with (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nAnswers with the error page 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Response` The response.\n\nIt runs the route `#409` when you declared one.\n\nExample: Answer 409\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nAnswers with the error page 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description of the problem. |\n\nReturns: `Response` The response.\n\nIt runs the route `#501` when you declared one.\n\nExample: Answer 501\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Controller","summary":"Eigenschaften und Methoden des Controllers, des Objekts, das eine Anfrage beantwortet.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Eigenschaften und Methoden des Controllers, des Objekts, das eine Anfrage beantwortet.\n\nDer Controller ist `this` in jeder Aktion einer Route. Er enthält die Daten der Anfrage und die Methoden, die sie beantworten. Der Leitfaden [Controller](../../guides/controllers/) erklärt mit Beispielen, wie du ihn verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### controller.body\n\nType: `property`\n\nDer geparste Body der Anfrage.\n\nReturns: `Object`\n\nEin JSON- oder URL-kodierter Body wird in ein Objekt geparst. Werte eines Formulars sind Strings. Eine Route mit einem Schema ersetzt ihn durch das validierte Modell. Du kannst auch ein neues Objekt zuweisen.\n\nExample: Den Body lesen\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nDer Query-String der URL als Objekt.\n\nReturns: `Object`\n\nDie Werte sind Strings: `?page=2` ergibt `{ page: '2' }`. Das Objekt wird beim ersten Lesen geparst.\n\nExample: Paginierung\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nDie dynamischen Parameter der URL.\n\nReturns: `Object`\n\nJedes `{name}` der Route wird zu einem Schlüssel. Parameter, die mit einem Typ deklariert sind, werden konvertiert: `{id:number}` mit `parseInt()`, `{active:boolean}` mit `parseBoolean()` und `{date:date}` mit `parseDate()`. Dieselben Werte kommen als Argumente der Aktion an.\n\nExample: Typisierter Parameter\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nDie hochgeladenen Dateien.\n\nReturns: `Array`\n\nNur Routen mit dem Flag `upload` empfangen Dateien. Jede Datei hat `name` (das Formularfeld), `filename`, `type`, `size`, `extension`, `width` und `height` sowie die Methoden `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` und `isAudio()`. `move()`, `copy()` und `read()` geben ohne Callback ein Promise zurück. Die temporären Dateien werden entfernt, wenn die Anfrage endet, außer du rufst `controller.autoclear(false)` auf.\n\nExample: Einen Upload speichern\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nDer angemeldete Benutzer.\n\nReturns: `Object`\n\nDas Objekt, das dein `AUTH()`-Delegate an `$.success(user)` übergeben hat. Es ist `undefined`, wenn niemand angemeldet ist. Du kannst es zuweisen.\n\nExample: Profil\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nDie Header der Anfrage.\n\nReturns: `Object`\n\nDie Namen der Header sind kleingeschrieben.\n\nExample: Einen Header lesen\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nDie IP-Adresse des Clients.\n\nReturns: `String`\n\nHinter einem Proxy ist es die erste Adresse des Headers `X-Forwarded-For`, sonst die Adresse der Verbindung.\n\n### controller.url\n\nType: `property`\n\nDer Pfad der URL der Anfrage in Kleinbuchstaben.\n\nReturns: `String`\n\nEr hat keinen Query-String und endet immer mit `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true`, wenn der Client ein Mobilgerät ist.\n\nReturns: `Boolean`\n\nDas wird anhand des Headers `User-Agent` geprüft. Du kannst es zuweisen.\n\n### controller.xhr\n\nType: `property`\n\n`true`, wenn die Anfrage per XMLHttpRequest gesendet wurde.\n\nReturns: `Boolean`\n\nEs ist `true`, wenn die Anfrage den Header `X-Requested-With: XMLHttpRequest` hat.\n\n### controller.language\n\nType: `property`\n\nDie Sprache der Anfrage.\n\nReturns: `String`\n\nEs ist der Wert, den dein Lokalisierungs-Delegate (`DEF.onLocale`) zurückgibt. Views und `controller.mail()` übersetzen Texte damit.\n\n### controller.status\n\nType: `property`\n\nDer HTTP-Statuscode der Antwort.\n\nReturns: `Number`\n\nSetze ihn, bevor du antwortest. `json()`, `jsonstring()`, `plain()`, `content()` und `html()` verwenden ihn, und `200`, wenn er nicht gesetzt ist. `invalid()` verwendet für die Fehler einen Status über `399`.\n\nExample: Erstellt\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nEin Objekt, das sich die View und ihr Layout teilen.\n\nReturns: `Object`\n\nWerte, die du hier vor `view()` speicherst, sind in der View und im Layout als `repository` verfügbar. Auch der Seitentitel und die Meta-Tags werden darin gespeichert.\n\nExample: Einen Wert an das Layout übergeben\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nDas Problem einer Fehlerroute.\n\nReturns: `Error|String`\n\nIn einer Route für einen Fehlerstatus (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) enthält es das Problem, das an `throw404()`, `throw500()` und die anderen übergeben wurde.\n\n### controller.req\n\nType: `property`\n\nDas Request-Objekt des Frameworks.\n\nReturns: `Request`\n\nEs erweitert den Node.js-Request. Die Eigenschaften des Controllers wie `body`, `query` und `ip` lesen daraus.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nAntwortet mit einem als JSON serialisierten Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Der zu serialisierende Wert. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `beautify` | `Boolean` | no | `false` | Formatiert das JSON mit Einrückung. |\n| `replacer` | `Function` | no |  | Ein Replacer für `JSON.stringify()`. |\n\nReturns: `Controller` Der Controller.\n\nDer Content-Type ist `application/json`, und der Status ist `controller.status` oder `200`. Ein `ErrorBuilder` wird mit seinen Fehlern und seinem eigenen Status beantwortet. `beautify` kann das zweite Argument sein.\n\nExample: Ein Objekt\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Formatiert\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nAntwortet mit einem Text, der bereits JSON ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Der JSON-Text. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\nVerwende es, wenn du das JSON als String hast, zum Beispiel aus einem Cache. Der Text wird unverändert gesendet, mit dem Content-Type `application/json`.\n\nExample: Aus einem Cache\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nAntwortet mit reinem Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | Der Text. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\nDer Content-Type ist `text/plain`. Ein Objekt wird als formatiertes JSON serialisiert; `null` ergibt einen leeren Body.\n\nExample: Text\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nAntwortet mit HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das HTML. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\nDasselbe wie `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nAntwortet mit einem Text und deinem Content-Type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Der Inhalt. |\n| `type` | `String` | no | `text/plain` | Der Content-Type. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\nEin `ErrorBuilder` als `body` wird als JSON mit seinem eigenen Status beantwortet.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRendert eine View und antwortet damit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name der View ohne `.html`. |\n| `model` | `Object` | no |  | Das Modell, in der View als `model` verfügbar. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `partial` | `Boolean` | no | `false` | Gibt das HTML als String zurück und antwortet nicht. Es kann das dritte Argument sein. |\n\nReturns: `Controller|String` Der Controller, oder das HTML, wenn `partial` `true` ist.\n\nDie View ist eine Datei `name.html` in `views/`, gerendert innerhalb des Layouts (standardmäßig `layout`, siehe `controller.layout()`). Routen eines anderen Controllers als `default` suchen Views in `views/<controller name>/`. Das erste Zeichen des Namens ändert, wo die Datei gesucht wird:\n\n| Präfix | Wo |\n| --- | --- |\n| `~` | Die Wurzel von `views/` |\n| `#plugin/view` | Die Views eines Plugins |\n| `=theme/view` | Die Views eines Themes |\n| `@` | Ein Paket |\n\nOhne Namen wird die View nach dem letzten Teil der URL benannt (`index` für `/`). Ist `partial` auf `true` gesetzt, gibt die Methode das gerenderte HTML zurück, statt zu antworten.\n\nExample: Eine Seite\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: HTML als String\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nWählt das Layout für die nächste View.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Layout-View oder ein leerer String. |\n\nReturns: `Controller` Der Controller.\n\nDas Standardlayout ist `layout` (die Konfiguration `default_layout`). Ein leerer String rendert die View ohne Layout.\n\nExample: Ohne Layout\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nSetzt den Titel der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Titel. |\n\nReturns: `Controller` Der Controller.\n\nDas Layout gibt ihn mit `@{title}` aus. Der Text wird HTML-kodiert.\n\nExample: Titel\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nSetzt die Meta-Werte der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Der Titel. |\n| `description` | `String` | no |  | Die Beschreibung. |\n| `keywords` | `String|Array` | no |  | Die Schlüsselwörter. |\n| `image` | `String` | no |  | Die URL eines Bildes. |\n\nReturns: `Controller` Der Controller.\n\nDas Layout gibt sie mit `@{meta}` aus. `keywords` kann ein Array sein.\n\nExample: Meta-Tags\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nAntwortet mit einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die Datei in `public/`, oder `~` und ein absoluter Pfad. |\n| `download` | `String|Boolean` | no |  | Ein Name für die heruntergeladene Datei; `true` verwendet den Namen der Datei. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `callback` | `Function` | no |  | Läuft, wenn die Datei gesendet wurde. |\n\nReturns: `Controller` Der Controller.\n\nDie Datei wird aus `public/` gelesen. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad.\n\nExample: Download\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nAntwortet mit einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Die Daten. |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `encoding` | `String` | no |  | Eine Konvertierung der Daten. |\n| `download` | `String` | no |  | Ein Name für die heruntergeladene Datei. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\n`encoding` konvertiert den Buffer, bevor er gesendet wird (`binary`, `utf8`, `ascii`).\n\nExample: Ein Bild im Speicher\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nAntwortet mit einem lesbaren Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Ein lesbarer Stream. |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `download` | `String` | no |  | Ein Name für die heruntergeladene Datei. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `callback` | `Function` | no |  | Läuft, wenn der Stream gesendet wurde. |\n| `nocompress` | `Boolean` | no | `false` | Deaktiviert die Komprimierung. |\n\nReturns: `Controller` Der Controller.\n\nDie Antwort wird komprimiert, außer `nocompress` ist `true`. Die ersten beiden Argumente können vertauscht werden (`type`, `stream`).\n\nExample: Eine CSV-Datei\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nLeitet den Client auf eine andere URL weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Ziel-URL. |\n| `permanent` | `Boolean` | no | `false` | Sendet `301 Moved Permanently`. |\n\nReturns: `Controller` Der Controller.\n\nDer Status ist `302`, oder `301`, wenn `permanent` `true` ist.\n\nExample: Nach einem Formular\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nAntwortet mit einem leeren Body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | Zusätzliche Header oder ein Statuscode. |\n\nReturns: `Controller` Der Controller.\n\nEine Zahl anstelle der Header setzt den Statuscode. Für `204 No Content` kannst du auch `controller.nocontent([headers])` verwenden.\n\nExample: Akzeptiert\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nAntwortet mit dem JSON `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Der Wert von `success`. |\n| `value` | `Object` | no |  | Ein Wert, der als `value` hinzugefügt wird. |\n\nReturns: `Controller` Der Controller.\n\n`success(value)` antwortet mit `{ \"success\": true, \"value\": value }`. `success(false)` antwortet mit `{ \"success\": false }`.\n\nExample: Mit einem Wert\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nAntwortet mit einem Fehler als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | Ein Statuscode, der Name des Fehlers oder der Fehler. |\n| `error` | `String` | no |  | Der Text des Fehlers. |\n\nReturns: `ErrorBuilder` Der Builder mit den Fehlern.\n\nDie Fehler werden als JSON-Array mit dem Status `400` beantwortet (die Konfiguration `default_errorbuilder_status`). Eine Zahl als erstes Argument setzt den Status; ein `Error` oder ein `ErrorBuilder` wird unverändert beantwortet. Die Antwort wird im nächsten Tick gesendet, sodass du dem zurückgegebenen Builder noch Fehler hinzufügen kannst.\n\nExample: Validierung\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Ein anderer Status\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nErstellt einen Callback, der mit Erfolg oder einem Fehler antwortet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` fügt die Antwort als `value` hinzu; ein anderer Wert wird selbst als `value` hinzugefügt. |\n\nReturns: `Function` Ein Callback `(err, response)`.\n\nDer Callback hat die Form `(err, response)`. Bei einem Fehler ruft er `controller.invalid(err)` auf. Sonst antwortet er mit `{ \"success\": true }`; mit `done(true)` wird die Antwort als `value` hinzugefügt, und mit einem anderen Wert wird dieser Wert hinzugefügt.\n\nExample: Ein beliebiger Callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nErstellt einen Callback, der mit der Antwort als JSON oder mit einer View antwortet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | Der Name einer View. |\n\nReturns: `Function` Ein Callback `(err, data)`.\n\nDer Callback hat die Form `(err, data)`. Wenn `err` ein `ErrorBuilder` ist und du keine View übergeben hast, werden seine Fehler als JSON beantwortet. Jeder andere Fehler antwortet mit der Fehlerseite `404`, oder `500`, wenn der `ErrorBuilder` einen `Error` enthält. Ohne Fehler antwortet er mit `data` als JSON oder rendert die View mit `data` als Modell.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: Eine View\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems, in der Fehlerroute als `controller.exception` verfügbar. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#404` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Dieselbe Familie antwortet mit anderen Status: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` und `throw503()`. Jede hat einen Alias namens `view400()` … `view503()`. Es passiert nichts, wenn die Anfrage bereits beantwortet wurde.\n\nExample: Fehlender Datensatz\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: Deine eigene Seite\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems, in der Fehlerroute als `controller.exception` verfügbar. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#403` aus, wenn du eine deklariert hast. Alias: `view403()`.\n\nExample: Nur für Admins\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nProtokolliert einen Fehler und antwortet mit der Fehlerseite 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | Der Fehler. |\n\nReturns: `Controller` Der Controller.\n\nDer Fehler wird vom Framework protokolliert (`DEF.onError`). Danach läuft die Route `#500`, wenn du eine deklariert hast. Alias: `view500()`.\n\nExample: In einem Promise\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLiest ein Cookie der Anfrage oder schreibt ein Cookie in die Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Cookies. |\n| `value` | `String` | no |  | Der zu schreibende Wert. |\n| `expires` | `String` | no |  | Wann das Cookie abläuft, zum Beispiel `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` Beim Lesen der Wert, beim Schreiben der Controller.\n\nMit einem Argument gibt sie den Wert des Cookies zurück oder einen leeren String. Mit einem Wert fügt sie einen Header `Set-Cookie` hinzu. `expires` ist ein Text wie `'5 days'` oder `'2 hours'`; ein negativer Wert (`'-1 day'`) entfernt das Cookie. Statt `expires` kannst du das Optionsobjekt mit `expires` darin übergeben.\n\nOptionen: `domain`, `path` (Standard `/`), `secure` (Standard ist die Konfiguration `default_cookies_secure`), `httponly` und `samesite` (`Lax`, `Strict` oder `None`; Standard `Lax`, die Konfiguration `default_cookies_samesite`).\n\nExample: Schreiben und lesen\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Entfernen\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nSetzt einen Header der Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Headers. |\n| `value` | `String` | yes |  | Der Wert. |\n\nReturns: `Controller` Der Controller.\n\nExample: Ein Header\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nDeaktiviert den HTTP-Cache der Antwort.\n\nReturns: `Controller` Der Controller.\n\nExample: Frische Daten\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nErstellt ein CSRF-Token für die aktuelle Anfrage.\n\nReturns: `String` Das Token.\n\nRouten mit dem Flag `csrf` prüfen das Token aus dem Header `x-csrf-token` oder aus dem Argument `?csrf=` der URL. In Views ist dasselbe Token `@{csrf}`.\n\nExample: Das Token senden\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nBehält oder entfernt die hochgeladenen Dateien, wenn die Anfrage endet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` behält die Dateien. |\n\nReturns: `Controller` Der Controller.\n\n`autoclear(false)` behält die temporären Dateien von `controller.files` nach der Antwort, für Arbeit, die später weitergeht. `controller.clear()` entfernt sie sofort.\n\nExample: Später verarbeiten\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nSendet ein Server-Sent Event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | Die Daten des Events. |\n| `eventname` | `String` | no |  | Der Name des Events. |\n| `id` | `String` | no |  | Die ID des Events. |\n| `retry` | `Number` | no |  | Wie lange der Browser wartet, bevor er sich neu verbindet, in Millisekunden. |\n\nReturns: `Boolean` `false`, wenn das Event nicht gesendet werden kann (der Client hat die Verbindung getrennt oder die Anfrage wurde beantwortet).\n\nDer erste Aufruf antwortet mit den Headern von `text/event-stream` und hält die Verbindung offen. Ein Objekt wird als JSON serialisiert. Fehlt `retry`, verwendet der erste Aufruf das Timeout der Route. Die vorherige Event-ID, die der Browser gesendet hat, steht in `controller.sseID`. Der Stream endet mit `controller.close()`.\n\nExample: Eine Uhr\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nLeitet die Anfrage an eine andere URL weiter und antwortet mit deren Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | Die Ziel-URL oder die Optionen. |\n\nReturns: `undefined` Nichts.\n\nMethode, Body, Query-String und Header der Anfrage werden an das Ziel gesendet (außer `host`, `connection`, `accept-encoding` und den Headern `x-forwarded-*`). Status und Body der Antwort werden zurückgegeben. Bei einem Fehler ruft sie `controller.invalid(err)` auf.\n\nOptionen: `url` (Pflicht), `method`, `headers`, `timeout` (Standard `10000` ms) und `callback(err, response)`, der vor der Antwort läuft.\n\nExample: Eine API weiterleiten\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nLiest die Basic-Authentifizierung oder fordert sie beim Browser an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | Der Realm, den der Browser anzeigt. |\n\nReturns: `Object|null` Ohne Label die Anmeldedaten; mit Label `null`.\n\nOhne Argument gibt sie `{ user, password, empty }` aus dem Header `Authorization` zurück. Mit einem Label antwortet sie mit `401` und dem Header `WWW-Authenticate`, sodass der Browser einen Anmeldedialog anzeigt.\n\nExample: Eine geschützte Seite\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nGibt an, ob der Client noch verbunden ist.\n\nReturns: `Boolean`\n\nEs ist `false`, nachdem der Client die Verbindung geschlossen hat oder nach `controller.close()`. Prüfe es bei langen Arbeiten, bevor du antwortest.\n\nExample: Lange Arbeit\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nFür einen Controller immer `true`.\n\nReturns: `Boolean`\n\nNützlich, um in einer gemeinsamen Funktion einen Controller von einem `$`-Objekt zu unterscheiden.\n\nExample: Eine gemeinsame Funktion\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nGibt an, ob die Anfrage über HTTPS kam.\n\nReturns: `Boolean`\n\nEs ist `true`, wenn das Protokoll `https:` (oder `wss:`) ist. Hinter einem Proxy hängt es von der URL ab, die das Framework sieht. Dasselbe wie `req.secured`.\n\nExample: HTTPS erzwingen\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nDer Header `Referer` der Anfrage.\n\nReturns: `String`\n\nEin leerer String, wenn der Header fehlt.\n\nExample: Zurückgehen\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nGibt an, ob der User-Agent wie ein Bot aussieht.\n\nReturns: `Boolean`\n\nEs prüft den Header `User-Agent` auf Wörter wie `bot`, `crawler` und `spider`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nDer geparste User-Agent als kurzer Text mit Browser und System.\n\nReturns: `String`\n\nVerwende `req.useragent(true)` für ein Objekt mit Browser, Betriebssystem und Gerät. Dasselbe wie `req.ua`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nDie geparste URL der Anfrage.\n\nReturns: `Object`\n\nEin Objekt von `url.parse()` mit `pathname`, `query`, `hostname` und den anderen Teilen.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nDie Teile des Pfads der URL.\n\nReturns: `String[]`\n\n`/products/shoes/` ergibt `['products', 'shoes']`.\n\nExample: Beispiel\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nDie Subdomain der Anfrage als Array.\n\nReturns: `String[]`\n\n`shop.eu.example.com` ergibt `['shop', 'eu']`; `www` wird ignoriert. Ohne Subdomain ist es `null`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nDie ID der Session der Anfrage.\n\nReturns: `String`\n\nWird von deinem `AUTH()`-Delegate oder vom Session-Mechanismus gesetzt. Dasselbe wie `req.sessionid`.\n\nExample: Beispiel\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nDie ID des letzten Events, das der Browser empfangen hat.\n\nReturns: `String`\n\nDer Wert des Headers `Last-Event-ID`, den der Browser sendet, wenn er sich erneut mit einer Route für Server-Sent Events verbindet, oder `null`.\n\nExample: Beispiel\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nDie Route, auf die die Anfrage gepasst hat.\n\nReturns: `Object`\n\nEin internes Objekt des Frameworks mit URL, Flags, Schema und Optionen der Route. Lies es, ändere es nicht.\n\nExample: Beispiel\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nDie eigenen Optionen der Route.\n\nReturns: `Object`\n\nDas Objekt, das du `ROUTE()` als Optionen übergibst.\n\nExample: Beispiel\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nDie Flags der Route.\n\nReturns: `String[]`\n\nEin Array mit den Flags der Route, zum Beispiel `['get', 'json']`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nDer Name des Schemas der Route.\n\nReturns: `String`\n\nFür eine Route wie `POST /api/users/ *Users --> save` ist es `'Users'`. Ein leerer String, wenn die Route kein Schema hat.\n\nExample: Beispiel\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nDer Name des Controllers.\n\nReturns: `String`\n\nDer Name der Datei in `/controllers/` (ohne `.js`), die die Route deklariert hat.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nDie Breadcrumb des aktuellen Sitemap-Eintrags.\n\nReturns: `Object[]`\n\nDie von `controller.sitemap()` gesetzten Einträge; in Views steht dieselbe Liste in `@{sitemap}`.\n\nExample: Beispiel\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nAntwortet mit JSONP: einem Aufruf einer JavaScript-Funktion mit den Daten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der JavaScript-Funktion. |\n| `obj` | `Object` | yes |  | Die Daten. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `beautify` | `Boolean` | no | `false` | Formatiert das JSON. |\n| `replacer` | `Function` | no |  | Ein Replacer für `JSON.stringify()`. |\n\nReturns: `Controller` Der Controller.\n\nDer Body ist `name(json)` mit dem Content-Type `application/x-javascript`. Ohne `name` heißt die Funktion `callback`. Ein `ErrorBuilder` wird mit seinen Fehlern beantwortet.\n\nExample: Name aus dem Query-String\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#400` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Das Problem steht in `controller.exception` der Fehlerroute. Alias: `controller.view400()`.\n\nExample: Mit 400 antworten\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#401` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Das Problem steht in `controller.exception` der Fehlerroute. Alias: `controller.view401()`.\n\nExample: Mit 401 antworten\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#409` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Das Problem steht in `controller.exception` der Fehlerroute. Alias: `controller.view409()`.\n\nExample: Mit 409 antworten\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#501` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Das Problem steht in `controller.exception` der Fehlerroute. Alias: `controller.view501()`.\n\nExample: Mit 501 antworten\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Controller` Der Controller.\n\nSie führt die Route `#503` aus, wenn du eine deklariert hast; sonst rendert das Framework seine eigene Fehlerseite. Das Problem steht in `controller.exception` der Fehlerroute. Alias: `controller.view503()`.\n\nExample: Mit 503 antworten\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias von `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 400.\n\nExample: Dasselbe wie throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias von `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 401.\n\nExample: Dasselbe wie throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias von `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 403.\n\nExample: Dasselbe wie throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias von `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 404.\n\nExample: Dasselbe wie throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias von `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 409.\n\nExample: Dasselbe wie throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias von `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Der Fehler, vom Framework protokolliert. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 500.\n\nExample: Dasselbe wie throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias von `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 501.\n\nExample: Dasselbe wie throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias von `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Das Problem. |\n\nReturns: `Controller` Der Controller.\n\nSie antwortet auf dieselbe Weise mit der Fehlerseite 503.\n\nExample: Dasselbe wie throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nAntwortet mit `204 No Content` ohne Body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Controller` Der Controller.\n\nExample: Nichts zu antworten\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nSchließt die Verbindung ohne Antwort.\n\nReturns: `Controller` Der Controller.\n\nDer Socket wird zerstört. Es passiert nichts, wenn die Anfrage bereits beantwortet wurde.\n\nExample: Eine Anfrage verwerfen\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nBeendet die Antwort, meist einen Stream von Server-Sent Events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Ruft `res.end()` auf. |\n\nReturns: `Controller` Der Controller.\n\nSie beendet die Antwort von `controller.sse()` und markiert den Controller als getrennt. Ist `end` auf `false` gesetzt, wird die Antwort nur als beendet markiert.\n\nExample: Einen Stream stoppen\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nMarkiert den Controller als abgebrochen.\n\nReturns: `Controller` Der Controller.\n\nSie setzt `controller.isCanceled` auf `true`. In einem Handler von `ON('controller')` aufgerufen, verhindert sie, dass die Aktion der Route läuft; der Handler muss dann selbst antworten.\n\nExample: Anfragen während der Wartung stoppen\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nEntfernt die hochgeladenen Dateien der Anfrage sofort.\n\nReturns: `Controller` Der Controller.\n\nDie temporären Dateien von `controller.files` werden gelöscht, und `body`, `query` und die Cookies der Anfrage werden geleert.\n\nExample: Nach der Arbeit\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nLässt dich selbst mit der Node.js-Response antworten.\n\nReturns: `Boolean` `true`, wenn du antworten kannst.\n\nDas Framework markiert die Anfrage als beantwortet und wartet nicht mehr auf sie. Schreibe dann mit `writeHead()` und `end()` in `controller.res`. Sie gibt `false` zurück, wenn die Anfrage bereits beantwortet wurde.\n\nExample: Die Response schreiben\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nProtokolliert einen Fehler mit dem Namen des Controllers und der URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Der Fehler. |\n\nReturns: `Controller` Der Controller.\n\nDer Fehler geht an `F.error()` und an `controller.exception`; die Anfrage wird nicht beantwortet. Ein `ErrorBuilder` wird stattdessen als JSON beantwortet.\n\nExample: Protokollieren und weitermachen\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nErstellt einen Callback, der den Fehler beantwortet und nur das Ergebnis weitergibt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Läuft bei Erfolg mit den Ergebnissen. |\n\nReturns: `Function` Ein Callback `(err, a, b, c)`.\n\nDie zurückgegebene Funktion hat die Form `(err, a, b, c)`. Bei einem Fehler ruft sie `controller.invalid(err)` auf; sonst ruft sie `callback(a, b, c)` mit dem Controller als `this` auf.\n\nExample: Nur der Erfolgsfall\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nErstellt eine absolute URL mit dem Host der Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein anzuhängender Pfad. |\n\nReturns: `String` Die URL, zum Beispiel `https://example.com/products/`.\n\nProtokoll, Hostname und Port der Anfrage, mit angehängtem `path`.\n\nExample: Ein Link für eine E-Mail\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nAntwortet mit einem Bild, das der Bildprozessor verändert hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Das Bild. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `callback` | `Function` | no |  | Läuft, wenn die Antwort endet. |\n\nReturns: `Controller` Der Controller.\n\n`filename` ist eine Datei in `/public/` (oder ein vollständiger Pfad mit vorangestelltem `~`) oder ein Stream. `make(image)` verändert das Bild mit den Methoden von `Image` (`resize()`, `quality()`, ...). Das Ergebnis wird in `/tmp/` zwischengespeichert. Es benötigt GraphicsMagick oder ImageMagick.\n\nExample: Ein Vorschaubild\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nSpeichert die ganze Antwort einer Aktion im Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel im Cache. |\n| `expire` | `String|Date` | yes |  | Wie lange, zum Beispiel `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` überspringt den Cache. |\n| `fn` | `Function` | yes |  | Erstellt die Antwort; läuft mit dem Controller als `this`. |\n| `fnFrom` | `Function` | no |  | Läuft vor einer Antwort aus dem Cache. |\n\nReturns: `Controller` Der Controller.\n\nDer erste Aufruf führt `fn` aus und speichert die Antwort (eine View, JSON oder Text) unter `key` für die Dauer `expire`. Spätere Aufrufe antworten aus dem Cache, und `fnFrom` läuft davor. Ist `disabled` auf `true` gesetzt, wird der Cache übersprungen. Das Theme wird dem Schlüssel hinzugefügt.\n\nExample: Die Startseite cachen\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nSetzt die Meta-Beschreibung der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die Beschreibung. |\n\nReturns: `Controller` Der Controller.\n\nIm Layout wird sie von `@{meta}` ausgegeben. `controller.keywords()` setzt auf dieselbe Weise die Schlüsselwörter und `controller.author()` den Autor.\n\nExample: Meta-Tags\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nSetzt die Meta-Schlüsselwörter der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Die Schlüsselwörter. |\n\nReturns: `Controller` Der Controller.\n\nEin Array wird mit Kommas verbunden. Im Layout werden sie von `@{meta}` ausgegeben.\n\nExample: Schlüsselwörter\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nFügt Tags in den Head des Layouts ein oder liest sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Ein Dateiname oder ein HTML-Tag. |\n\nReturns: `Controller|String` Der Controller, oder ohne Argumente das HTML.\n\nEine `.css`-Datei wird zu einem `<link>` und eine `.js`-Datei zu einem `<script>`; relative Namen verweisen auf `/public/css/` und `/public/js/`. Ein Wert, der mit `<` beginnt, wird unverändert eingefügt. Jeder Wert wird nur einmal eingefügt. Ohne Argumente gibt sie das HTML zurück; im Layout verwendest du `@{head}`.\n\nExample: Dateien für eine Seite\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nFügt Inhalt an einer benannten Stelle des Layouts ein oder liest ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Stelle. |\n| `value` | `String` | no |  | Der Inhalt. |\n\nReturns: `Controller|String` Der Controller, oder nur mit `name` der Inhalt.\n\nEin `.js`-Wert wird zu einem `<script>` und ein `.css`-Wert zu einem `<link>`; andere Werte werden unverändert eingefügt. Im Layout verwendest du `@{place('name')}`.\n\nExample: Skripte am Ende der Seite\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nSetzt das Theme der Views dieser Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Themes. |\n\nReturns: `Controller` Der Controller.\n\nViews, Layouts und statische Dateien werden dann zuerst in `/themes/{name}/` gesucht. Der Standard kommt aus `CONF.default_theme`.\n\nExample: Ein Theme pro Kunde\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nRendert eine Komponente zu HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Komponente. |\n| `settings` | `Object` | no |  | Die Einstellungen der Komponente. |\n| `model` | `Object` | no |  | Das Modell; standardmäßig das Modell der View. |\n\nReturns: `String` Das HTML, oder für eine unbekannte Komponente ein leerer String.\n\nDie Komponente ist eine Datei in `/components/`. Ihr CSS und JS werden in den Head des Layouts eingefügt. In Views verwendest du `@{component('name')}`.\n\nExample: HTML einer Komponente\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nFührt einen View-Helfer aus `DEF.helpers` aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Helfers. |\n| `arg` | `Object` | no |  | Argumente für den Helfer. |\n\nReturns: `String` Die Ausgabe des Helfers.\n\nDer Helfer läuft mit dem Controller als `this`. Ein unbekannter Helfer gibt einen leeren String zurück.\n\nExample: Einen Helfer in einer Aktion verwenden\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nErstellt die URL einer Datei in `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n| `path` | `String` | no |  | Ein Pfad, der mit einer relativen URL verbunden wird. |\n\nReturns: `String` Die URL.\n\nSie berücksichtigt die Einstellungen für statische URLs und das Theme. Die Familie `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` und `public_download()` macht dasselbe für ihr eigenes Verzeichnis.\n\nExample: Eine URL in JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `js`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n| `tag` | `Boolean` | no | `false` | Gibt ein HTML-Tag zurück. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_script`, Standard `/js/`). Ist `tag` auf `true` gesetzt, gibt sie das HTML-Tag zurück (`<script>` oder `<link>`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `css`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n| `tag` | `Boolean` | no | `false` | Gibt ein HTML-Tag zurück. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_style`, Standard `/css/`). Ist `tag` auf `true` gesetzt, gibt sie das HTML-Tag zurück (`<script>` oder `<link>`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `img`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_image`, Standard `/img/`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `videos`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_video`, Standard `/videos/`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `fonts`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_font`, Standard `/fonts/`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nErstellt die URL einer Datei im öffentlichen Verzeichnis `download`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datei. |\n\nReturns: `String` Die URL.\n\nDas Verzeichnis kommt aus der Konfiguration (`static_url_download`, Standard `/download/`).\n\nExample: URL einer Datei\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nFügt den Tests des Frameworks einen Test einer Route hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die zu testende Route. |\n| `name` | `String` | no |  | Der Name des Tests. |\n| `callback` | `Function` | no |  | `function(result)`, die bei Erfolg `true` zurückgibt. |\n\nReturns: `Object` Der Test.\n\nDie Tests eines Controllers laufen nacheinander. `url` ist eine Route wie `'GET /api/products/'` oder `'API /api/ products_query'` (dann ist der Name des Tests die Operation). `callback(result)` erhält `{ err, value, response, name }` und gibt `true` zurück, wenn der Test bestanden ist; ohne ihn ist ein Test bestanden, wenn kein Fehler auftritt.\n\nExample: Routen aus einer Route testen\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nDer Header `Host` der Anfrage.\n\nReturns: `String`\n\nDer Hostname mit dem Port, zum Beispiel `example.com:8000`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nGibt an, ob die Anfrage über HTTPS kam.\n\nReturns: `Boolean`\n\nEs ist `true`, wenn das Protokoll `https:` oder `wss:` ist.\n\nExample: Beispiel\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nDas Ergebnis der Autorisierung.\n\nReturns: `Boolean`\n\nEs ist `true`, bis dein `AUTH()`-Delegate läuft; danach ist es `true`, wenn das Delegate den Benutzer akzeptiert hat, und `false`, wenn es ihn abgelehnt hat.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nGibt an, ob die Anfrage eine statische Datei anfordert.\n\nReturns: `Boolean`\n\nEs ist `true`, wenn die URL eine Dateiendung hat und statische Dateien erlaubt sind. Nützlich in `DEF.onLocale` und in Middleware.\n\nExample: Beispiel\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nGibt an, ob die Anfrage von JavaScript kam.\n\nReturns: `Boolean`\n\nEs ist `true`, wenn der Header `X-Requested-With` den Wert `XMLHttpRequest` hat.\n\nExample: Beispiel\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nDie IP-Adresse des Clients.\n\nReturns: `String`\n\nHinter einem Proxy ist es die erste Adresse von `X-Forwarded-For`. Sie kann gesetzt werden.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nDie geparste URL der Anfrage.\n\nReturns: `Object`\n\nEin Objekt von `url.parse()` mit `pathname`, `query`, `hostname` und `port`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nDie Teile des Pfads in Kleinbuchstaben.\n\nReturns: `String[]`\n\n`/Products/Shoes/` ergibt `['products', 'shoes']`. `req.split` behält die ursprüngliche Groß- und Kleinschreibung.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nDie Teile des Pfads der URL.\n\nReturns: `String[]`\n\nDie Teile so, wie sie in der URL standen. Dasselbe wie `controller.split`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nDie Subdomain als Array oder `null`.\n\nReturns: `String[]`\n\n`www` wird ignoriert. `a.localhost` ergibt `['a']`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nGibt an, ob der User-Agent ein Mobilgerät ist.\n\nReturns: `Boolean`\n\nEs prüft den Header `User-Agent`. Es kann gesetzt werden.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nGibt an, ob der User-Agent wie ein Bot aussieht.\n\nReturns: `Boolean`\n\nEs prüft den Header `User-Agent`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nDer geparste User-Agent als kurzer Text mit Browser und System.\n\nReturns: `String`\n\nDasselbe wie `req.useragent()`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nDer Query-String als Objekt.\n\nReturns: `Object`\n\nEr wird beim ersten Lesen geparst und kann gesetzt werden.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nDer geparste Body der Anfrage.\n\nReturns: `Object`\n\nEin JSON- oder Formular-Body. Dasselbe wie `controller.body`.\n\nExample: Beispiel\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nDie hochgeladenen Dateien.\n\nReturns: `HttpFile[]`\n\nEin Array von `HttpFile`-Objekten für Routen mit dem Flag `upload`. Dasselbe wie `controller.files`.\n\nExample: Beispiel\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nDer vom `AUTH()`-Delegate akzeptierte Benutzer oder `null`.\n\nReturns: `Object`\n\nDasselbe wie `controller.user`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nDas Session-Objekt der Anfrage oder `null`.\n\nReturns: `Object`\n\nWird von deinem `AUTH()`-Delegate oder vom Session-Mechanismus gesetzt. Dasselbe wie `controller.session`.\n\nExample: Beispiel\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nParst den Header `User-Agent`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Gibt ein Objekt zurück. |\n\nReturns: `String|Object` Der User-Agent.\n\nOhne Argument gibt sie einen kurzen Text mit den im Header gefundenen Namen zurück, etwa Browser und System. Mit `true` gibt sie `{ os, browser, device }` zurück, wobei `device` `desktop`, `mobile`, `tablet` oder `tv` ist. Das Ergebnis wird an der Anfrage zwischengespeichert.\n\nExample: Details des Geräts\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nLiest ein Cookie der Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Cookies. |\n\nReturns: `String` Der Wert.\n\nDer Wert wird dekodiert. Ein fehlendes Cookie ergibt einen leeren String. `controller.cookie(name)` macht dasselbe.\n\nExample: Ein Cookie in Middleware lesen\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nLiest den Header der Basic-Autorisierung.\n\nReturns: `Object` `{ user, password, empty }`.\n\nSie dekodiert `Authorization: Basic ...` zu `{ user, password, empty }`. `empty` ist `true`, wenn der Benutzer oder das Passwort fehlt.\n\nExample: Basic-Auth\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nFührt das `AUTH()`-Delegate für diese Anfrage selbst aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` Die Anfrage.\n\n`callback(err, user, isAuthorized)` erhält das Ergebnis des Delegates. Ohne Delegate ist `isAuthorized` `false`. Nützlich für Routen, die die Autorisierungs-Flags nicht verwenden.\n\nExample: Einen Benutzer auf einer öffentlichen Route prüfen\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nEntfernt die hochgeladenen Dateien der Anfrage.\n\nReturns: `Request` Die Anfrage.\n\nDasselbe wie `controller.clear()`.\n\nExample: Die Dateien entfernen\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nErstellt ein CSRF-Token für die Anfrage.\n\nReturns: `String` Das Token.\n\nDasselbe wie `controller.csrf()`; sie verwendet `DEF.onCSRFcreate(req)`.\n\nExample: Ein Token in Middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nVerschlüsselt die Textantwort dieser Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` schaltet es aus. |\n\nReturns: `Request` Die Anfrage.\n\nDie Antwort wird mit `CONF.secret_encryption` verschlüsselt und erhält den Header `X-Encryption: a`. `controller.encrypt([enable])` macht dasselbe.\n\nExample: Eine Antwort verschlüsseln\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nErstellt eine absolute URL mit dem Host der Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Ein anzuhängender Pfad. |\n\nReturns: `String` Die URL.\n\nProtokoll, Hostname und Port der Anfrage, mit angehängtem `path`. Dasselbe wie `controller.hostname()`.\n\nExample: Absolute URL\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nDeaktiviert den HTTP-Cache der Antwort.\n\nReturns: `Request` Die Anfrage.\n\nSie ruft `res.nocache()` auf.\n\nExample: In Middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nDer Controller der Anfrage.\n\nReturns: `Controller`\n\nWird gesetzt, wenn ein Controller die Anfrage verarbeitet.\n\nExample: Beispiel\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nGibt an, ob die Antwort gesendet wurde.\n\nReturns: `Boolean`\n\nEs ist `true`, nachdem das Framework die Anfrage beantwortet hat.\n\nExample: Beispiel\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nSchaltet die Komprimierung von HTML und statischen Dateien für diese Antwort aus.\n\nReturns: `Boolean`\n\nMit `true` minifiziert das Framework das HTML und die statischen Dateien, die es sendet, nicht.\n\nExample: Beispiel\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nAntwortet mit einem Objekt als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Der Wert. |\n\nReturns: `Response` Die Antwort.\n\nDer Status kommt aus den Optionen der Antwort (standardmäßig `200`).\n\nExample: JSON aus einer Route mit (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nAntwortet mit einem Body und einem Content-Type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Der HTTP-Status. |\n| `body` | `String` | yes |  | Der Body. |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `compress` | `Boolean` | no |  | Komprimierung. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Response` Die Antwort.\n\nBodys über 4 kB werden mit GZIP komprimiert.\n\nExample: Eine CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nAntwortet im Stil von Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | Der HTTP-Status. |\n| `body` | `String|Object|Number` | yes |  | Der Body. |\n| `type` | `String` | no |  | Der Content-Type. |\n\nReturns: `Response` Die Antwort.\n\nEin String ist `text/html`, eine Zahl wird mit dem Text dieses Status beantwortet, ein Objekt ist JSON, und ein `ErrorBuilder` wird mit seinen Fehlern beantwortet. Das ist für Middleware gedacht, die für Express geschrieben wurde.\n\nExample: Express-Stil\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nAntwortet mit einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Die Daten. |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `encoding` | `String` | no |  | Die Kodierung des Buffers. |\n| `download` | `String` | no |  | Ein Dateiname zum Herunterladen. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n\nReturns: `Response` Die Antwort.\n\n`download` setzt den Dateinamen von `Content-Disposition`.\n\nExample: Eine generierte Datei\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nAntwortet mit einem veränderten Bild ohne den Cache in `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | Das Bild. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Zusätzliche Header der Antwort. |\n| `callback` | `Function` | no |  | Läuft am Ende. |\n\nReturns: `Response` Die Antwort.\n\nFunktioniert wie `res.image()`, aber das Ergebnis wird bei jeder Anfrage neu erstellt.\n\nExample: Bild mit einem Zeitstempel\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nDeaktiviert den HTTP-Cache der Antwort.\n\nReturns: `Response` Die Antwort.\n\nSie entfernt `If-None-Match` und `If-Modified-Since` aus der Anfrage und setzt `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: In einer Route mit (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Response` Die Antwort.\n\nSie führt die Route `#409` aus, wenn du eine deklariert hast.\n\nExample: Mit 409 antworten\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nAntwortet mit der Fehlerseite 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung des Problems. |\n\nReturns: `Response` Die Antwort.\n\nSie führt die Route `#501` aus, wenn du eine deklariert hast.\n\nExample: Mit 501 antworten\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Controller","summary":"Propiedades y métodos del controlador, el objeto que responde a una petición.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Propiedades y métodos del controlador, el objeto que responde a una petición.\n\nEl controlador es `this` dentro de cada acción de una ruta. Contiene los datos de la petición y los métodos que la responden. La guía [Controladores](../../guides/controllers/) explica cómo usarlo con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### controller.body\n\nType: `property`\n\nEl cuerpo de la petición ya procesado.\n\nReturns: `Object`\n\nUn cuerpo JSON o URL-encoded se convierte en un objeto. Los valores de un formulario son strings. Una ruta con un esquema lo reemplaza por el modelo validado. También puedes asignar un objeto nuevo.\n\nExample: Leer el cuerpo\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nLa query string de la URL como objeto.\n\nReturns: `Object`\n\nLos valores son strings: `?page=2` da `{ page: '2' }`. El objeto se procesa la primera vez que lo lees.\n\nExample: Paginación\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nLos parámetros dinámicos de la URL.\n\nReturns: `Object`\n\nCada `{name}` de la ruta se convierte en una clave. Los parámetros declarados con un tipo se convierten: `{id:number}` con `parseInt()`, `{active:boolean}` con `parseBoolean()` y `{date:date}` con `parseDate()`. Los mismos valores llegan como argumentos de la acción.\n\nExample: Parámetro con tipo\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nLos archivos subidos.\n\nReturns: `Array`\n\nSolo las rutas con el flag `upload` reciben archivos. Cada archivo tiene `name` (el campo del formulario), `filename`, `type`, `size`, `extension`, `width` y `height`, y los métodos `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` e `isAudio()`. `move()`, `copy()` y `read()` devuelven una promesa sin callback. Los archivos temporales se eliminan cuando termina la petición, salvo que llames a `controller.autoclear(false)`.\n\nExample: Guardar un archivo subido\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nEl usuario autenticado.\n\nReturns: `Object`\n\nEl objeto que tu delegado `AUTH()` pasó a `$.success(user)`. Es `undefined` cuando nadie ha iniciado sesión. Puedes asignarlo.\n\nExample: Perfil\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nLas cabeceras de la petición.\n\nReturns: `Object`\n\nLos nombres de las cabeceras están en minúsculas.\n\nExample: Leer una cabecera\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nLa dirección IP del cliente.\n\nReturns: `String`\n\nDetrás de un proxy es la primera dirección de la cabecera `X-Forwarded-For`; si no, la dirección de la conexión.\n\n### controller.url\n\nType: `property`\n\nLa ruta de la URL de la petición en minúsculas.\n\nReturns: `String`\n\nNo tiene query string y siempre termina en `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true` cuando el cliente es un dispositivo móvil.\n\nReturns: `Boolean`\n\nSe comprueba en la cabecera `User-Agent`. Puedes asignarlo.\n\n### controller.xhr\n\nType: `property`\n\n`true` cuando la petición se envió con XMLHttpRequest.\n\nReturns: `Boolean`\n\nEs `true` cuando la petición tiene la cabecera `X-Requested-With: XMLHttpRequest`.\n\n### controller.language\n\nType: `property`\n\nEl idioma de la petición.\n\nReturns: `String`\n\nEs el valor que devuelve tu delegado de localización (`DEF.onLocale`). Las vistas y `controller.mail()` traducen los textos con él.\n\n### controller.status\n\nType: `property`\n\nEl código de estado HTTP de la respuesta.\n\nReturns: `Number`\n\nEstablécelo antes de responder. `json()`, `jsonstring()`, `plain()`, `content()` y `html()` lo usan, y `200` cuando no está establecido. `invalid()` usa un estado mayor que `399` para los errores.\n\nExample: Creado\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn objeto compartido por la vista y su plantilla.\n\nReturns: `Object`\n\nLos valores que guardas aquí antes de `view()` están disponibles en la vista y en la plantilla como `repository`. El título de la página y las etiquetas meta también se guardan aquí.\n\nExample: Pasar un valor a la plantilla\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nEl problema de una ruta de error.\n\nReturns: `Error|String`\n\nEn una ruta para un estado de error (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) contiene el problema pasado a `throw404()`, `throw500()` y los demás.\n\n### controller.req\n\nType: `property`\n\nEl objeto de petición del framework.\n\nReturns: `Request`\n\nExtiende la petición de Node.js. Las propiedades del controlador como `body`, `query` e `ip` leen de él.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nResponde con un objeto serializado como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El valor a serializar. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `beautify` | `Boolean` | no | `false` | Formatea el JSON con sangría. |\n| `replacer` | `Function` | no |  | Un replacer para `JSON.stringify()`. |\n\nReturns: `Controller` El controlador.\n\nEl tipo de contenido es `application/json` y el estado es `controller.status` o `200`. Un `ErrorBuilder` se responde como sus errores con su propio estado. `beautify` puede ser el segundo argumento.\n\nExample: Un objeto\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Formateado\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nResponde con un texto que ya es JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | El texto JSON. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\nÚsalo cuando tienes el JSON como string, por ejemplo de una caché. El texto se envía tal cual, con el tipo de contenido `application/json`.\n\nExample: Desde una caché\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nResponde con texto plano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | El texto. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\nEl tipo de contenido es `text/plain`. Un objeto se serializa como JSON formateado; `null` da un cuerpo vacío.\n\nExample: Texto\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nResponde con HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | El HTML. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\nLo mismo que `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nResponde con un texto y tu tipo de contenido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | El contenido. |\n| `type` | `String` | no | `text/plain` | El tipo de contenido. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\nUn `ErrorBuilder` como `body` se responde como JSON con su propio estado.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenderiza una vista y responde con ella.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre de la vista sin `.html`. |\n| `model` | `Object` | no |  | El modelo, disponible en la vista como `model`. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `partial` | `Boolean` | no | `false` | Devuelve el HTML como string y no responde. Puede ser el tercer argumento. |\n\nReturns: `Controller|String` El controlador, o el HTML cuando `partial` es `true`.\n\nLa vista es un archivo `name.html` en `views/`, renderizado dentro de la plantilla (`layout` por defecto, consulta `controller.layout()`). Las rutas de un controlador distinto de `default` buscan las vistas en `views/<controller name>/`. El primer carácter del nombre cambia dónde se busca el archivo:\n\n| Prefijo | Dónde |\n| --- | --- |\n| `~` | La raíz de `views/` |\n| `#plugin/view` | Las vistas de un plugin |\n| `=theme/view` | Las vistas de un tema |\n| `@` | Un paquete |\n\nSin nombre, la vista toma el nombre de la última parte de la URL (`index` para `/`). Con `partial` a `true`, el método devuelve el HTML renderizado en lugar de responder.\n\nExample: Una página\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: HTML como string\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nElige la plantilla para la siguiente vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la vista de la plantilla, o un string vacío. |\n\nReturns: `Controller` El controlador.\n\nLa plantilla por defecto es `layout` (la configuración `default_layout`). Un string vacío renderiza la vista sin plantilla.\n\nExample: Sin plantilla\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nEstablece el título de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El título. |\n\nReturns: `Controller` El controlador.\n\nLa plantilla lo imprime con `@{title}`. El texto se codifica como HTML.\n\nExample: Título\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nEstablece los valores meta de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | El título. |\n| `description` | `String` | no |  | La descripción. |\n| `keywords` | `String|Array` | no |  | Las palabras clave. |\n| `image` | `String` | no |  | La URL de una imagen. |\n\nReturns: `Controller` El controlador.\n\nLa plantilla los imprime con `@{meta}`. `keywords` puede ser un array.\n\nExample: Etiquetas meta\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nResponde con un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo en `public/`, o `~` y una ruta absoluta. |\n| `download` | `String|Boolean` | no |  | Un nombre para el archivo descargado; `true` usa el nombre del archivo. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `callback` | `Function` | no |  | Se ejecuta cuando se envía el archivo. |\n\nReturns: `Controller` El controlador.\n\nEl archivo se lee de `public/`. Un nombre que empieza por `~` es una ruta absoluta.\n\nExample: Descarga\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nResponde con un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Los datos. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n| `encoding` | `String` | no |  | Una conversión de los datos. |\n| `download` | `String` | no |  | Un nombre para el archivo descargado. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\n`encoding` convierte el buffer antes de enviarlo (`binary`, `utf8`, `ascii`).\n\nExample: Una imagen en memoria\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nResponde con un stream legible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un stream legible. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n| `download` | `String` | no |  | Un nombre para el archivo descargado. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `callback` | `Function` | no |  | Se ejecuta cuando se envía el stream. |\n| `nocompress` | `Boolean` | no | `false` | Desactiva la compresión. |\n\nReturns: `Controller` El controlador.\n\nLa respuesta se comprime salvo que `nocompress` sea `true`. Los dos primeros argumentos se pueden intercambiar (`type`, `stream`).\n\nExample: Un archivo CSV\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nRedirige al cliente a otra URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de destino. |\n| `permanent` | `Boolean` | no | `false` | Envía `301 Moved Permanently`. |\n\nReturns: `Controller` El controlador.\n\nEl estado es `302`, o `301` cuando `permanent` es `true`.\n\nExample: Después de un formulario\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nResponde con un cuerpo vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | Cabeceras adicionales, o un código de estado. |\n\nReturns: `Controller` El controlador.\n\nUn número en lugar de las cabeceras establece el código de estado. Para `204 No Content` también puedes usar `controller.nocontent([headers])`.\n\nExample: Aceptado\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nResponde con el JSON `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | El valor de `success`. |\n| `value` | `Object` | no |  | Un valor añadido como `value`. |\n\nReturns: `Controller` El controlador.\n\n`success(value)` responde `{ \"success\": true, \"value\": value }`. `success(false)` responde `{ \"success\": false }`.\n\nExample: Con un valor\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nResponde con un error como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | Un código de estado, el nombre del error o el error. |\n| `error` | `String` | no |  | El texto del error. |\n\nReturns: `ErrorBuilder` El builder con los errores.\n\nLos errores se responden como un array JSON con el estado `400` (la configuración `default_errorbuilder_status`). Un número como primer argumento establece el estado; un `Error` o un `ErrorBuilder` se responde tal cual. La respuesta se envía en el siguiente tick, así que aún puedes añadir errores al builder devuelto.\n\nExample: Validación\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Otro estado\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nCrea un callback que responde con éxito o con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` añade la respuesta como `value`; otro valor se añade él mismo como `value`. |\n\nReturns: `Function` Un callback `(err, response)`.\n\nEl callback tiene la forma `(err, response)`. Si hay error, llama a `controller.invalid(err)`. Si no, responde `{ \"success\": true }`; con `done(true)` la respuesta se añade como `value`, y con otro valor se añade ese valor.\n\nExample: Cualquier callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nCrea un callback que responde con la respuesta como JSON o con una vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | El nombre de una vista. |\n\nReturns: `Function` Un callback `(err, data)`.\n\nEl callback tiene la forma `(err, data)`. Cuando `err` es un `ErrorBuilder` y no pasaste una vista, sus errores se responden como JSON. Cualquier otro error responde con la página de error `404`, o `500` cuando el `ErrorBuilder` contiene un `Error`. Sin error, responde `data` como JSON, o renderiza la vista con `data` como modelo.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: Una vista\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nResponde con la página de error 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema, disponible en la ruta de error como `controller.exception`. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#404` si la declaraste; si no, el framework renderiza su propia página de error. La misma familia responde otros estados: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` y `throw503()`. Cada uno tiene un alias llamado `view400()` … `view503()`. No pasa nada si la petición ya fue respondida.\n\nExample: Registro inexistente\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: Tu propia página\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nResponde con la página de error 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema, disponible en la ruta de error como `controller.exception`. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#403` si la declaraste. Alias: `view403()`.\n\nExample: Solo para administradores\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nRegistra un error y responde con la página de error 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | El error. |\n\nReturns: `Controller` El controlador.\n\nEl framework registra el error (`DEF.onError`). Después se ejecuta la ruta `#500` si la declaraste. Alias: `view500()`.\n\nExample: En una promesa\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLee una cookie de la petición o escribe una cookie en la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cookie. |\n| `value` | `String` | no |  | El valor a escribir. |\n| `expires` | `String` | no |  | Cuándo expira la cookie, por ejemplo `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` El valor al leer, el controlador al escribir.\n\nCon un argumento devuelve el valor de la cookie, o un string vacío. Con un valor añade una cabecera `Set-Cookie`. `expires` es un texto como `'5 days'` o `'2 hours'`; uno negativo (`'-1 day'`) elimina la cookie. En lugar de `expires` puedes pasar el objeto de opciones con `expires` dentro.\n\nOpciones: `domain`, `path` (por defecto `/`), `secure` (por defecto la configuración `default_cookies_secure`), `httponly` y `samesite` (`Lax`, `Strict` o `None`; por defecto `Lax`, la configuración `default_cookies_samesite`).\n\nExample: Escribir y leer\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Eliminar\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nEstablece una cabecera de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cabecera. |\n| `value` | `String` | yes |  | El valor. |\n\nReturns: `Controller` El controlador.\n\nExample: Una cabecera\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nDesactiva la caché HTTP de la respuesta.\n\nReturns: `Controller` El controlador.\n\nExample: Datos frescos\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrea un token CSRF para la petición actual.\n\nReturns: `String` El token.\n\nLas rutas con el flag `csrf` verifican el token de la cabecera `x-csrf-token` o del argumento `?csrf=` de la URL. En las vistas, el mismo token es `@{csrf}`.\n\nExample: Enviar el token\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nConserva o elimina los archivos subidos cuando termina la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` conserva los archivos. |\n\nReturns: `Controller` El controlador.\n\n`autoclear(false)` conserva los archivos temporales de `controller.files` después de la respuesta, para trabajo que continúa más tarde. `controller.clear()` los elimina de inmediato.\n\nExample: Procesar más tarde\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nEnvía un evento server-sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | Los datos del evento. |\n| `eventname` | `String` | no |  | El nombre del evento. |\n| `id` | `String` | no |  | El ID del evento. |\n| `retry` | `Number` | no |  | Cuánto espera el navegador antes de reconectar, en milisegundos. |\n\nReturns: `Boolean` `false` cuando el evento no se puede enviar (el cliente se desconectó o la petición ya fue respondida).\n\nLa primera llamada responde con las cabeceras de `text/event-stream` y mantiene la conexión abierta. Un objeto se serializa como JSON. Cuando falta `retry`, la primera llamada usa el tiempo de espera de la ruta. El ID del evento anterior que envió el navegador está en `controller.sseID`. El stream termina con `controller.close()`.\n\nExample: Un reloj\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nReenvía la petición a otra URL y responde con su respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | La URL de destino, o las opciones. |\n\nReturns: `undefined` Nada.\n\nEl método, el cuerpo, la query string y las cabeceras de la petición se envían al destino (excepto `host`, `connection`, `accept-encoding` y las cabeceras `x-forwarded-*`). El estado y el cuerpo de la respuesta se devuelven. Si hay error, llama a `controller.invalid(err)`.\n\nOpciones: `url` (obligatoria), `method`, `headers`, `timeout` (por defecto `10000` ms) y `callback(err, response)`, que se ejecuta antes de la respuesta.\n\nExample: Reenviar una API\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nLee la autenticación de acceso Basic, o se la pide al navegador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | El realm que muestra el navegador. |\n\nReturns: `Object|null` Las credenciales sin etiqueta; `null` con etiqueta.\n\nSin argumento devuelve `{ user, password, empty }` de la cabecera `Authorization`. Con una etiqueta responde `401` con la cabecera `WWW-Authenticate`, así que el navegador muestra un diálogo de inicio de sesión.\n\nExample: Una página protegida\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nIndica si el cliente sigue conectado.\n\nReturns: `Boolean`\n\nEs `false` después de que el cliente cierre la conexión o después de `controller.close()`. Compruébalo en trabajos largos antes de responder.\n\nExample: Trabajo largo\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nSiempre `true` para un controlador.\n\nReturns: `Boolean`\n\nÚtil para distinguir un controlador de un objeto `$` en una función compartida.\n\nExample: Una función compartida\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nIndica si la petición llegó por HTTPS.\n\nReturns: `Boolean`\n\nEs `true` cuando el protocolo es `https:` (o `wss:`). Detrás de un proxy depende de la URL que ve el framework. Igual que `req.secured`.\n\nExample: Forzar HTTPS\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nLa cabecera `Referer` de la petición.\n\nReturns: `String`\n\nUn string vacío cuando falta la cabecera.\n\nExample: Volver atrás\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nIndica si el user agent parece un bot.\n\nReturns: `Boolean`\n\nBusca en la cabecera `User-Agent` palabras como `bot`, `crawler` y `spider`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nEl user agent procesado como un texto corto con el navegador y el sistema.\n\nReturns: `String`\n\nUsa `req.useragent(true)` para obtener un objeto con el navegador, el SO y el dispositivo. Igual que `req.ua`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nLa URL procesada de la petición.\n\nReturns: `Object`\n\nUn objeto de `url.parse()` con `pathname`, `query`, `hostname` y las demás partes.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nLas partes de la ruta de la URL.\n\nReturns: `String[]`\n\n`/products/shoes/` da `['products', 'shoes']`.\n\nExample: Ejemplo\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nEl subdominio de la petición como array.\n\nReturns: `String[]`\n\n`shop.eu.example.com` da `['shop', 'eu']`; `www` se ignora. Es `null` si no hay subdominio.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nEl id de la sesión de la petición.\n\nReturns: `String`\n\nLo establece tu delegado `AUTH()` o el mecanismo de sesiones. Igual que `req.sessionid`.\n\nExample: Ejemplo\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nEl id del último evento que recibió el navegador.\n\nReturns: `String`\n\nEl valor de la cabecera `Last-Event-ID` que envía el navegador cuando se reconecta a una ruta de eventos server-sent, o `null`.\n\nExample: Ejemplo\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nLa ruta con la que coincidió la petición.\n\nReturns: `Object`\n\nUn objeto interno del framework con la URL, los flags, el esquema y las opciones de la ruta. Léelo, no lo cambies.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nLas opciones propias de la ruta.\n\nReturns: `Object`\n\nEl objeto que pasas a `ROUTE()` como opciones.\n\nExample: Ejemplo\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nLos flags de la ruta.\n\nReturns: `String[]`\n\nUn array con los flags de la ruta, por ejemplo `['get', 'json']`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nEl nombre del esquema de la ruta.\n\nReturns: `String`\n\nPara una ruta como `POST /api/users/ *Users --> save` es `'Users'`. Un string vacío cuando la ruta no tiene esquema.\n\nExample: Ejemplo\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nEl nombre del controlador.\n\nReturns: `String`\n\nEl nombre del archivo en `/controllers/` (sin `.js`) que declaró la ruta.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nLa ruta de navegación (breadcrumb) del elemento actual del sitemap.\n\nReturns: `Object[]`\n\nLos elementos establecidos por `controller.sitemap()`; en las vistas, la misma lista está en `@{sitemap}`.\n\nExample: Ejemplo\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nResponde con JSONP: una llamada a una función JavaScript con los datos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la función JavaScript. |\n| `obj` | `Object` | yes |  | Los datos. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `beautify` | `Boolean` | no | `false` | Formatea el JSON. |\n| `replacer` | `Function` | no |  | Un replacer para `JSON.stringify()`. |\n\nReturns: `Controller` El controlador.\n\nEl cuerpo es `name(json)` con el tipo de contenido `application/x-javascript`. Sin `name`, la función es `callback`. Un `ErrorBuilder` se responde como sus errores.\n\nExample: Nombre desde la query string\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nResponde con la página de error 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#400` si la declaraste; si no, el framework renderiza su propia página de error. El problema está en `controller.exception` de la ruta de error. Alias: `controller.view400()`.\n\nExample: Responder 400\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nResponde con la página de error 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#401` si la declaraste; si no, el framework renderiza su propia página de error. El problema está en `controller.exception` de la ruta de error. Alias: `controller.view401()`.\n\nExample: Responder 401\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nResponde con la página de error 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#409` si la declaraste; si no, el framework renderiza su propia página de error. El problema está en `controller.exception` de la ruta de error. Alias: `controller.view409()`.\n\nExample: Responder 409\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nResponde con la página de error 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#501` si la declaraste; si no, el framework renderiza su propia página de error. El problema está en `controller.exception` de la ruta de error. Alias: `controller.view501()`.\n\nExample: Responder 501\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nResponde con la página de error 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Controller` El controlador.\n\nEjecuta la ruta `#503` si la declaraste; si no, el framework renderiza su propia página de error. El problema está en `controller.exception` de la ruta de error. Alias: `controller.view503()`.\n\nExample: Responder 503\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias de `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 400 de la misma forma.\n\nExample: Igual que throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias de `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 401 de la misma forma.\n\nExample: Igual que throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias de `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 403 de la misma forma.\n\nExample: Igual que throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias de `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 404 de la misma forma.\n\nExample: Igual que throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias de `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 409 de la misma forma.\n\nExample: Igual que throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias de `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | El error, que el framework registra. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 500 de la misma forma.\n\nExample: Igual que throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias de `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 501 de la misma forma.\n\nExample: Igual que throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias de `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | El problema. |\n\nReturns: `Controller` El controlador.\n\nResponde la página de error 503 de la misma forma.\n\nExample: Igual que throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nResponde `204 No Content` sin cuerpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Controller` El controlador.\n\nExample: Nada que responder\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nCierra la conexión sin responder.\n\nReturns: `Controller` El controlador.\n\nEl socket se destruye. No pasa nada si la petición ya fue respondida.\n\nExample: Descartar una petición\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nTermina la respuesta, sobre todo un stream de eventos server-sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Llama a `res.end()`. |\n\nReturns: `Controller` El controlador.\n\nTermina la respuesta de `controller.sse()` y marca el controlador como desconectado. Con `end` a `false`, la respuesta solo se marca como terminada.\n\nExample: Detener un stream\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nMarca el controlador como cancelado.\n\nReturns: `Controller` El controlador.\n\nEstablece `controller.isCanceled` a `true`. Llamado en un manejador de `ON('controller')`, impide que se ejecute la acción de la ruta, así que el manejador debe responder por sí mismo.\n\nExample: Detener peticiones durante el mantenimiento\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nElimina ahora los archivos subidos de la petición.\n\nReturns: `Controller` El controlador.\n\nSe borran los archivos temporales de `controller.files` y se vacían `body`, `query` y las cookies de la petición.\n\nExample: Después del trabajo\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nTe permite responder tú mismo con la respuesta de Node.js.\n\nReturns: `Boolean` `true` cuando puedes responder.\n\nEl framework marca la petición como respondida y deja de esperarla. Después escribe en `controller.res` con `writeHead()` y `end()`. Devuelve `false` cuando la petición ya fue respondida.\n\nExample: Escribir la respuesta\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nRegistra un error con el nombre del controlador y la URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | El error. |\n\nReturns: `Controller` El controlador.\n\nEl error va a `F.error()` y a `controller.exception`; la petición no se responde. En cambio, un `ErrorBuilder` se responde como JSON.\n\nExample: Registrar y continuar\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nCrea un callback que responde el error y solo pasa el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Se ejecuta con los resultados en caso de éxito. |\n\nReturns: `Function` Un callback `(err, a, b, c)`.\n\nLa función devuelta tiene la forma `(err, a, b, c)`. Si hay error, llama a `controller.invalid(err)`; si no, llama a `callback(a, b, c)` con el controlador como `this`.\n\nExample: Solo el camino de éxito\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nCrea una URL absoluta con el host de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta a añadir. |\n\nReturns: `String` La URL, por ejemplo `https://example.com/products/`.\n\nEl protocolo, el nombre de host y el puerto de la petición con `path` añadido.\n\nExample: Un enlace para un email\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nResponde con una imagen modificada por el procesador de imágenes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | La imagen. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `callback` | `Function` | no |  | Se ejecuta cuando termina la respuesta. |\n\nReturns: `Controller` El controlador.\n\n`filename` es un archivo en `/public/` (o una ruta completa con `~` delante) o un stream. `make(image)` cambia la imagen con los métodos de `Image` (`resize()`, `quality()`, ...). El resultado se guarda en caché en `/tmp/`. Necesita GraphicsMagick o ImageMagick.\n\nExample: Una miniatura\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nGuarda en caché toda la respuesta de una acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave en la caché. |\n| `expire` | `String|Date` | yes |  | Cuánto tiempo, por ejemplo `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` omite la caché. |\n| `fn` | `Function` | yes |  | Crea la respuesta; se ejecuta con el controlador como `this`. |\n| `fnFrom` | `Function` | no |  | Se ejecuta antes de una respuesta desde la caché. |\n\nReturns: `Controller` El controlador.\n\nLa primera llamada ejecuta `fn` y guarda la respuesta (una vista, JSON o texto) bajo `key` durante `expire`. Las llamadas posteriores responden desde la caché, y antes se ejecuta `fnFrom`. Con `disabled` a `true` se omite la caché. El tema se añade a la clave.\n\nExample: Guardar en caché la página de inicio\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nEstablece la meta descripción de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La descripción. |\n\nReturns: `Controller` El controlador.\n\nEn la plantilla la escribe `@{meta}`. `controller.keywords()` establece las palabras clave y `controller.author()` el autor de la misma forma.\n\nExample: Etiquetas meta\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nEstablece las meta palabras clave de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Las palabras clave. |\n\nReturns: `Controller` El controlador.\n\nUn array se une con comas. En la plantilla lo escribe `@{meta}`.\n\nExample: Palabras clave\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nAñade etiquetas en el head de la plantilla, o las lee.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Un nombre de archivo o una etiqueta HTML. |\n\nReturns: `Controller|String` El controlador, o el HTML sin argumentos.\n\nUn archivo `.css` se convierte en un `<link>` y un archivo `.js` en un `<script>`; los nombres relativos apuntan a `/public/css/` y `/public/js/`. Un valor que empieza por `<` se añade tal cual. Cada valor se añade una sola vez. Sin argumentos devuelve el HTML; en la plantilla usa `@{head}`.\n\nExample: Archivos para una página\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nAñade contenido en un lugar con nombre de la plantilla, o lo lee.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del lugar. |\n| `value` | `String` | no |  | El contenido. |\n\nReturns: `Controller|String` El controlador, o el contenido si solo pasas `name`.\n\nUn valor `.js` se convierte en un `<script>` y un valor `.css` en un `<link>`; los demás valores se añaden tal cual. En la plantilla usa `@{place('name')}`.\n\nExample: Scripts al final de la página\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nEstablece el tema de las vistas de esta petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del tema. |\n\nReturns: `Controller` El controlador.\n\nLas vistas, las plantillas y los archivos estáticos se buscan entonces primero en `/themes/{name}/`. El valor por defecto viene de `CONF.default_theme`.\n\nExample: Un tema por cliente\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nRenderiza un componente a HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del componente. |\n| `settings` | `Object` | no |  | Los ajustes del componente. |\n| `model` | `Object` | no |  | El modelo; por defecto, el modelo de la vista. |\n\nReturns: `String` El HTML, o un string vacío para un componente desconocido.\n\nEl componente es un archivo en `/components/`. Su CSS y su JS se añaden al head de la plantilla. En las vistas usa `@{component('name')}`.\n\nExample: HTML de un componente\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nEjecuta un helper de vista de `DEF.helpers`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del helper. |\n| `arg` | `Object` | no |  | Argumentos para el helper. |\n\nReturns: `String` La salida del helper.\n\nEl helper se ejecuta con el controlador como `this`. Un helper desconocido devuelve un string vacío.\n\nExample: Usar un helper en una acción\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nCrea la URL de un archivo en `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n| `path` | `String` | no |  | Una ruta unida a una URL relativa. |\n\nReturns: `String` La URL.\n\nRespeta los ajustes de URL estáticas y el tema. La familia `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` y `public_download()` hace lo mismo para su propio directorio.\n\nExample: Una URL en JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `js`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n| `tag` | `Boolean` | no | `false` | Devuelve una etiqueta HTML. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_script`, por defecto `/js/`). Con `tag` a `true` devuelve la etiqueta HTML (`<script>` o `<link>`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `css`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n| `tag` | `Boolean` | no | `false` | Devuelve una etiqueta HTML. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_style`, por defecto `/css/`). Con `tag` a `true` devuelve la etiqueta HTML (`<script>` o `<link>`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `img`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_image`, por defecto `/img/`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `videos`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_video`, por defecto `/videos/`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `fonts`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_font`, por defecto `/fonts/`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nCrea la URL de un archivo en el directorio público `download`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo. |\n\nReturns: `String` La URL.\n\nEl directorio viene de la configuración (`static_url_download`, por defecto `/download/`).\n\nExample: URL de un archivo\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nAñade una prueba de una ruta a las pruebas del framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La ruta a probar. |\n| `name` | `String` | no |  | El nombre de la prueba. |\n| `callback` | `Function` | no |  | `function(result)` que devuelve `true` si tiene éxito. |\n\nReturns: `Object` La prueba.\n\nLas pruebas de un controlador se ejecutan una tras otra. `url` es una ruta como `'GET /api/products/'` o `'API /api/ products_query'` (entonces el nombre de la prueba es la operación). `callback(result)` recibe `{ err, value, response, name }` y devuelve `true` cuando la prueba pasa; sin él, una prueba pasa cuando no hay error.\n\nExample: Probar rutas desde una ruta\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nLa cabecera `Host` de la petición.\n\nReturns: `String`\n\nEl nombre de host con el puerto, por ejemplo `example.com:8000`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nIndica si la petición llegó por HTTPS.\n\nReturns: `Boolean`\n\nEs `true` cuando el protocolo es `https:` o `wss:`.\n\nExample: Ejemplo\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nEl resultado de la autorización.\n\nReturns: `Boolean`\n\nEs `true` hasta que se ejecuta tu delegado `AUTH()`; después es `true` cuando el delegado aceptó al usuario y `false` cuando lo rechazó.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nIndica si la petición pide un archivo estático.\n\nReturns: `Boolean`\n\nEs `true` cuando la URL tiene una extensión de archivo y los archivos estáticos están permitidos. Útil en `DEF.onLocale` y en middleware.\n\nExample: Ejemplo\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nIndica si la petición vino de JavaScript.\n\nReturns: `Boolean`\n\nEs `true` cuando la cabecera `X-Requested-With` es `XMLHttpRequest`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nLa dirección IP del cliente.\n\nReturns: `String`\n\nDetrás de un proxy es la primera dirección de `X-Forwarded-For`. Se puede asignar.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nLa URL procesada de la petición.\n\nReturns: `Object`\n\nUn objeto de `url.parse()` con `pathname`, `query`, `hostname` y `port`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nLas partes de la ruta en minúsculas.\n\nReturns: `String[]`\n\n`/Products/Shoes/` da `['products', 'shoes']`. `req.split` conserva las mayúsculas originales.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nLas partes de la ruta de la URL.\n\nReturns: `String[]`\n\nLas partes tal como estaban en la URL. Igual que `controller.split`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nEl subdominio como array, o `null`.\n\nReturns: `String[]`\n\n`www` se ignora. `a.localhost` da `['a']`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nIndica si el user agent es un dispositivo móvil.\n\nReturns: `Boolean`\n\nComprueba la cabecera `User-Agent`. Se puede asignar.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nIndica si el user agent parece un bot.\n\nReturns: `Boolean`\n\nComprueba la cabecera `User-Agent`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nEl user agent procesado como un texto corto con el navegador y el sistema.\n\nReturns: `String`\n\nLo mismo que `req.useragent()`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nLa query string como objeto.\n\nReturns: `Object`\n\nSe procesa en la primera lectura y se puede asignar.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nEl cuerpo de la petición ya procesado.\n\nReturns: `Object`\n\nUn cuerpo JSON o de formulario. Igual que `controller.body`.\n\nExample: Ejemplo\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nLos archivos subidos.\n\nReturns: `HttpFile[]`\n\nUn array de objetos `HttpFile` para rutas con el flag `upload`. Igual que `controller.files`.\n\nExample: Ejemplo\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nEl usuario aceptado por el delegado `AUTH()`, o `null`.\n\nReturns: `Object`\n\nIgual que `controller.user`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nEl objeto de sesión de la petición, o `null`.\n\nReturns: `Object`\n\nLo establece tu delegado `AUTH()` o el mecanismo de sesiones. Igual que `controller.session`.\n\nExample: Ejemplo\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nProcesa la cabecera `User-Agent`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Devuelve un objeto. |\n\nReturns: `String|Object` El user agent.\n\nSin argumento devuelve un texto corto con los nombres encontrados en la cabecera, como el navegador y el sistema. Con `true` devuelve `{ os, browser, device }`, donde `device` es `desktop`, `mobile`, `tablet` o `tv`. El resultado se guarda en caché en la petición.\n\nExample: Detalles del dispositivo\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nLee una cookie de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cookie. |\n\nReturns: `String` El valor.\n\nEl valor se decodifica. Una cookie inexistente da un string vacío. `controller.cookie(name)` hace lo mismo.\n\nExample: Leer una cookie en un middleware\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nLee la cabecera de autorización Basic.\n\nReturns: `Object` `{ user, password, empty }`.\n\nDecodifica `Authorization: Basic ...` en `{ user, password, empty }`. `empty` es `true` cuando falta el usuario o la contraseña.\n\nExample: Autenticación Basic\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nEjecuta tú mismo el delegado `AUTH()` para esta petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` La petición.\n\n`callback(err, user, isAuthorized)` recibe el resultado del delegado. Sin delegado, `isAuthorized` es `false`. Útil para rutas que no usan los flags de autorización.\n\nExample: Comprobar un usuario en una ruta pública\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nElimina los archivos subidos de la petición.\n\nReturns: `Request` La petición.\n\nIgual que `controller.clear()`.\n\nExample: Limpiar los archivos\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrea un token CSRF para la petición.\n\nReturns: `String` El token.\n\nIgual que `controller.csrf()`; usa `DEF.onCSRFcreate(req)`.\n\nExample: Un token en un middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nCifra la respuesta de texto de esta petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `Request` La petición.\n\nLa respuesta se cifra con `CONF.secret_encryption` y recibe la cabecera `X-Encryption: a`. `controller.encrypt([enable])` hace lo mismo.\n\nExample: Cifrar una respuesta\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nCrea una URL absoluta con el host de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Una ruta a añadir. |\n\nReturns: `String` La URL.\n\nEl protocolo, el nombre de host y el puerto de la petición con `path` añadido. Igual que `controller.hostname()`.\n\nExample: URL absoluta\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nDesactiva la caché HTTP de la respuesta.\n\nReturns: `Request` La petición.\n\nLlama a `res.nocache()`.\n\nExample: En un middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nEl controlador de la petición.\n\nReturns: `Controller`\n\nSe establece cuando un controlador maneja la petición.\n\nExample: Ejemplo\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nIndica si la respuesta se envió.\n\nReturns: `Boolean`\n\nEs `true` después de que el framework haya respondido a la petición.\n\nExample: Ejemplo\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nDesactiva la compresión del HTML y de los archivos estáticos para esta respuesta.\n\nReturns: `Boolean`\n\nCon `true`, el framework no minifica el HTML ni los archivos estáticos que envía.\n\nExample: Ejemplo\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nResponde con un objeto como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El valor. |\n\nReturns: `Response` La respuesta.\n\nEl estado viene de las opciones de la respuesta (`200` por defecto).\n\nExample: JSON desde una ruta con (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nResponde con un cuerpo y un tipo de contenido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | El estado HTTP. |\n| `body` | `String` | yes |  | El cuerpo. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n| `compress` | `Boolean` | no |  | Compresión. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Response` La respuesta.\n\nLos cuerpos de más de 4 kB se comprimen con GZIP.\n\nExample: Un CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nResponde al estilo de Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | El estado HTTP. |\n| `body` | `String|Object|Number` | yes |  | El cuerpo. |\n| `type` | `String` | no |  | El tipo de contenido. |\n\nReturns: `Response` La respuesta.\n\nUn string es `text/html`, un número se responde como el texto de ese estado, un objeto es JSON y un `ErrorBuilder` se responde como sus errores. Está pensado para middleware escrito para Express.\n\nExample: Estilo Express\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nResponde con un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Los datos. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n| `encoding` | `String` | no |  | La codificación del buffer. |\n| `download` | `String` | no |  | Un nombre de archivo para descargar. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n\nReturns: `Response` La respuesta.\n\n`download` establece el nombre de archivo de `Content-Disposition`.\n\nExample: Un archivo generado\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nResponde con una imagen modificada sin la caché de `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | La imagen. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Cabeceras adicionales de la respuesta. |\n| `callback` | `Function` | no |  | Se ejecuta al final. |\n\nReturns: `Response` La respuesta.\n\nFunciona como `res.image()`, pero el resultado se crea en cada petición.\n\nExample: Imagen con una marca de tiempo\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nDesactiva la caché HTTP de la respuesta.\n\nReturns: `Response` La respuesta.\n\nElimina `If-None-Match` e `If-Modified-Since` de la petición y establece `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: En una ruta con (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nResponde con la página de error 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta `#409` si la declaraste.\n\nExample: Responder 409\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nResponde con la página de error 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción del problema. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta `#501` si la declaraste.\n\nExample: Responder 501\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Controller","summary":"Propriétés et méthodes du contrôleur, l'objet qui répond à une requête.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Propriétés et méthodes du contrôleur, l'objet qui répond à une requête.\n\nLe contrôleur est `this` dans chaque action d'une route. Il contient les données de la requête et les méthodes qui y répondent. Le guide [Contrôleurs](../../guides/controllers/) explique comment l'utiliser avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### controller.body\n\nType: `property`\n\nLe corps analysé de la requête.\n\nReturns: `Object`\n\nUn corps JSON ou URL-encoded est analysé en objet. Les valeurs d'un formulaire sont des chaînes. Une route avec un schéma le remplace par le modèle validé. Tu peux aussi lui affecter un nouvel objet.\n\nExample: Lire le corps\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nLa query string de l'URL sous forme d'objet.\n\nReturns: `Object`\n\nLes valeurs sont des chaînes : `?page=2` donne `{ page: '2' }`. L'objet est analysé la première fois que tu le lis.\n\nExample: Pagination\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nLes paramètres dynamiques de l'URL.\n\nReturns: `Object`\n\nChaque `{name}` de la route devient une clé. Les paramètres déclarés avec un type sont convertis : `{id:number}` avec `parseInt()`, `{active:boolean}` avec `parseBoolean()` et `{date:date}` avec `parseDate()`. Les mêmes valeurs arrivent en arguments de l'action.\n\nExample: Paramètre typé\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nLes fichiers uploadés.\n\nReturns: `Array`\n\nSeules les routes avec le flag `upload` reçoivent des fichiers. Chaque fichier possède `name` (le champ du formulaire), `filename`, `type`, `size`, `extension`, `width` et `height`, ainsi que les méthodes `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` et `isAudio()`. `move()`, `copy()` et `read()` renvoient une promesse sans callback. Les fichiers temporaires sont supprimés à la fin de la requête, sauf si tu appelles `controller.autoclear(false)`.\n\nExample: Enregistrer un upload\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nL'utilisateur connecté.\n\nReturns: `Object`\n\nL'objet que ton délégué `AUTH()` a passé à `$.success(user)`. Il vaut `undefined` lorsque personne n'est connecté. Tu peux lui affecter une valeur.\n\nExample: Profil\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nLes en-têtes de la requête.\n\nReturns: `Object`\n\nLes noms des en-têtes sont en minuscules.\n\nExample: Lire un en-tête\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nL'adresse IP du client.\n\nReturns: `String`\n\nDerrière un proxy, c'est la première adresse de l'en-tête `X-Forwarded-For` ; sinon, l'adresse de la connexion.\n\n### controller.url\n\nType: `property`\n\nLe chemin de l'URL de la requête en minuscules.\n\nReturns: `String`\n\nIl ne contient pas de query string et se termine toujours par `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true` lorsque le client est un appareil mobile.\n\nReturns: `Boolean`\n\nIl est déterminé à partir de l'en-tête `User-Agent`. Tu peux lui affecter une valeur.\n\n### controller.xhr\n\nType: `property`\n\n`true` lorsque la requête a été envoyée par XMLHttpRequest.\n\nReturns: `Boolean`\n\nIl vaut `true` lorsque la requête contient l'en-tête `X-Requested-With: XMLHttpRequest`.\n\n### controller.language\n\nType: `property`\n\nLa langue de la requête.\n\nReturns: `String`\n\nC'est la valeur renvoyée par ton délégué de localisation (`DEF.onLocale`). Les vues et `controller.mail()` traduisent les textes avec elle.\n\n### controller.status\n\nType: `property`\n\nLe code de statut HTTP de la réponse.\n\nReturns: `Number`\n\nDéfinis-le avant de répondre. `json()`, `jsonstring()`, `plain()`, `content()` et `html()` l'utilisent, et `200` lorsqu'il n'est pas défini. `invalid()` utilise un statut supérieur à `399` pour les erreurs.\n\nExample: Créé\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn objet partagé par la vue et son layout.\n\nReturns: `Object`\n\nLes valeurs que tu y stockes avant `view()` sont disponibles dans la vue et dans le layout sous le nom `repository`. Le titre de la page et les balises meta y sont aussi stockés.\n\nExample: Passer une valeur au layout\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nLe problème d'une route d'erreur.\n\nReturns: `Error|String`\n\nDans une route pour un statut d'erreur (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`), il contient le problème passé à `throw404()`, `throw500()` et aux autres.\n\n### controller.req\n\nType: `property`\n\nL'objet requête du framework.\n\nReturns: `Request`\n\nIl étend la requête de Node.js. Les propriétés du contrôleur comme `body`, `query` et `ip` sont lues depuis celui-ci.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nRépond avec un objet sérialisé en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | La valeur à sérialiser. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `beautify` | `Boolean` | no | `false` | Formate le JSON avec une indentation. |\n| `replacer` | `Function` | no |  | Un replacer pour `JSON.stringify()`. |\n\nReturns: `Controller` Le contrôleur.\n\nLe type de contenu est `application/json` et le statut est `controller.status` ou `200`. Un `ErrorBuilder` est renvoyé sous forme de ses erreurs avec son propre statut. `beautify` peut être le deuxième argument.\n\nExample: Un objet\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Formaté\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nRépond avec un texte qui est déjà du JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Le texte JSON. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\nUtilise-la lorsque tu as le JSON sous forme de chaîne, par exemple depuis un cache. Le texte est envoyé tel quel, avec le type de contenu `application/json`.\n\nExample: Depuis un cache\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nRépond avec du texte brut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | Le texte. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\nLe type de contenu est `text/plain`. Un objet est sérialisé en JSON formaté ; `null` donne un corps vide.\n\nExample: Texte\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nRépond avec du HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le HTML. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\nÉquivaut à `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nRépond avec un texte et ton type de contenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le contenu. |\n| `type` | `String` | no | `text/plain` | Le type de contenu. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\nUn `ErrorBuilder` comme `body` est renvoyé en JSON avec son propre statut.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRend une vue et répond avec elle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom de la vue sans `.html`. |\n| `model` | `Object` | no |  | Le modèle, disponible dans la vue sous le nom `model`. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `partial` | `Boolean` | no | `false` | Renvoie le HTML sous forme de chaîne et ne répond pas. Peut être le troisième argument. |\n\nReturns: `Controller|String` Le contrôleur, ou le HTML lorsque `partial` vaut `true`.\n\nLa vue est un fichier `name.html` dans `views/`, rendu dans le layout (`layout` par défaut, voir `controller.layout()`). Les routes d'un contrôleur autre que `default` cherchent les vues dans `views/<controller name>/`. Le premier caractère du nom change l'endroit où le fichier est recherché :\n\n| Préfixe | Emplacement |\n| --- | --- |\n| `~` | La racine de `views/` |\n| `#plugin/view` | Les vues d'un plugin |\n| `=theme/view` | Les vues d'un thème |\n| `@` | Un paquet |\n\nSans nom, la vue est nommée d'après la dernière partie de l'URL (`index` pour `/`). Avec `partial` à `true`, la méthode renvoie le HTML rendu au lieu de répondre.\n\nExample: Une page\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: Le HTML sous forme de chaîne\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nChoisit le layout de la prochaine vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la vue de layout, ou une chaîne vide. |\n\nReturns: `Controller` Le contrôleur.\n\nLe layout par défaut est `layout` (la configuration `default_layout`). Une chaîne vide rend la vue sans layout.\n\nExample: Sans layout\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nDéfinit le titre de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le titre. |\n\nReturns: `Controller` Le contrôleur.\n\nLe layout l'affiche avec `@{title}`. Le texte est encodé en HTML.\n\nExample: Titre\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nDéfinit les valeurs meta de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Le titre. |\n| `description` | `String` | no |  | La description. |\n| `keywords` | `String|Array` | no |  | Les mots-clés. |\n| `image` | `String` | no |  | L'URL d'une image. |\n\nReturns: `Controller` Le contrôleur.\n\nLe layout les affiche avec `@{meta}`. `keywords` peut être un tableau.\n\nExample: Balises meta\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nRépond avec un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier dans `public/`, ou `~` suivi d'un chemin absolu. |\n| `download` | `String|Boolean` | no |  | Un nom pour le fichier téléchargé ; `true` utilise le nom du fichier. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute lorsque le fichier est envoyé. |\n\nReturns: `Controller` Le contrôleur.\n\nLe fichier est lu depuis `public/`. Un nom qui commence par `~` est un chemin absolu.\n\nExample: Téléchargement\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nRépond avec un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Les données. |\n| `type` | `String` | yes |  | Le type de contenu. |\n| `encoding` | `String` | no |  | Une conversion des données. |\n| `download` | `String` | no |  | Un nom pour le fichier téléchargé. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\n`encoding` convertit le buffer avant son envoi (`binary`, `utf8`, `ascii`).\n\nExample: Une image en mémoire\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nRépond avec un flux lisible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un flux lisible. |\n| `type` | `String` | yes |  | Le type de contenu. |\n| `download` | `String` | no |  | Un nom pour le fichier téléchargé. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute lorsque le flux est envoyé. |\n| `nocompress` | `Boolean` | no | `false` | Désactive la compression. |\n\nReturns: `Controller` Le contrôleur.\n\nLa réponse est compressée sauf si `nocompress` vaut `true`. Les deux premiers arguments peuvent être inversés (`type`, `stream`).\n\nExample: Un fichier CSV\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nRedirige le client vers une autre URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL cible. |\n| `permanent` | `Boolean` | no | `false` | Envoie `301 Moved Permanently`. |\n\nReturns: `Controller` Le contrôleur.\n\nLe statut est `302`, ou `301` lorsque `permanent` vaut `true`.\n\nExample: Après un formulaire\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nRépond avec un corps vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | En-têtes supplémentaires, ou un code de statut. |\n\nReturns: `Controller` Le contrôleur.\n\nUn nombre à la place des en-têtes définit le code de statut. Pour `204 No Content`, tu peux aussi utiliser `controller.nocontent([headers])`.\n\nExample: Accepté\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nRépond avec le JSON `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | La valeur de `success`. |\n| `value` | `Object` | no |  | Une valeur ajoutée comme `value`. |\n\nReturns: `Controller` Le contrôleur.\n\n`success(value)` répond `{ \"success\": true, \"value\": value }`. `success(false)` répond `{ \"success\": false }`.\n\nExample: Avec une valeur\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nRépond avec une erreur en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | Un code de statut, le nom de l'erreur ou l'erreur. |\n| `error` | `String` | no |  | Le texte de l'erreur. |\n\nReturns: `ErrorBuilder` Le builder contenant les erreurs.\n\nLes erreurs sont renvoyées sous forme de tableau JSON avec le statut `400` (la configuration `default_errorbuilder_status`). Un nombre en premier argument définit le statut ; une `Error` ou un `ErrorBuilder` est renvoyé tel quel. La réponse est envoyée au tick suivant, tu peux donc encore ajouter des erreurs au builder renvoyé.\n\nExample: Validation\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Un autre statut\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nCrée un callback qui répond un succès ou une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` ajoute la réponse comme `value` ; une autre valeur est elle-même ajoutée comme `value`. |\n\nReturns: `Function` Un callback `(err, response)`.\n\nLe callback a la forme `(err, response)`. En cas d'erreur, il appelle `controller.invalid(err)`. Sinon, il répond `{ \"success\": true }` ; avec `done(true)`, la réponse est ajoutée comme `value`, et avec une autre valeur, c'est cette valeur qui est ajoutée.\n\nExample: N'importe quel callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nCrée un callback qui renvoie la réponse en JSON ou avec une vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | Le nom d'une vue. |\n\nReturns: `Function` Un callback `(err, data)`.\n\nLe callback a la forme `(err, data)`. Lorsque `err` est un `ErrorBuilder` et que tu n'as pas passé de vue, ses erreurs sont renvoyées en JSON. Toute autre erreur renvoie la page d'erreur `404`, ou `500` lorsque l'`ErrorBuilder` contient une `Error`. Sans erreur, il renvoie `data` en JSON, ou rend la vue avec `data` comme modèle.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: Une vue\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème, disponible dans la route d'erreur sous `controller.exception`. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#404` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. La même famille répond pour d'autres statuts : `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` et `throw503()`. Chacune a un alias nommé `view400()` … `view503()`. Rien ne se passe si la requête a déjà reçu une réponse.\n\nExample: Enregistrement introuvable\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: Ta propre page\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème, disponible dans la route d'erreur sous `controller.exception`. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#403` si tu en as déclaré une. Alias : `view403()`.\n\nExample: Réservé aux administrateurs\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nEnregistre une erreur dans le journal et répond avec la page d'erreur 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | L'erreur. |\n\nReturns: `Controller` Le contrôleur.\n\nL'erreur est enregistrée par le framework (`DEF.onError`). Ensuite, la route `#500` s'exécute si tu en as déclaré une. Alias : `view500()`.\n\nExample: Dans une promesse\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLit un cookie de la requête ou écrit un cookie dans la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du cookie. |\n| `value` | `String` | no |  | La valeur à écrire. |\n| `expires` | `String` | no |  | Quand le cookie expire, par exemple `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` La valeur en lecture, le contrôleur en écriture.\n\nAvec un seul argument, elle renvoie la valeur du cookie, ou une chaîne vide. Avec une valeur, elle ajoute un en-tête `Set-Cookie`. `expires` est un texte comme `'5 days'` ou `'2 hours'` ; une valeur négative (`'-1 day'`) supprime le cookie. À la place de `expires`, tu peux passer l'objet d'options contenant `expires`.\n\nOptions : `domain`, `path` (par défaut `/`), `secure` (par défaut la configuration `default_cookies_secure`), `httponly` et `samesite` (`Lax`, `Strict` ou `None` ; par défaut `Lax`, la configuration `default_cookies_samesite`).\n\nExample: Écrire et lire\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Supprimer\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nDéfinit un en-tête de la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'en-tête. |\n| `value` | `String` | yes |  | La valeur. |\n\nReturns: `Controller` Le contrôleur.\n\nExample: Un en-tête\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nDésactive le cache HTTP de la réponse.\n\nReturns: `Controller` Le contrôleur.\n\nExample: Données fraîches\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrée un jeton CSRF pour la requête courante.\n\nReturns: `String` Le jeton.\n\nLes routes avec le flag `csrf` vérifient le jeton provenant de l'en-tête `x-csrf-token` ou de l'argument `?csrf=` de l'URL. Dans les vues, le même jeton est `@{csrf}`.\n\nExample: Envoyer le jeton\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nConserve ou supprime les fichiers uploadés à la fin de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` conserve les fichiers. |\n\nReturns: `Controller` Le contrôleur.\n\n`autoclear(false)` conserve les fichiers temporaires de `controller.files` après la réponse, pour un travail qui se poursuit plus tard. `controller.clear()` les supprime immédiatement.\n\nExample: Traiter plus tard\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nEnvoie un événement server-sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | Les données de l'événement. |\n| `eventname` | `String` | no |  | Le nom de l'événement. |\n| `id` | `String` | no |  | L'ID de l'événement. |\n| `retry` | `Number` | no |  | Le temps d'attente du navigateur avant de se reconnecter, en millisecondes. |\n\nReturns: `Boolean` `false` lorsque l'événement ne peut pas être envoyé (le client s'est déconnecté ou la requête a déjà reçu une réponse).\n\nLe premier appel répond avec les en-têtes de `text/event-stream` et garde la connexion ouverte. Un objet est sérialisé en JSON. Lorsque `retry` est absent, le premier appel utilise le délai d'expiration de la route. L'ID du dernier événement envoyé par le navigateur se trouve dans `controller.sseID`. Le flux se termine avec `controller.close()`.\n\nExample: Une horloge\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nTransmet la requête à une autre URL et répond avec sa réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | L'URL cible, ou les options. |\n\nReturns: `undefined` Rien.\n\nLa méthode, le corps, la query string et les en-têtes de la requête sont envoyés à la cible (sauf `host`, `connection`, `accept-encoding` et les en-têtes `x-forwarded-*`). Le statut et le corps de la réponse sont renvoyés. En cas d'erreur, elle appelle `controller.invalid(err)`.\n\nOptions : `url` (obligatoire), `method`, `headers`, `timeout` (par défaut `10000` ms) et `callback(err, response)`, qui s'exécute avant la réponse.\n\nExample: Transmettre une API\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nLit l'authentification Basic, ou la demande au navigateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | Le realm affiché par le navigateur. |\n\nReturns: `Object|null` Les identifiants sans libellé ; `null` avec un libellé.\n\nSans argument, elle renvoie `{ user, password, empty }` depuis l'en-tête `Authorization`. Avec un libellé, elle répond `401` avec l'en-tête `WWW-Authenticate`, afin que le navigateur affiche une boîte de connexion.\n\nExample: Une page protégée\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nIndique si le client est toujours connecté.\n\nReturns: `Boolean`\n\nIl vaut `false` après que le client a fermé la connexion ou après `controller.close()`. Vérifie-le pendant un long traitement avant de répondre.\n\nExample: Long traitement\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nToujours `true` pour un contrôleur.\n\nReturns: `Boolean`\n\nUtile pour distinguer un contrôleur d'un objet `$` dans une fonction partagée.\n\nExample: Une fonction partagée\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nIndique si la requête est arrivée en HTTPS.\n\nReturns: `Boolean`\n\nIl vaut `true` lorsque le protocole est `https:` (ou `wss:`). Derrière un proxy, cela dépend de l'URL que voit le framework. Identique à `req.secured`.\n\nExample: Forcer HTTPS\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nL'en-tête `Referer` de la requête.\n\nReturns: `String`\n\nUne chaîne vide lorsque l'en-tête est absent.\n\nExample: Revenir en arrière\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nIndique si l'user agent ressemble à un robot.\n\nReturns: `Boolean`\n\nIl recherche dans l'en-tête `User-Agent` des mots comme `bot`, `crawler` et `spider`.\n\nExample: Exemple\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nL'user agent analysé, sous forme de texte court avec le navigateur et le système.\n\nReturns: `String`\n\nUtilise `req.useragent(true)` pour obtenir un objet avec le navigateur, l'OS et l'appareil. Identique à `req.ua`.\n\nExample: Exemple\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nL'URL analysée de la requête.\n\nReturns: `Object`\n\nUn objet de `url.parse()` avec `pathname`, `query`, `hostname` et les autres parties.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nLes parties du chemin de l'URL.\n\nReturns: `String[]`\n\n`/products/shoes/` donne `['products', 'shoes']`.\n\nExample: Exemple\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nLe sous-domaine de la requête sous forme de tableau.\n\nReturns: `String[]`\n\n`shop.eu.example.com` donne `['shop', 'eu']` ; `www` est ignoré. Il vaut `null` sans sous-domaine.\n\nExample: Exemple\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nL'id de la session de la requête.\n\nReturns: `String`\n\nDéfini par ton délégué `AUTH()` ou par le mécanisme de session. Identique à `req.sessionid`.\n\nExample: Exemple\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nL'id du dernier événement reçu par le navigateur.\n\nReturns: `String`\n\nLa valeur de l'en-tête `Last-Event-ID` que le navigateur envoie lorsqu'il se reconnecte à une route d'événements server-sent, ou `null`.\n\nExample: Exemple\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nLa route à laquelle la requête correspond.\n\nReturns: `Object`\n\nUn objet interne du framework avec l'URL, les flags, le schéma et les options de la route. Lis-le, ne le modifie pas.\n\nExample: Exemple\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nLes options personnalisées de la route.\n\nReturns: `Object`\n\nL'objet que tu passes à `ROUTE()` comme options.\n\nExample: Exemple\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nLes flags de la route.\n\nReturns: `String[]`\n\nUn tableau avec les flags de la route, par exemple `['get', 'json']`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nLe nom du schéma de la route.\n\nReturns: `String`\n\nPour une route comme `POST /api/users/ *Users --> save`, il vaut `'Users'`. Une chaîne vide lorsque la route n'a pas de schéma.\n\nExample: Exemple\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nLe nom du contrôleur.\n\nReturns: `String`\n\nLe nom du fichier de `/controllers/` (sans `.js`) qui a déclaré la route.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nLe fil d'Ariane de l'élément courant du sitemap.\n\nReturns: `Object[]`\n\nLes éléments définis par `controller.sitemap()` ; dans les vues, la même liste se trouve dans `@{sitemap}`.\n\nExample: Exemple\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nRépond en JSONP : un appel d'une fonction JavaScript avec les données.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la fonction JavaScript. |\n| `obj` | `Object` | yes |  | Les données. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `beautify` | `Boolean` | no | `false` | Formate le JSON. |\n| `replacer` | `Function` | no |  | Un replacer pour `JSON.stringify()`. |\n\nReturns: `Controller` Le contrôleur.\n\nLe corps est `name(json)` avec le type de contenu `application/x-javascript`. Sans `name`, la fonction est `callback`. Un `ErrorBuilder` est renvoyé sous forme de ses erreurs.\n\nExample: Nom depuis la query string\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#400` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. Le problème se trouve dans `controller.exception` de la route d'erreur. Alias : `controller.view400()`.\n\nExample: Répondre 400\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#401` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. Le problème se trouve dans `controller.exception` de la route d'erreur. Alias : `controller.view401()`.\n\nExample: Répondre 401\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#409` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. Le problème se trouve dans `controller.exception` de la route d'erreur. Alias : `controller.view409()`.\n\nExample: Répondre 409\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#501` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. Le problème se trouve dans `controller.exception` de la route d'erreur. Alias : `controller.view501()`.\n\nExample: Répondre 501\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle exécute la route `#503` si tu en as déclaré une ; sinon, le framework affiche sa propre page d'erreur. Le problème se trouve dans `controller.exception` de la route d'erreur. Alias : `controller.view503()`.\n\nExample: Répondre 503\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias de `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 400 de la même manière.\n\nExample: Identique à throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias de `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 401 de la même manière.\n\nExample: Identique à throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias de `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 403 de la même manière.\n\nExample: Identique à throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias de `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 404 de la même manière.\n\nExample: Identique à throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias de `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 409 de la même manière.\n\nExample: Identique à throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias de `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'erreur, enregistrée par le framework. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 500 de la même manière.\n\nExample: Identique à throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias de `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 501 de la même manière.\n\nExample: Identique à throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias de `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Le problème. |\n\nReturns: `Controller` Le contrôleur.\n\nElle renvoie la page d'erreur 503 de la même manière.\n\nExample: Identique à throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nRépond `204 No Content` sans corps.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Controller` Le contrôleur.\n\nExample: Rien à répondre\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nFerme la connexion sans réponse.\n\nReturns: `Controller` Le contrôleur.\n\nLe socket est détruit. Rien ne se passe si la requête a déjà reçu une réponse.\n\nExample: Abandonner une requête\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nTermine la réponse, le plus souvent un flux d'événements server-sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Appelle `res.end()`. |\n\nReturns: `Controller` Le contrôleur.\n\nElle termine la réponse de `controller.sse()` et marque le contrôleur comme déconnecté. Avec `end` à `false`, la réponse est seulement marquée comme terminée.\n\nExample: Arrêter un flux\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nMarque le contrôleur comme annulé.\n\nReturns: `Controller` Le contrôleur.\n\nElle définit `controller.isCanceled` à `true`. Appelée dans un gestionnaire de `ON('controller')`, elle empêche l'exécution de l'action de la route ; le gestionnaire doit donc répondre lui-même.\n\nExample: Bloquer les requêtes pendant la maintenance\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nSupprime immédiatement les fichiers uploadés de la requête.\n\nReturns: `Controller` Le contrôleur.\n\nLes fichiers temporaires de `controller.files` sont supprimés, et `body`, `query` ainsi que les cookies de la requête sont vidés.\n\nExample: Après le traitement\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nTe permet de répondre toi-même avec la réponse de Node.js.\n\nReturns: `Boolean` `true` lorsque tu peux répondre.\n\nLe framework marque la requête comme ayant reçu une réponse et cesse de l'attendre. Écris ensuite dans `controller.res` avec `writeHead()` et `end()`. Elle renvoie `false` si la requête a déjà reçu une réponse.\n\nExample: Écrire la réponse\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nEnregistre une erreur dans le journal avec le nom du contrôleur et l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'erreur. |\n\nReturns: `Controller` Le contrôleur.\n\nL'erreur est transmise à `F.error()` et à `controller.exception` ; la requête ne reçoit pas de réponse. Un `ErrorBuilder` est en revanche renvoyé en JSON.\n\nExample: Enregistrer et continuer\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nCrée un callback qui renvoie l'erreur et ne transmet que le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | S'exécute en cas de succès avec les résultats. |\n\nReturns: `Function` Un callback `(err, a, b, c)`.\n\nLa fonction renvoyée a la forme `(err, a, b, c)`. En cas d'erreur, elle appelle `controller.invalid(err)` ; sinon, elle appelle `callback(a, b, c)` avec le contrôleur comme `this`.\n\nExample: Uniquement le cas de succès\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nCrée une URL absolue avec l'hôte de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin à ajouter. |\n\nReturns: `String` L'URL, par exemple `https://example.com/products/`.\n\nLe protocole, le nom d'hôte et le port de la requête, suivis de `path`.\n\nExample: Un lien pour un e-mail\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nRépond avec une image modifiée par le processeur d'images.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'image. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute à la fin de la réponse. |\n\nReturns: `Controller` Le contrôleur.\n\n`filename` est un fichier de `/public/` (ou un chemin complet précédé de `~`) ou un flux. `make(image)` modifie l'image avec les méthodes de `Image` (`resize()`, `quality()`, ...). Le résultat est mis en cache dans `/tmp/`. Nécessite GraphicsMagick ou ImageMagick.\n\nExample: Une miniature\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nMet en cache toute la réponse d'une action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé dans le cache. |\n| `expire` | `String|Date` | yes |  | La durée, par exemple `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` ignore le cache. |\n| `fn` | `Function` | yes |  | Crée la réponse ; s'exécute avec le contrôleur comme `this`. |\n| `fnFrom` | `Function` | no |  | S'exécute avant une réponse depuis le cache. |\n\nReturns: `Controller` Le contrôleur.\n\nLe premier appel exécute `fn` et stocke la réponse (une vue, du JSON ou du texte) sous `key` pendant `expire`. Les appels suivants répondent depuis le cache, et `fnFrom` s'exécute avant. Avec `disabled` à `true`, le cache est ignoré. Le thème est ajouté à la clé.\n\nExample: Mettre en cache la page d'accueil\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nDéfinit la meta description de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La description. |\n\nReturns: `Controller` Le contrôleur.\n\nDans le layout, elle est écrite par `@{meta}`. `controller.keywords()` définit les mots-clés et `controller.author()` l'auteur de la même manière.\n\nExample: Balises meta\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nDéfinit les meta keywords de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Les mots-clés. |\n\nReturns: `Controller` Le contrôleur.\n\nUn tableau est joint avec des virgules. Dans le layout, ils sont écrits par `@{meta}`.\n\nExample: Mots-clés\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nAjoute des balises dans le head du layout, ou les lit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Un nom de fichier ou une balise HTML. |\n\nReturns: `Controller|String` Le contrôleur, ou le HTML sans arguments.\n\nUn fichier `.css` devient un `<link>` et un fichier `.js` un `<script>` ; les noms relatifs pointent vers `/public/css/` et `/public/js/`. Une valeur qui commence par `<` est ajoutée telle quelle. Chaque valeur n'est ajoutée qu'une fois. Sans arguments, elle renvoie le HTML ; dans le layout, utilise `@{head}`.\n\nExample: Fichiers pour une seule page\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nAjoute du contenu dans un emplacement nommé du layout, ou le lit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'emplacement. |\n| `value` | `String` | no |  | Le contenu. |\n\nReturns: `Controller|String` Le contrôleur, ou le contenu avec seulement `name`.\n\nUne valeur `.js` devient un `<script>` et une valeur `.css` un `<link>` ; les autres valeurs sont ajoutées telles quelles. Dans le layout, utilise `@{place('name')}`.\n\nExample: Scripts en fin de page\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nDéfinit le thème des vues de cette requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du thème. |\n\nReturns: `Controller` Le contrôleur.\n\nLes vues, les layouts et les fichiers statiques sont alors d'abord recherchés dans `/themes/{name}/`. La valeur par défaut vient de `CONF.default_theme`.\n\nExample: Un thème par client\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nRend un composant en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du composant. |\n| `settings` | `Object` | no |  | Les paramètres du composant. |\n| `model` | `Object` | no |  | Le modèle ; par défaut le modèle de la vue. |\n\nReturns: `String` Le HTML, ou une chaîne vide pour un composant inconnu.\n\nLe composant est un fichier de `/components/`. Son CSS et son JS sont ajoutés au head du layout. Dans les vues, utilise `@{component('name')}`.\n\nExample: HTML d'un composant\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nExécute un helper de vue de `DEF.helpers`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du helper. |\n| `arg` | `Object` | no |  | Les arguments du helper. |\n\nReturns: `String` La sortie du helper.\n\nLe helper s'exécute avec le contrôleur comme `this`. Un helper inconnu renvoie une chaîne vide.\n\nExample: Utiliser un helper dans une action\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nCrée l'URL d'un fichier de `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n| `path` | `String` | no |  | Un chemin joint à une URL relative. |\n\nReturns: `String` L'URL.\n\nElle respecte les paramètres d'URL statiques et le thème. La famille `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` et `public_download()` fait de même pour son propre répertoire.\n\nExample: Une URL dans du JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `js`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n| `tag` | `Boolean` | no | `false` | Renvoie une balise HTML. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_script`, par défaut `/js/`). Avec `tag` à `true`, elle renvoie la balise HTML (`<script>` ou `<link>`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `css`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n| `tag` | `Boolean` | no | `false` | Renvoie une balise HTML. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_style`, par défaut `/css/`). Avec `tag` à `true`, elle renvoie la balise HTML (`<script>` ou `<link>`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `img`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_image`, par défaut `/img/`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `videos`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_video`, par défaut `/videos/`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `fonts`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_font`, par défaut `/fonts/`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nCrée l'URL d'un fichier du répertoire public `download`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier. |\n\nReturns: `String` L'URL.\n\nLe répertoire vient de la configuration (`static_url_download`, par défaut `/download/`).\n\nExample: URL d'un fichier\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nAjoute un test d'une route aux tests du framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La route à tester. |\n| `name` | `String` | no |  | Le nom du test. |\n| `callback` | `Function` | no |  | `function(result)` qui renvoie `true` en cas de succès. |\n\nReturns: `Object` Le test.\n\nLes tests d'un même contrôleur s'exécutent l'un après l'autre. `url` est une route comme `'GET /api/products/'` ou `'API /api/ products_query'` (le nom du test est alors l'opération). `callback(result)` reçoit `{ err, value, response, name }` et renvoie `true` lorsque le test réussit ; sans lui, un test réussit lorsqu'il n'y a pas d'erreur.\n\nExample: Tester des routes depuis une route\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nL'en-tête `Host` de la requête.\n\nReturns: `String`\n\nLe nom d'hôte avec le port, par exemple `example.com:8000`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nIndique si la requête est arrivée en HTTPS.\n\nReturns: `Boolean`\n\nIl vaut `true` lorsque le protocole est `https:` ou `wss:`.\n\nExample: Exemple\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nLe résultat de l'autorisation.\n\nReturns: `Boolean`\n\nIl vaut `true` jusqu'à l'exécution de ton délégué `AUTH()`, puis `true` lorsque le délégué a accepté l'utilisateur et `false` lorsqu'il l'a refusé.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nIndique si la requête demande un fichier statique.\n\nReturns: `Boolean`\n\nIl vaut `true` lorsque l'URL a une extension de fichier et que les fichiers statiques sont autorisés. Utile dans `DEF.onLocale` et dans les middleware.\n\nExample: Exemple\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nIndique si la requête provient de JavaScript.\n\nReturns: `Boolean`\n\nIl vaut `true` lorsque l'en-tête `X-Requested-With` vaut `XMLHttpRequest`.\n\nExample: Exemple\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nL'adresse IP du client.\n\nReturns: `String`\n\nDerrière un proxy, c'est la première adresse de `X-Forwarded-For`. Elle peut être modifiée.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nL'URL analysée de la requête.\n\nReturns: `Object`\n\nUn objet de `url.parse()` avec `pathname`, `query`, `hostname` et `port`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nLes parties du chemin en minuscules.\n\nReturns: `String[]`\n\n`/Products/Shoes/` donne `['products', 'shoes']`. `req.split` conserve la casse d'origine.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nLes parties du chemin de l'URL.\n\nReturns: `String[]`\n\nLes parties telles qu'elles apparaissent dans l'URL. Identique à `controller.split`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nLe sous-domaine sous forme de tableau, ou `null`.\n\nReturns: `String[]`\n\n`www` est ignoré. `a.localhost` donne `['a']`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nIndique si l'user agent est un appareil mobile.\n\nReturns: `Boolean`\n\nIl est déterminé à partir de l'en-tête `User-Agent`. Il peut être modifié.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nIndique si l'user agent ressemble à un robot.\n\nReturns: `Boolean`\n\nIl est déterminé à partir de l'en-tête `User-Agent`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nL'user agent analysé, sous forme de texte court avec le navigateur et le système.\n\nReturns: `String`\n\nÉquivaut à `req.useragent()`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nLa query string sous forme d'objet.\n\nReturns: `Object`\n\nElle est analysée à la première lecture et peut être modifiée.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nLe corps analysé de la requête.\n\nReturns: `Object`\n\nUn corps JSON ou de formulaire. Identique à `controller.body`.\n\nExample: Exemple\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nLes fichiers uploadés.\n\nReturns: `HttpFile[]`\n\nUn tableau d'objets `HttpFile` pour les routes avec le flag `upload`. Identique à `controller.files`.\n\nExample: Exemple\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nL'utilisateur accepté par le délégué `AUTH()`, ou `null`.\n\nReturns: `Object`\n\nIdentique à `controller.user`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nL'objet session de la requête, ou `null`.\n\nReturns: `Object`\n\nDéfini par ton délégué `AUTH()` ou par le mécanisme de session. Identique à `controller.session`.\n\nExample: Exemple\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nAnalyse l'en-tête `User-Agent`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Renvoie un objet. |\n\nReturns: `String|Object` L'user agent.\n\nSans argument, elle renvoie un texte court avec les noms trouvés dans l'en-tête, comme le navigateur et le système. Avec `true`, elle renvoie `{ os, browser, device }`, où `device` vaut `desktop`, `mobile`, `tablet` ou `tv`. Le résultat est mis en cache sur la requête.\n\nExample: Détails de l'appareil\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nLit un cookie de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du cookie. |\n\nReturns: `String` La valeur.\n\nLa valeur est décodée. Un cookie absent donne une chaîne vide. `controller.cookie(name)` fait de même.\n\nExample: Lire un cookie dans un middleware\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nLit l'en-tête d'autorisation Basic.\n\nReturns: `Object` `{ user, password, empty }`.\n\nElle décode `Authorization: Basic ...` en `{ user, password, empty }`. `empty` vaut `true` lorsque l'utilisateur ou le mot de passe est absent.\n\nExample: Authentification Basic\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nExécute toi-même le délégué `AUTH()` pour cette requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` La requête.\n\n`callback(err, user, isAuthorized)` reçoit le résultat du délégué. Sans délégué, `isAuthorized` vaut `false`. Utile pour les routes qui n'utilisent pas les flags d'autorisation.\n\nExample: Vérifier un utilisateur sur une route publique\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nSupprime les fichiers uploadés de la requête.\n\nReturns: `Request` La requête.\n\nIdentique à `controller.clear()`.\n\nExample: Supprimer les fichiers\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrée un jeton CSRF pour la requête.\n\nReturns: `String` Le jeton.\n\nIdentique à `controller.csrf()` ; elle utilise `DEF.onCSRFcreate(req)`.\n\nExample: Un jeton dans un middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nChiffre la réponse texte de cette requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `Request` La requête.\n\nLa réponse est chiffrée avec `CONF.secret_encryption` et reçoit l'en-tête `X-Encryption: a`. `controller.encrypt([enable])` fait de même.\n\nExample: Chiffrer une réponse\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nCrée une URL absolue avec l'hôte de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un chemin à ajouter. |\n\nReturns: `String` L'URL.\n\nLe protocole, le nom d'hôte et le port de la requête, suivis de `path`. Identique à `controller.hostname()`.\n\nExample: URL absolue\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nDésactive le cache HTTP de la réponse.\n\nReturns: `Request` La requête.\n\nElle appelle `res.nocache()`.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nLe contrôleur de la requête.\n\nReturns: `Controller`\n\nDéfini lorsqu'un contrôleur traite la requête.\n\nExample: Exemple\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nIndique si la réponse a été envoyée.\n\nReturns: `Boolean`\n\nIl vaut `true` après que le framework a répondu à la requête.\n\nExample: Exemple\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nDésactive la compression du HTML et des fichiers statiques pour cette réponse.\n\nReturns: `Boolean`\n\nAvec `true`, le framework ne minifie pas le HTML ni les fichiers statiques qu'il envoie.\n\nExample: Exemple\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nRépond avec un objet en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | La valeur. |\n\nReturns: `Response` La réponse.\n\nLe statut vient des options de la réponse (`200` par défaut).\n\nExample: JSON depuis une route avec (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nRépond avec un corps et un type de contenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Le statut HTTP. |\n| `body` | `String` | yes |  | Le corps. |\n| `type` | `String` | yes |  | Le type de contenu. |\n| `compress` | `Boolean` | no |  | Compression. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Response` La réponse.\n\nLes corps de plus de 4 kB sont compressés en GZIP.\n\nExample: Un CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nRépond à la manière d'Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | Le statut HTTP. |\n| `body` | `String|Object|Number` | yes |  | Le corps. |\n| `type` | `String` | no |  | Le type de contenu. |\n\nReturns: `Response` La réponse.\n\nUne chaîne est du `text/html`, un nombre est renvoyé comme le texte de ce statut, un objet est du JSON et un `ErrorBuilder` est renvoyé sous forme de ses erreurs. Elle est destinée aux middleware écrits pour Express.\n\nExample: Style Express\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nRépond avec un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Les données. |\n| `type` | `String` | yes |  | Le type de contenu. |\n| `encoding` | `String` | no |  | L'encodage du buffer. |\n| `download` | `String` | no |  | Un nom de fichier à télécharger. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n\nReturns: `Response` La réponse.\n\n`download` définit le nom de fichier de `Content-Disposition`.\n\nExample: Un fichier généré\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nRépond avec une image modifiée sans le cache de `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | L'image. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | En-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute à la fin. |\n\nReturns: `Response` La réponse.\n\nFonctionne comme `res.image()`, mais le résultat est créé à chaque requête.\n\nExample: Image avec un horodatage\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nDésactive le cache HTTP de la réponse.\n\nReturns: `Response` La réponse.\n\nElle supprime `If-None-Match` et `If-Modified-Since` de la requête et définit `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: Dans une route avec (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Response` La réponse.\n\nElle exécute la route `#409` si tu en as déclaré une.\n\nExample: Répondre 409\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nRépond avec la page d'erreur 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description du problème. |\n\nReturns: `Response` La réponse.\n\nElle exécute la route `#501` si tu en as déclaré une.\n\nExample: Répondre 501\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Controller","summary":"Proprietà e metodi del controller, l'oggetto che risponde a una richiesta.","markdown":"---\ntitle: Controller\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Controller\n\n> Proprietà e metodi del controller, l'oggetto che risponde a una richiesta.\n\nIl controller è `this` dentro ogni azione di una route. Contiene i dati della richiesta e i metodi che rispondono alla richiesta. La guida [Controller](../../guides/controllers/) spiega come usarlo con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### controller.body\n\nType: `property`\n\nIl corpo della richiesta già analizzato.\n\nReturns: `Object`\n\nUn corpo JSON o URL-encoded viene analizzato in un oggetto. I valori di un form sono stringhe. Una route con uno schema lo sostituisce con il modello validato. Puoi anche assegnare un nuovo oggetto.\n\nExample: Leggere il corpo\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nLa query string dell'URL come oggetto.\n\nReturns: `Object`\n\nI valori sono stringhe: `?page=2` dà `{ page: '2' }`. L'oggetto viene analizzato la prima volta che lo leggi.\n\nExample: Paginazione\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nI parametri dinamici dell'URL.\n\nReturns: `Object`\n\nOgni `{name}` della route diventa una chiave. I parametri dichiarati con un tipo vengono convertiti: `{id:number}` con `parseInt()`, `{active:boolean}` con `parseBoolean()` e `{date:date}` con `parseDate()`. Gli stessi valori arrivano come argomenti dell'azione.\n\nExample: Parametro tipizzato\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nI file caricati.\n\nReturns: `Array`\n\nSolo le route con il flag `upload` ricevono file. Ogni file ha `name` (il campo del form), `filename`, `type`, `size`, `extension`, `width` e `height`, e i metodi `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` e `isAudio()`. `move()`, `copy()` e `read()` restituiscono una promise senza callback. I file temporanei vengono rimossi quando la richiesta termina, a meno che tu non chiami `controller.autoclear(false)`.\n\nExample: Salvare un upload\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nL'utente autenticato.\n\nReturns: `Object`\n\nL'oggetto che il tuo delegato `AUTH()` ha passato a `$.success(user)`. È `undefined` quando nessuno è autenticato. Puoi assegnarlo.\n\nExample: Profilo\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nGli header della richiesta.\n\nReturns: `Object`\n\nI nomi degli header sono in minuscolo.\n\nExample: Leggere un header\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nL'indirizzo IP del client.\n\nReturns: `String`\n\nDietro un proxy è il primo indirizzo dell'header `X-Forwarded-For`; altrimenti l'indirizzo della connessione.\n\n### controller.url\n\nType: `property`\n\nIl percorso dell'URL della richiesta in minuscolo.\n\nReturns: `String`\n\nNon ha query string e termina sempre con `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true` quando il client è un dispositivo mobile.\n\nReturns: `Boolean`\n\nViene verificato sull'header `User-Agent`. Puoi assegnarlo.\n\n### controller.xhr\n\nType: `property`\n\n`true` quando la richiesta è stata inviata da XMLHttpRequest.\n\nReturns: `Boolean`\n\nÈ `true` quando la richiesta ha l'header `X-Requested-With: XMLHttpRequest`.\n\n### controller.language\n\nType: `property`\n\nLa lingua della richiesta.\n\nReturns: `String`\n\nÈ il valore restituito dal tuo delegato di localizzazione (`DEF.onLocale`). Le viste e `controller.mail()` traducono i testi con essa.\n\n### controller.status\n\nType: `property`\n\nIl codice di stato HTTP della risposta.\n\nReturns: `Number`\n\nImpostalo prima di rispondere. `json()`, `jsonstring()`, `plain()`, `content()` e `html()` lo usano, e usano `200` quando non è impostato. `invalid()` usa uno stato superiore a `399` per gli errori.\n\nExample: Creato\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn oggetto condiviso dalla vista e dal suo layout.\n\nReturns: `Object`\n\nI valori che salvi qui prima di `view()` sono disponibili nella vista e nel layout come `repository`. Vi vengono salvati anche il titolo della pagina e i meta tag.\n\nExample: Passare un valore al layout\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nIl problema di una route di errore.\n\nReturns: `Error|String`\n\nIn una route per uno stato di errore (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) contiene il problema passato a `throw404()`, `throw500()` e agli altri.\n\n### controller.req\n\nType: `property`\n\nL'oggetto richiesta del framework.\n\nReturns: `Request`\n\nEstende la richiesta di Node.js. Le proprietà del controller come `body`, `query` e `ip` leggono da esso.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nRisponde con un oggetto serializzato come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Il valore da serializzare. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `beautify` | `Boolean` | no | `false` | Formatta il JSON con l'indentazione. |\n| `replacer` | `Function` | no |  | Un replacer per `JSON.stringify()`. |\n\nReturns: `Controller` Il controller.\n\nIl content type è `application/json` e lo stato è `controller.status` oppure `200`. Un `ErrorBuilder` viene restituito come i suoi errori con il proprio stato. `beautify` può essere il secondo argomento.\n\nExample: Un oggetto\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Formattato\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nRisponde con un testo che è già JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Il testo JSON. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\nUsalo quando hai il JSON come stringa, per esempio da una cache. Il testo viene inviato così com'è, con il content type `application/json`.\n\nExample: Da una cache\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nRisponde con testo semplice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | Il testo. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\nIl content type è `text/plain`. Un oggetto viene serializzato come JSON formattato; `null` dà un corpo vuoto.\n\nExample: Testo\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nRisponde con HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | L'HTML. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\nEquivale a `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nRisponde con un testo e il tuo content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il contenuto. |\n| `type` | `String` | no | `text/plain` | Il content type. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\nUn `ErrorBuilder` come `body` viene restituito come JSON con il proprio stato.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenderizza una vista e risponde con essa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome della vista senza `.html`. |\n| `model` | `Object` | no |  | Il modello, disponibile nella vista come `model`. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `partial` | `Boolean` | no | `false` | Restituisce l'HTML come stringa e non risponde. Può essere il terzo argomento. |\n\nReturns: `Controller|String` Il controller, oppure l'HTML quando `partial` è `true`.\n\nLa vista è un file `name.html` in `views/`, renderizzato dentro il layout (`layout` per impostazione predefinita, vedi `controller.layout()`). Le route di un controller diverso da `default` cercano le viste in `views/<controller name>/`. Il primo carattere del nome cambia il punto in cui viene cercato il file:\n\n| Prefisso | Dove |\n| --- | --- |\n| `~` | La radice di `views/` |\n| `#plugin/view` | Le viste di un plugin |\n| `=theme/view` | Le viste di un tema |\n| `@` | Un pacchetto |\n\nSenza nome, la vista ha il nome dell'ultima parte dell'URL (`index` per `/`). Con `partial` impostato a `true` il metodo restituisce l'HTML renderizzato invece di rispondere.\n\nExample: Una pagina\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: HTML come stringa\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nSceglie il layout per la vista successiva.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista di layout, oppure una stringa vuota. |\n\nReturns: `Controller` Il controller.\n\nIl layout predefinito è `layout` (la configurazione `default_layout`). Una stringa vuota renderizza la vista senza layout.\n\nExample: Senza layout\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nImposta il titolo della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il titolo. |\n\nReturns: `Controller` Il controller.\n\nIl layout lo stampa con `@{title}`. Il testo viene codificato in HTML.\n\nExample: Titolo\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nImposta i valori meta della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Il titolo. |\n| `description` | `String` | no |  | La descrizione. |\n| `keywords` | `String|Array` | no |  | Le parole chiave. |\n| `image` | `String` | no |  | L'URL di un'immagine. |\n\nReturns: `Controller` Il controller.\n\nIl layout li stampa con `@{meta}`. `keywords` può essere un array.\n\nExample: Meta tag\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nRisponde con un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file in `public/`, oppure `~` e un percorso assoluto. |\n| `download` | `String|Boolean` | no |  | Un nome per il file scaricato; `true` usa il nome del file. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `callback` | `Function` | no |  | Viene eseguita quando il file è stato inviato. |\n\nReturns: `Controller` Il controller.\n\nIl file viene letto da `public/`. Un nome che inizia con `~` è un percorso assoluto.\n\nExample: Download\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nRisponde con un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | I dati. |\n| `type` | `String` | yes |  | Il content type. |\n| `encoding` | `String` | no |  | Una conversione dei dati. |\n| `download` | `String` | no |  | Un nome per il file scaricato. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\n`encoding` converte il buffer prima dell'invio (`binary`, `utf8`, `ascii`).\n\nExample: Un'immagine in memoria\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nRisponde con uno stream leggibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Uno stream leggibile. |\n| `type` | `String` | yes |  | Il content type. |\n| `download` | `String` | no |  | Un nome per il file scaricato. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `callback` | `Function` | no |  | Viene eseguita quando lo stream è stato inviato. |\n| `nocompress` | `Boolean` | no | `false` | Disattiva la compressione. |\n\nReturns: `Controller` Il controller.\n\nLa risposta viene compressa a meno che `nocompress` sia `true`. I primi due argomenti possono essere scambiati (`type`, `stream`).\n\nExample: Un file CSV\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nReindirizza il client a un altro URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di destinazione. |\n| `permanent` | `Boolean` | no | `false` | Invia `301 Moved Permanently`. |\n\nReturns: `Controller` Il controller.\n\nLo stato è `302`, oppure `301` quando `permanent` è `true`.\n\nExample: Dopo un form\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nRisponde con un corpo vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | Header aggiuntivi, oppure un codice di stato. |\n\nReturns: `Controller` Il controller.\n\nUn numero al posto degli header imposta il codice di stato. Per `204 No Content` puoi usare anche `controller.nocontent([headers])`.\n\nExample: Accettato\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nRisponde con il JSON `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Il valore di `success`. |\n| `value` | `Object` | no |  | Un valore aggiunto come `value`. |\n\nReturns: `Controller` Il controller.\n\n`success(value)` risponde `{ \"success\": true, \"value\": value }`. `success(false)` risponde `{ \"success\": false }`.\n\nExample: Con un valore\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nRisponde con un errore come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | Un codice di stato, il nome dell'errore o l'errore. |\n| `error` | `String` | no |  | Il testo dell'errore. |\n\nReturns: `ErrorBuilder` Il builder con gli errori.\n\nGli errori vengono restituiti come array JSON con lo stato `400` (la configurazione `default_errorbuilder_status`). Un numero come primo argomento imposta lo stato; un `Error` o un `ErrorBuilder` viene restituito così com'è. La risposta viene inviata al tick successivo, quindi puoi ancora aggiungere errori al builder restituito.\n\nExample: Validazione\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Un altro stato\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nCrea una callback che risponde con un successo o con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` aggiunge la risposta come `value`; un altro valore viene aggiunto esso stesso come `value`. |\n\nReturns: `Function` Una callback `(err, response)`.\n\nLa callback ha la forma `(err, response)`. In caso di errore chiama `controller.invalid(err)`. Altrimenti risponde `{ \"success\": true }`; con `done(true)` la risposta viene aggiunta come `value`, e con un altro valore viene aggiunto quel valore.\n\nExample: Qualsiasi callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nCrea una callback che risponde con la risposta come JSON o con una vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | Il nome di una vista. |\n\nReturns: `Function` Una callback `(err, data)`.\n\nLa callback ha la forma `(err, data)`. Quando `err` è un `ErrorBuilder` e non hai passato una vista, i suoi errori vengono restituiti come JSON. Qualsiasi altro errore risponde con la pagina di errore `404`, oppure `500` quando l'`ErrorBuilder` contiene un `Error`. Senza errori risponde con `data` come JSON, oppure renderizza la vista con `data` come modello.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: Una vista\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema, disponibile nella route di errore come `controller.exception`. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#404` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. La stessa famiglia risponde ad altri stati: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` e `throw503()`. Ognuno ha un alias chiamato `view400()` … `view503()`. Non succede nulla quando la richiesta ha già ricevuto risposta.\n\nExample: Record mancante\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: La tua pagina\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema, disponibile nella route di errore come `controller.exception`. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#403` quando ne hai dichiarata una. Alias: `view403()`.\n\nExample: Solo per gli amministratori\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nRegistra un errore nel log e risponde con la pagina di errore 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | L'errore. |\n\nReturns: `Controller` Il controller.\n\nL'errore viene registrato dal framework (`DEF.onError`). Poi viene eseguita la route `#500` quando ne hai dichiarata una. Alias: `view500()`.\n\nExample: In una promise\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLegge un cookie della richiesta o scrive un cookie nella risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del cookie. |\n| `value` | `String` | no |  | Il valore da scrivere. |\n| `expires` | `String` | no |  | Quando scade il cookie, per esempio `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` Il valore in lettura, il controller in scrittura.\n\nCon un solo argomento restituisce il valore del cookie, oppure una stringa vuota. Con un valore aggiunge un header `Set-Cookie`. `expires` è un testo come `'5 days'` o `'2 hours'`; uno negativo (`'-1 day'`) rimuove il cookie. Al posto di `expires` puoi passare l'oggetto delle opzioni con `expires` al suo interno.\n\nOpzioni: `domain`, `path` (predefinito `/`), `secure` (predefinito la configurazione `default_cookies_secure`), `httponly` e `samesite` (`Lax`, `Strict` o `None`; predefinito `Lax`, la configurazione `default_cookies_samesite`).\n\nExample: Scrivere e leggere\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Rimuovere\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nImposta un header della risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'header. |\n| `value` | `String` | yes |  | Il valore. |\n\nReturns: `Controller` Il controller.\n\nExample: Un header\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nDisattiva la cache HTTP della risposta.\n\nReturns: `Controller` Il controller.\n\nExample: Dati aggiornati\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrea un token CSRF per la richiesta corrente.\n\nReturns: `String` Il token.\n\nLe route con il flag `csrf` verificano il token dall'header `x-csrf-token` o dall'argomento `?csrf=` dell'URL. Nelle viste lo stesso token è `@{csrf}`.\n\nExample: Inviare il token\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nConserva o rimuove i file caricati quando la richiesta termina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` conserva i file. |\n\nReturns: `Controller` Il controller.\n\n`autoclear(false)` conserva i file temporanei di `controller.files` dopo la risposta, per un lavoro che prosegue in seguito. `controller.clear()` li rimuove immediatamente.\n\nExample: Elaborare in seguito\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nInvia un server-sent event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | I dati dell'evento. |\n| `eventname` | `String` | no |  | Il nome dell'evento. |\n| `id` | `String` | no |  | L'ID dell'evento. |\n| `retry` | `Number` | no |  | Quanto attende il browser prima di riconnettersi, in millisecondi. |\n\nReturns: `Boolean` `false` quando l'evento non può essere inviato (il client si è disconnesso o la richiesta ha già ricevuto risposta).\n\nLa prima chiamata risponde con gli header di `text/event-stream` e mantiene aperta la connessione. Un oggetto viene serializzato come JSON. Quando manca `retry`, la prima chiamata usa il timeout della route. L'ID dell'evento precedente inviato dal browser si trova in `controller.sseID`. Lo stream termina con `controller.close()`.\n\nExample: Un orologio\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nInoltra la richiesta a un altro URL e risponde con la sua risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | L'URL di destinazione, oppure le opzioni. |\n\nReturns: `undefined` Niente.\n\nIl metodo, il corpo, la query string e gli header della richiesta vengono inviati alla destinazione (tranne `host`, `connection`, `accept-encoding` e gli header `x-forwarded-*`). Lo stato e il corpo della risposta vengono restituiti al client. In caso di errore chiama `controller.invalid(err)`.\n\nOpzioni: `url` (obbligatorio), `method`, `headers`, `timeout` (predefinito `10000` ms) e `callback(err, response)`, che viene eseguita prima della risposta.\n\nExample: Inoltrare un'API\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nLegge l'autenticazione Basic, oppure la chiede al browser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | Il realm mostrato dal browser. |\n\nReturns: `Object|null` Le credenziali senza etichetta; `null` con un'etichetta.\n\nSenza argomento restituisce `{ user, password, empty }` dall'header `Authorization`. Con un'etichetta risponde `401` con l'header `WWW-Authenticate`, così il browser mostra una finestra di login.\n\nExample: Una pagina protetta\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nIndica se il client è ancora connesso.\n\nReturns: `Boolean`\n\nÈ `false` dopo che il client ha chiuso la connessione o dopo `controller.close()`. Controllalo nei lavori lunghi prima di rispondere.\n\nExample: Lavoro lungo\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nSempre `true` per un controller.\n\nReturns: `Boolean`\n\nUtile per distinguere un controller da un oggetto `$` in una funzione condivisa.\n\nExample: Una funzione condivisa\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nIndica se la richiesta è arrivata via HTTPS.\n\nReturns: `Boolean`\n\nÈ `true` quando il protocollo è `https:` (o `wss:`). Dietro un proxy dipende dall'URL che vede il framework. Equivale a `req.secured`.\n\nExample: Forzare HTTPS\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nL'header `Referer` della richiesta.\n\nReturns: `String`\n\nUna stringa vuota quando l'header manca.\n\nExample: Tornare indietro\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nIndica se lo user agent sembra un bot.\n\nReturns: `Boolean`\n\nCerca nell'header `User-Agent` parole come `bot`, `crawler` e `spider`.\n\nExample: Esempio\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nLo user agent analizzato, come testo breve con il browser e il sistema.\n\nReturns: `String`\n\nUsa `req.useragent(true)` per ottenere un oggetto con il browser, il sistema operativo e il dispositivo. Equivale a `req.ua`.\n\nExample: Esempio\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nL'URL della richiesta già analizzato.\n\nReturns: `Object`\n\nUn oggetto di `url.parse()` con `pathname`, `query`, `hostname` e le altre parti.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nLe parti del percorso dell'URL.\n\nReturns: `String[]`\n\n`/products/shoes/` dà `['products', 'shoes']`.\n\nExample: Esempio\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nIl sottodominio della richiesta come array.\n\nReturns: `String[]`\n\n`shop.eu.example.com` dà `['shop', 'eu']`; `www` viene ignorato. È `null` senza sottodominio.\n\nExample: Esempio\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nL'id della sessione della richiesta.\n\nReturns: `String`\n\nImpostato dal tuo delegato `AUTH()` o dal meccanismo delle sessioni. Equivale a `req.sessionid`.\n\nExample: Esempio\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nL'id dell'ultimo evento ricevuto dal browser.\n\nReturns: `String`\n\nIl valore dell'header `Last-Event-ID` che il browser invia quando si riconnette a una route di server-sent events, oppure `null`.\n\nExample: Esempio\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nLa route a cui corrisponde la richiesta.\n\nReturns: `Object`\n\nUn oggetto interno del framework con l'URL, i flag, lo schema e le opzioni della route. Leggilo, non modificarlo.\n\nExample: Esempio\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nLe opzioni personalizzate della route.\n\nReturns: `Object`\n\nL'oggetto che passi a `ROUTE()` come opzioni.\n\nExample: Esempio\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nI flag della route.\n\nReturns: `String[]`\n\nUn array con i flag della route, per esempio `['get', 'json']`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nIl nome dello schema della route.\n\nReturns: `String`\n\nPer una route come `POST /api/users/ *Users --> save` è `'Users'`. Una stringa vuota quando la route non ha uno schema.\n\nExample: Esempio\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nIl nome del controller.\n\nReturns: `String`\n\nIl nome del file in `/controllers/` (senza `.js`) che ha dichiarato la route.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nIl breadcrumb dell'elemento corrente della sitemap.\n\nReturns: `Object[]`\n\nGli elementi impostati da `controller.sitemap()`; nelle viste lo stesso elenco è in `@{sitemap}`.\n\nExample: Esempio\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nRisponde con JSONP: una chiamata di una funzione JavaScript con i dati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della funzione JavaScript. |\n| `obj` | `Object` | yes |  | I dati. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `beautify` | `Boolean` | no | `false` | Formatta il JSON. |\n| `replacer` | `Function` | no |  | Un replacer per `JSON.stringify()`. |\n\nReturns: `Controller` Il controller.\n\nIl corpo è `name(json)` con il content type `application/x-javascript`. Senza `name` la funzione è `callback`. Un `ErrorBuilder` viene restituito come i suoi errori.\n\nExample: Nome dalla query string\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#400` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view400()`.\n\nExample: Rispondere 400\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#401` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view401()`.\n\nExample: Rispondere 401\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#409` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view409()`.\n\nExample: Rispondere 409\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#501` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view501()`.\n\nExample: Rispondere 501\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Controller` Il controller.\n\nEsegue la route `#503` quando ne hai dichiarata una; altrimenti il framework renderizza la propria pagina di errore. Il problema si trova in `controller.exception` della route di errore. Alias: `controller.view503()`.\n\nExample: Rispondere 503\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias di `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 400 nello stesso modo.\n\nExample: Come throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias di `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 401 nello stesso modo.\n\nExample: Come throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias di `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 403 nello stesso modo.\n\nExample: Come throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias di `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 404 nello stesso modo.\n\nExample: Come throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias di `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 409 nello stesso modo.\n\nExample: Come throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias di `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'errore, registrato nel log dal framework. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 500 nello stesso modo.\n\nExample: Come throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias di `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 501 nello stesso modo.\n\nExample: Come throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias di `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Il problema. |\n\nReturns: `Controller` Il controller.\n\nRisponde con la pagina di errore 503 nello stesso modo.\n\nExample: Come throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nRisponde `204 No Content` senza corpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Controller` Il controller.\n\nExample: Niente da rispondere\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nChiude la connessione senza rispondere.\n\nReturns: `Controller` Il controller.\n\nIl socket viene distrutto. Non succede nulla quando la richiesta ha già ricevuto risposta.\n\nExample: Scartare una richiesta\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nTermina la risposta, soprattutto uno stream di server-sent events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Chiama `res.end()`. |\n\nReturns: `Controller` Il controller.\n\nTermina la risposta di `controller.sse()` e contrassegna il controller come disconnesso. Con `end` impostato a `false` la risposta viene solo contrassegnata come terminata.\n\nExample: Fermare uno stream\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nContrassegna il controller come annullato.\n\nReturns: `Controller` Il controller.\n\nImposta `controller.isCanceled` a `true`. Chiamato in un handler di `ON('controller')`, impedisce l'esecuzione dell'azione della route, quindi l'handler deve rispondere da sé.\n\nExample: Fermare le richieste durante la manutenzione\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nRimuove subito i file caricati della richiesta.\n\nReturns: `Controller` Il controller.\n\nI file temporanei di `controller.files` vengono eliminati e `body`, `query` e i cookie della richiesta vengono svuotati.\n\nExample: Dopo il lavoro\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nTi permette di rispondere tu stesso con la risposta di Node.js.\n\nReturns: `Boolean` `true` quando puoi rispondere.\n\nIl framework contrassegna la richiesta come già risposta e smette di attenderla. Poi scrivi su `controller.res` con `writeHead()` ed `end()`. Restituisce `false` quando la richiesta ha già ricevuto risposta.\n\nExample: Scrivere la risposta\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nRegistra nel log un errore con il nome del controller e l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'errore. |\n\nReturns: `Controller` Il controller.\n\nL'errore va a `F.error()` e a `controller.exception`; alla richiesta non viene data risposta. Un `ErrorBuilder` invece viene restituito come JSON.\n\nExample: Registrare e continuare\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nCrea una callback che risponde con l'errore e passa oltre solo il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Viene eseguita in caso di successo con i risultati. |\n\nReturns: `Function` Una callback `(err, a, b, c)`.\n\nLa funzione restituita ha la forma `(err, a, b, c)`. In caso di errore chiama `controller.invalid(err)`; altrimenti chiama `callback(a, b, c)` con il controller come `this`.\n\nExample: Solo il percorso di successo\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nCrea un URL assoluto con l'host della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso da aggiungere. |\n\nReturns: `String` L'URL, per esempio `https://example.com/products/`.\n\nIl protocollo, il nome host e la porta della richiesta, con `path` aggiunto.\n\nExample: Un link per un'email\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nRisponde con un'immagine modificata dall'elaboratore di immagini.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'immagine. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `callback` | `Function` | no |  | Viene eseguita quando la risposta termina. |\n\nReturns: `Controller` Il controller.\n\n`filename` è un file in `/public/` (oppure un percorso completo preceduto da `~`) o uno stream. `make(image)` modifica l'immagine con i metodi di `Image` (`resize()`, `quality()`, ...). Il risultato viene messo in cache in `/tmp/`. Richiede GraphicsMagick o ImageMagick.\n\nExample: Una miniatura\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nMette in cache l'intera risposta di un'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave nella cache. |\n| `expire` | `String|Date` | yes |  | Per quanto tempo, per esempio `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` salta la cache. |\n| `fn` | `Function` | yes |  | Crea la risposta; viene eseguita con il controller come `this`. |\n| `fnFrom` | `Function` | no |  | Viene eseguita prima di una risposta dalla cache. |\n\nReturns: `Controller` Il controller.\n\nLa prima chiamata esegue `fn` e salva la risposta (una vista, JSON o testo) sotto `key` per `expire`. Le chiamate successive rispondono dalla cache, e prima viene eseguita `fnFrom`. Con `disabled` impostato a `true` la cache viene saltata. Il tema viene aggiunto alla chiave.\n\nExample: Mettere in cache la home page\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nImposta la meta description della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La descrizione. |\n\nReturns: `Controller` Il controller.\n\nNel layout viene scritta da `@{meta}`. `controller.keywords()` imposta le parole chiave e `controller.author()` l'autore nello stesso modo.\n\nExample: Meta tag\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nImposta le meta keywords della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Le parole chiave. |\n\nReturns: `Controller` Il controller.\n\nUn array viene unito con virgole. Nel layout vengono scritte da `@{meta}`.\n\nExample: Parole chiave\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nAggiunge tag nell'head del layout, oppure li legge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Il nome di un file o un tag HTML. |\n\nReturns: `Controller|String` Il controller, oppure l'HTML senza argomenti.\n\nUn file `.css` diventa un `<link>` e un file `.js` uno `<script>`; i nomi relativi puntano a `/public/css/` e `/public/js/`. Un valore che inizia con `<` viene aggiunto così com'è. Ogni valore viene aggiunto una sola volta. Senza argomenti restituisce l'HTML; nel layout usa `@{head}`.\n\nExample: File per una pagina\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nAggiunge contenuto in un punto con nome del layout, oppure lo legge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del punto. |\n| `value` | `String` | no |  | Il contenuto. |\n\nReturns: `Controller|String` Il controller, oppure il contenuto con solo `name`.\n\nUn valore `.js` diventa uno `<script>` e un valore `.css` un `<link>`; gli altri valori vengono aggiunti così come sono. Nel layout usa `@{place('name')}`.\n\nExample: Script alla fine della pagina\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nImposta il tema delle viste di questa richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del tema. |\n\nReturns: `Controller` Il controller.\n\nViste, layout e file statici vengono quindi cercati prima in `/themes/{name}/`. Il valore predefinito proviene da `CONF.default_theme`.\n\nExample: Un tema per cliente\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nRenderizza un componente in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del componente. |\n| `settings` | `Object` | no |  | Le impostazioni del componente. |\n| `model` | `Object` | no |  | Il modello; per impostazione predefinita il modello della vista. |\n\nReturns: `String` L'HTML, oppure una stringa vuota per un componente sconosciuto.\n\nIl componente è un file in `/components/`. Il suo CSS e il suo JS vengono aggiunti all'head del layout. Nelle viste usa `@{component('name')}`.\n\nExample: HTML di un componente\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nEsegue un helper di vista da `DEF.helpers`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'helper. |\n| `arg` | `Object` | no |  | Argomenti per l'helper. |\n\nReturns: `String` L'output dell'helper.\n\nL'helper viene eseguito con il controller come `this`. Un helper sconosciuto restituisce una stringa vuota.\n\nExample: Usare un helper in un'azione\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nCrea l'URL di un file in `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n| `path` | `String` | no |  | Un percorso unito a un URL relativo. |\n\nReturns: `String` L'URL.\n\nRispetta le impostazioni degli URL statici e il tema. La famiglia `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` e `public_download()` fa lo stesso per la propria cartella.\n\nExample: Un URL in JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `js`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n| `tag` | `Boolean` | no | `false` | Restituisce un tag HTML. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_script`, predefinito `/js/`). Con `tag` impostato a `true` restituisce il tag HTML (`<script>` o `<link>`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `css`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n| `tag` | `Boolean` | no | `false` | Restituisce un tag HTML. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_style`, predefinito `/css/`). Con `tag` impostato a `true` restituisce il tag HTML (`<script>` o `<link>`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `img`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_image`, predefinito `/img/`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `videos`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_video`, predefinito `/videos/`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `fonts`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_font`, predefinito `/fonts/`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nCrea l'URL di un file nella cartella pubblica `download`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file. |\n\nReturns: `String` L'URL.\n\nLa cartella proviene dalla configurazione (`static_url_download`, predefinito `/download/`).\n\nExample: URL di un file\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nAggiunge un test di una route ai test del framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La route da testare. |\n| `name` | `String` | no |  | Il nome del test. |\n| `callback` | `Function` | no |  | `function(result)` che restituisce `true` in caso di successo. |\n\nReturns: `Object` Il test.\n\nI test di un controller vengono eseguiti uno dopo l'altro. `url` è una route come `'GET /api/products/'` o `'API /api/ products_query'` (in quel caso il nome del test è l'operazione). `callback(result)` riceve `{ err, value, response, name }` e restituisce `true` quando il test passa; senza di essa, un test passa quando non c'è errore.\n\nExample: Testare le route da una route\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nL'header `Host` della richiesta.\n\nReturns: `String`\n\nIl nome host con la porta, per esempio `example.com:8000`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nIndica se la richiesta è arrivata via HTTPS.\n\nReturns: `Boolean`\n\nÈ `true` quando il protocollo è `https:` o `wss:`.\n\nExample: Esempio\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nIl risultato dell'autorizzazione.\n\nReturns: `Boolean`\n\nÈ `true` finché il tuo delegato `AUTH()` non viene eseguito; poi è `true` quando il delegato ha accettato l'utente e `false` quando lo ha rifiutato.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nIndica se la richiesta chiede un file statico.\n\nReturns: `Boolean`\n\nÈ `true` quando l'URL ha un'estensione di file e i file statici sono consentiti. Utile in `DEF.onLocale` e nei middleware.\n\nExample: Esempio\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nIndica se la richiesta è arrivata da JavaScript.\n\nReturns: `Boolean`\n\nÈ `true` quando l'header `X-Requested-With` è `XMLHttpRequest`.\n\nExample: Esempio\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nL'indirizzo IP del client.\n\nReturns: `String`\n\nDietro un proxy è il primo indirizzo di `X-Forwarded-For`. Può essere impostato.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nL'URL della richiesta già analizzato.\n\nReturns: `Object`\n\nUn oggetto di `url.parse()` con `pathname`, `query`, `hostname` e `port`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nLe parti del percorso in minuscolo.\n\nReturns: `String[]`\n\n`/Products/Shoes/` dà `['products', 'shoes']`. `req.split` mantiene le maiuscole e minuscole originali.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nLe parti del percorso dell'URL.\n\nReturns: `String[]`\n\nLe parti così come erano nell'URL. Equivale a `controller.split`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nIl sottodominio come array, oppure `null`.\n\nReturns: `String[]`\n\n`www` viene ignorato. `a.localhost` dà `['a']`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nIndica se lo user agent è un dispositivo mobile.\n\nReturns: `Boolean`\n\nVerifica l'header `User-Agent`. Può essere impostato.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nIndica se lo user agent sembra un bot.\n\nReturns: `Boolean`\n\nVerifica l'header `User-Agent`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nLo user agent analizzato, come testo breve con il browser e il sistema.\n\nReturns: `String`\n\nEquivale a `req.useragent()`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nLa query string come oggetto.\n\nReturns: `Object`\n\nViene analizzata alla prima lettura e può essere impostata.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nIl corpo della richiesta già analizzato.\n\nReturns: `Object`\n\nUn corpo JSON o di un form. Equivale a `controller.body`.\n\nExample: Esempio\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nI file caricati.\n\nReturns: `HttpFile[]`\n\nUn array di oggetti `HttpFile` per le route con il flag `upload`. Equivale a `controller.files`.\n\nExample: Esempio\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nL'utente accettato dal delegato `AUTH()`, oppure `null`.\n\nReturns: `Object`\n\nEquivale a `controller.user`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nL'oggetto sessione della richiesta, oppure `null`.\n\nReturns: `Object`\n\nImpostato dal tuo delegato `AUTH()` o dal meccanismo delle sessioni. Equivale a `controller.session`.\n\nExample: Esempio\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nAnalizza l'header `User-Agent`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Restituisce un oggetto. |\n\nReturns: `String|Object` Lo user agent.\n\nSenza argomento restituisce un testo breve con i nomi trovati nell'header, come il browser e il sistema. Con `true` restituisce `{ os, browser, device }`, dove `device` è `desktop`, `mobile`, `tablet` o `tv`. Il risultato viene messo in cache sulla richiesta.\n\nExample: Dettagli del dispositivo\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nLegge un cookie della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del cookie. |\n\nReturns: `String` Il valore.\n\nIl valore viene decodificato. Un cookie mancante dà una stringa vuota. `controller.cookie(name)` fa lo stesso.\n\nExample: Leggere un cookie in un middleware\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nLegge l'header di autorizzazione Basic.\n\nReturns: `Object` `{ user, password, empty }`.\n\nDecodifica `Authorization: Basic ...` in `{ user, password, empty }`. `empty` è `true` quando manca l'utente o la password.\n\nExample: Autenticazione Basic\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nEsegue manualmente il delegato `AUTH()` per questa richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` La richiesta.\n\n`callback(err, user, isAuthorized)` riceve il risultato del delegato. Senza delegato `isAuthorized` è `false`. Utile per le route che non usano i flag di autorizzazione.\n\nExample: Verificare un utente su una route pubblica\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nRimuove i file caricati della richiesta.\n\nReturns: `Request` La richiesta.\n\nEquivale a `controller.clear()`.\n\nExample: Svuotare i file\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nCrea un token CSRF per la richiesta.\n\nReturns: `String` Il token.\n\nEquivale a `controller.csrf()`; usa `DEF.onCSRFcreate(req)`.\n\nExample: Un token in un middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nCifra la risposta testuale di questa richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` la disattiva. |\n\nReturns: `Request` La richiesta.\n\nLa risposta viene cifrata con `CONF.secret_encryption` e riceve l'header `X-Encryption: a`. `controller.encrypt([enable])` fa lo stesso.\n\nExample: Cifrare una risposta\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nCrea un URL assoluto con l'host della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Un percorso da aggiungere. |\n\nReturns: `String` L'URL.\n\nIl protocollo, il nome host e la porta della richiesta, con `path` aggiunto. Equivale a `controller.hostname()`.\n\nExample: URL assoluto\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nDisattiva la cache HTTP della risposta.\n\nReturns: `Request` La richiesta.\n\nChiama `res.nocache()`.\n\nExample: In un middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nIl controller della richiesta.\n\nReturns: `Controller`\n\nImpostato quando un controller gestisce la richiesta.\n\nExample: Esempio\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nIndica se la risposta è stata inviata.\n\nReturns: `Boolean`\n\nÈ `true` dopo che il framework ha risposto alla richiesta.\n\nExample: Esempio\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nDisattiva la compressione dell'HTML e dei file statici per questa risposta.\n\nReturns: `Boolean`\n\nCon `true` il framework non minifica l'HTML e i file statici che invia.\n\nExample: Esempio\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nRisponde con un oggetto come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Il valore. |\n\nReturns: `Response` La risposta.\n\nLo stato proviene dalle opzioni della risposta (`200` per impostazione predefinita).\n\nExample: JSON da una route con (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nRisponde con un corpo e un content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Lo stato HTTP. |\n| `body` | `String` | yes |  | Il corpo. |\n| `type` | `String` | yes |  | Il content type. |\n| `compress` | `Boolean` | no |  | Compressione. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Response` La risposta.\n\nI corpi oltre 4 kB vengono compressi con GZIP.\n\nExample: Un CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nRisponde nello stile di Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | Lo stato HTTP. |\n| `body` | `String|Object|Number` | yes |  | Il corpo. |\n| `type` | `String` | no |  | Il content type. |\n\nReturns: `Response` La risposta.\n\nUna stringa è `text/html`, un numero viene restituito come il testo di quello stato, un oggetto è JSON e un `ErrorBuilder` viene restituito come i suoi errori. È pensato per i middleware scritti per Express.\n\nExample: Stile Express\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nRisponde con un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | I dati. |\n| `type` | `String` | yes |  | Il content type. |\n| `encoding` | `String` | no |  | La codifica del buffer. |\n| `download` | `String` | no |  | Un nome di file da scaricare. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n\nReturns: `Response` La risposta.\n\n`download` imposta il nome del file di `Content-Disposition`.\n\nExample: Un file generato\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nRisponde con un'immagine modificata senza la cache di `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | L'immagine. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Header aggiuntivi della risposta. |\n| `callback` | `Function` | no |  | Viene eseguita alla fine. |\n\nReturns: `Response` La risposta.\n\nFunziona come `res.image()`, ma il risultato viene creato per ogni richiesta.\n\nExample: Immagine con un timestamp\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nDisattiva la cache HTTP della risposta.\n\nReturns: `Response` La risposta.\n\nRimuove `If-None-Match` e `If-Modified-Since` dalla richiesta e imposta `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: In una route con (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Response` La risposta.\n\nEsegue la route `#409` quando ne hai dichiarata una.\n\nExample: Rispondere 409\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nRisponde con la pagina di errore 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione del problema. |\n\nReturns: `Response` La risposta.\n\nEsegue la route `#501` quando ne hai dichiarata una.\n\nExample: Rispondere 501\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabU9G1fU60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/controller/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Kontrolér","summary":"Vlastnosti a metódy kontroléra, objektu, ktorý odpovedá na požiadavku.","markdown":"---\ntitle: \"Kontrolér\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/controller/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Kontrolér\n\n> Vlastnosti a metódy kontroléra, objektu, ktorý odpovedá na požiadavku.\n\nKontrolér je `this` vnútri každej akcie trasy. Obsahuje dáta požiadavky a metódy, ktoré na požiadavku odpovedajú. Príručka [Kontroléry](../../guides/controllers/) vysvetľuje jeho použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### controller.body\n\nType: `property`\n\nSpracované telo požiadavky.\n\nReturns: `Object`\n\nTelo vo formáte JSON alebo URL-encoded sa spracuje do objektu. Hodnoty formulára sú reťazce. Trasa so schémou ho nahradí validovaným modelom. Môžeš priradiť aj nový objekt.\n\nExample: Čítanie tela\n```js\nexports.install = function() {\n\tROUTE('POST /api/contact/', contact);\n};\n\nfunction contact() {\n\tvar email = this.body.email;\n\tthis.success();\n}\n```\n\n### controller.query\n\nType: `property`\n\nQuery string URL ako objekt.\n\nReturns: `Object`\n\nHodnoty sú reťazce: `?page=2` dáva `{ page: '2' }`. Objekt sa spracuje pri prvom čítaní.\n\nExample: Stránkovanie\n```js\nfunction list() {\n\tvar page = (this.query.page || '1').parseInt();\n\tthis.json({ page: page });\n}\n```\n\n### controller.params\n\nType: `property`\n\nDynamické parametre URL.\n\nReturns: `Object`\n\nKaždé `{name}` trasy sa stane kľúčom. Parametre deklarované s typom sa skonvertujú: `{id:number}` pomocou `parseInt()`, `{active:boolean}` pomocou `parseBoolean()` a `{date:date}` pomocou `parseDate()`. Rovnaké hodnoty prichádzajú ako argumenty akcie.\n\nExample: Typovaný parameter\n```js\nexports.install = function() {\n\tROUTE('GET /orders/{id:number}/', order);\n};\n\nfunction order(id) {\n\t// this.params.id is a number\n\tthis.json({ id: this.params.id });\n}\n```\n\n### controller.files\n\nType: `property`\n\nNahrané súbory.\n\nReturns: `Array`\n\nSúbory dostávajú len trasy s flagom `upload`. Každý súbor má `name` (pole formulára), `filename`, `type`, `size`, `extension`, `width` a `height` a metódy `move(path)`, `copy(path)`, `read()`, `isImage()`, `isVideo()` a `isAudio()`. `move()`, `copy()` a `read()` bez callbacku vrátia promise. Dočasné súbory sa odstránia, keď požiadavka skončí, pokiaľ nezavoláš `controller.autoclear(false)`.\n\nExample: Uloženie nahraného súboru\n```js\nexports.install = function() {\n\tROUTE('POST /upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tawait file.move(PATH.public('uploads/' + file.filename));\n\tthis.success();\n}\n```\n\n### controller.user\n\nType: `property`\n\nPrihlásený používateľ.\n\nReturns: `Object`\n\nObjekt, ktorý tvoj delegát `AUTH()` odovzdal do `$.success(user)`. Je `undefined`, keď nie je nikto prihlásený. Môžeš ho priradiť.\n\nExample: Profil\n```js\nexports.install = function() {\n\tROUTE('+GET /api/profile/', profile);\n};\n\nfunction profile() {\n\tthis.json({ name: this.user.name });\n}\n```\n\n### controller.headers\n\nType: `property`\n\nHlavičky požiadavky.\n\nReturns: `Object`\n\nNázvy hlavičiek sú malými písmenami.\n\nExample: Čítanie hlavičky\n```js\nfunction api() {\n\tvar token = this.headers['x-token'];\n\tthis.plain(token ? 'ok' : 'missing');\n}\n```\n\n### controller.ip\n\nType: `property`\n\nIP adresa klienta.\n\nReturns: `String`\n\nZa proxy je to prvá adresa z hlavičky `X-Forwarded-For`; inak adresa spojenia.\n\n### controller.url\n\nType: `property`\n\nCesta URL požiadavky malými písmenami.\n\nReturns: `String`\n\nNemá query string a vždy končí na `/`.\n\n### controller.mobile\n\nType: `property`\n\n`true`, keď je klient mobilné zariadenie.\n\nReturns: `Boolean`\n\nTestuje sa podľa hlavičky `User-Agent`. Môžeš ju priradiť.\n\n### controller.xhr\n\nType: `property`\n\n`true`, keď požiadavku poslal XMLHttpRequest.\n\nReturns: `Boolean`\n\nJe `true`, keď má požiadavka hlavičku `X-Requested-With: XMLHttpRequest`.\n\n### controller.language\n\nType: `property`\n\nJazyk požiadavky.\n\nReturns: `String`\n\nJe to hodnota, ktorú vráti tvoj lokalizačný delegát (`DEF.onLocale`). Views a `controller.mail()` podľa neho prekladajú texty.\n\n### controller.status\n\nType: `property`\n\nHTTP stavový kód odpovede.\n\nReturns: `Number`\n\nNastav ho predtým, ako odpovieš. Používajú ho `json()`, `jsonstring()`, `plain()`, `content()` a `html()`, a keď nie je nastavený, použijú `200`. `invalid()` používa pre chyby stav nad `399`.\n\nExample: Vytvorené\n```js\nfunction create() {\n\tthis.status = 201;\n\tthis.json({ id: UID() });\n}\n```\n\n### controller.repository\n\nType: `property`\n\nObjekt zdieľaný medzi view a jeho layoutom.\n\nReturns: `Object`\n\nHodnoty, ktoré sem uložíš pred `view()`, sú dostupné vo view aj v layoute ako `repository`. Ukladá sa sem aj titulok stránky a meta značky.\n\nExample: Odovzdanie hodnoty layoutu\n```js\nfunction home() {\n\tthis.repository.menu = 'home';\n\tthis.view('index');\n}\n```\n\n### controller.exception\n\nType: `property`\n\nProblém chybovej trasy.\n\nReturns: `Error|String`\n\nV trase pre chybový stav (`ROUTE('#404', ...)`, `ROUTE('#500', ...)`) obsahuje problém odovzdaný do `throw404()`, `throw500()` a ostatných.\n\n### controller.req\n\nType: `property`\n\nObjekt požiadavky frameworku.\n\nReturns: `Request`\n\nRozširuje Node.js požiadavku. Vlastnosti kontroléra ako `body`, `query` a `ip` čítajú z neho.\n\n### controller.json(obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nOdpovie objektom serializovaným ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Hodnota na serializáciu. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `beautify` | `Boolean` | no | `false` | Naformátuje JSON s odsadením. |\n| `replacer` | `Function` | no |  | Replacer pre `JSON.stringify()`. |\n\nReturns: `Controller` Kontrolér.\n\nTyp obsahu je `application/json` a stav je `controller.status` alebo `200`. Na `ErrorBuilder` sa odpovie jeho chybami s jeho vlastným stavom. `beautify` môže byť druhý argument.\n\nExample: Objekt\n```js\nexports.install = function() {\n\tROUTE('GET /api/products/', products);\n};\n\nfunction products() {\n\tthis.json([{ id: 1, name: 'Book' }]);\n}\n```\n\nExample: Naformátované\n```js\nthis.json({ name: 'Peter' }, true);\n```\n\n### controller.jsonstring(str, [headers])\n\nType: `method` · Since: `0.0.57`\n\nOdpovie textom, ktorý už je JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Text JSON. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\nPouži ju, keď máš JSON ako reťazec, napríklad z cache. Text sa pošle tak, ako je, s typom obsahu `application/json`.\n\nExample: Z cache\n```js\nfunction list() {\n\tthis.jsonstring('[{\"id\":1}]');\n}\n```\n\n### controller.plain(body, [headers])\n\nType: `method`\n\nOdpovie čistým textom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String|Object` | yes |  | Text. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\nTyp obsahu je `text/plain`. Objekt sa serializuje ako formátovaný JSON; `null` dáva prázdne telo.\n\nExample: Text\n```js\nfunction home() {\n\tthis.plain('Hello world');\n}\n```\n\n### controller.html(body, [headers])\n\nType: `method`\n\nOdpovie pomocou HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | HTML. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\nTo isté ako `content(body, 'text/html', headers)`.\n\nExample: HTML\n```js\nfunction home() {\n\tthis.html('<h1>Hello</h1>');\n}\n```\n\n### controller.content(body, type, [headers])\n\nType: `method`\n\nOdpovie textom s tvojím typom obsahu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Obsah. |\n| `type` | `String` | no | `text/plain` | Typ obsahu. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\nNa `ErrorBuilder` ako `body` sa odpovie ako JSON s jeho vlastným stavom.\n\nExample: XML\n```js\nfunction feed() {\n\tthis.content('<rss></rss>', 'application/xml');\n}\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nVykreslí view a odpovie ním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov view bez `.html`. |\n| `model` | `Object` | no |  | Model, dostupný vo view ako `model`. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `partial` | `Boolean` | no | `false` | Vráti HTML ako reťazec a neodpovie. Môže to byť tretí argument. |\n\nReturns: `Controller|String` Kontrolér, alebo HTML, keď je `partial` nastavené na `true`.\n\nView je súbor `name.html` vo `views/`, vykreslený vnútri layoutu (predvolene `layout`, pozri `controller.layout()`). Trasy iného kontroléra ako `default` hľadajú views vo `views/<controller name>/`. Prvý znak názvu mení, kde sa súbor hľadá:\n\n| Prefix | Kde |\n| --- | --- |\n| `~` | Koreň `views/` |\n| `#plugin/view` | Views pluginu |\n| `=theme/view` | Views témy |\n| `@` | Balík |\n\nBez názvu je view pomenované podľa poslednej časti URL (`index` pre `/`). S `partial` nastaveným na `true` metóda namiesto odpovede vráti vykreslené HTML.\n\nExample: Stránka\n```js\nexports.install = function() {\n\tROUTE('GET /', home);\n};\n\nfunction home() {\n\tthis.view('index', { title: 'Home' });\n}\n```\n\nExample: HTML ako reťazec\n```js\nvar html = this.view('~mail/order', order, true);\n```\n\n### controller.layout(name)\n\nType: `method`\n\nVyberie layout pre nasledujúce view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov view layoutu alebo prázdny reťazec. |\n\nReturns: `Controller` Kontrolér.\n\nPredvolený layout je `layout` (konfigurácia `default_layout`). Prázdny reťazec vykreslí view bez layoutu.\n\nExample: Bez layoutu\n```js\nfunction widget() {\n\tthis.layout('');\n\tthis.view('widget');\n}\n```\n\n### controller.title(value)\n\nType: `method`\n\nNastaví titulok stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Titulok. |\n\nReturns: `Controller` Kontrolér.\n\nLayout ho vypíše pomocou `@{title}`. Text sa zakóduje pre HTML.\n\nExample: Titulok\n```js\nthis.title('Products');\nthis.view('products');\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nNastaví meta hodnoty stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Titulok. |\n| `description` | `String` | no |  | Popis. |\n| `keywords` | `String|Array` | no |  | Kľúčové slová. |\n| `image` | `String` | no |  | URL obrázka. |\n\nReturns: `Controller` Kontrolér.\n\nLayout ich vypíše pomocou `@{meta}`. `keywords` môže byť pole.\n\nExample: Meta značky\n```js\nthis.meta('Products', 'All our products', ['shop', 'books']);\nthis.view('products');\n```\n\n### controller.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nOdpovie súborom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor v `public/`, alebo `~` a absolútna cesta. |\n| `download` | `String|Boolean` | no |  | Názov stiahnutého súboru; `true` použije názov súboru. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa, keď je súbor odoslaný. |\n\nReturns: `Controller` Kontrolér.\n\nSúbor sa číta z `public/`. Názov, ktorý začína na `~`, je absolútna cesta.\n\nExample: Stiahnutie\n```js\nfunction invoice() {\n\tthis.file('~' + PATH.private('invoices/1.pdf'), 'invoice.pdf');\n}\n```\n\n### controller.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nOdpovie bufferom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Dáta. |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `encoding` | `String` | no |  | Konverzia dát. |\n| `download` | `String` | no |  | Názov stiahnutého súboru. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\n`encoding` skonvertuje buffer pred odoslaním (`binary`, `utf8`, `ascii`).\n\nExample: Obrázok v pamäti\n```js\nfunction pixel() {\n\tvar buffer = Buffer.from('R0lGODlhAQABAAAAACw=', 'base64');\n\tthis.binary(buffer, 'image/gif');\n}\n```\n\n### controller.stream(stream, type, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nOdpovie čitateľným streamom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Čitateľný stream. |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `download` | `String` | no |  | Názov stiahnutého súboru. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa, keď je stream odoslaný. |\n| `nocompress` | `Boolean` | no | `false` | Vypne kompresiu. |\n\nReturns: `Controller` Kontrolér.\n\nOdpoveď sa komprimuje, pokiaľ `nocompress` nie je `true`. Prvé dva argumenty sa dajú vymeniť (`type`, `stream`).\n\nExample: CSV súbor\n```js\nfunction exportcsv() {\n\tvar stream = Fs.createReadStream(PATH.databases('export.csv'));\n\tthis.stream(stream, 'text/csv', 'export.csv');\n}\n```\n\n### controller.redirect(url, [permanent])\n\nType: `method`\n\nPresmeruje klienta na inú URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová URL. |\n| `permanent` | `Boolean` | no | `false` | Pošle `301 Moved Permanently`. |\n\nReturns: `Controller` Kontrolér.\n\nStav je `302`, alebo `301`, keď je `permanent` nastavené na `true`.\n\nExample: Po odoslaní formulára\n```js\nfunction save() {\n\tthis.redirect('/thanks/');\n}\n```\n\n### controller.empty([headers])\n\nType: `method`\n\nOdpovie prázdnym telom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object|Number` | no |  | Ďalšie hlavičky alebo stavový kód. |\n\nReturns: `Controller` Kontrolér.\n\nČíslo namiesto hlavičiek nastaví stavový kód. Pre `204 No Content` použi aj `controller.nocontent([headers])`.\n\nExample: Prijaté\n```js\nthis.empty(202);\n```\n\n### controller.success([success], [value])\n\nType: `method`\n\nOdpovie JSON-om `{ \"success\": true }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Hodnota `success`. |\n| `value` | `Object` | no |  | Hodnota pridaná ako `value`. |\n\nReturns: `Controller` Kontrolér.\n\n`success(value)` odpovie `{ \"success\": true, \"value\": value }`. `success(false)` odpovie `{ \"success\": false }`.\n\nExample: S hodnotou\n```js\nfunction create() {\n\tvar id = UID();\n\tthis.success(true, id);\n\t// {\"success\":true,\"value\":\"...\"}\n}\n```\n\n### controller.invalid([status], [error])\n\nType: `method`\n\nOdpovie chybou ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `status` | `Number|String|Error|ErrorBuilder` | no |  | Stavový kód, názov chyby alebo chyba. |\n| `error` | `String` | no |  | Text chyby. |\n\nReturns: `ErrorBuilder` Builder s chybami.\n\nNa chyby sa odpovie ako JSON pole so stavom `400` (konfigurácia `default_errorbuilder_status`). Číslo ako prvý argument nastaví stav; na `Error` alebo `ErrorBuilder` sa odpovie tak, ako je. Odpoveď sa pošle v nasledujúcom ticku, takže do vráteného buildera môžeš ešte pridať chyby.\n\nExample: Validácia\n```js\nfunction save() {\n\tif (!this.body.email)\n\t\treturn this.invalid('email', 'The email is required');\n\tthis.success();\n}\n```\n\nExample: Iný stav\n```js\nthis.invalid(409, 'The user exists');\n```\n\n### controller.done([value])\n\nType: `method`\n\nVytvorí callback, ktorý odpovie úspechom alebo chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` pridá odpoveď ako `value`; iná hodnota sa pridá ako `value` sama. |\n\nReturns: `Function` Callback `(err, response)`.\n\nCallback má tvar `(err, response)`. Pri chybe zavolá `controller.invalid(err)`. Inak odpovie `{ \"success\": true }`; s `done(true)` sa odpoveď pridá ako `value` a s inou hodnotou sa pridá táto hodnota.\n\nExample: Ľubovoľný callback (err, response)\n```js\nfunction remove(id) {\n\t// removeproduct(id, callback) is your own function\n\tremoveproduct(id, this.done());\n}\n\nfunction create() {\n\t// answers { \"success\": true, \"value\": response }\n\tcreateproduct(this.body, this.done(true));\n}\n```\n\n### controller.callback([view])\n\nType: `method`\n\nVytvorí callback, ktorý odpovie odpoveďou ako JSON alebo pomocou view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `view` | `String` | no |  | Názov view. |\n\nReturns: `Function` Callback `(err, data)`.\n\nCallback má tvar `(err, data)`. Keď je `err` `ErrorBuilder` a neodovzdal si view, odpovie sa jeho chybami ako JSON. Akákoľvek iná chyba odpovie chybovou stránkou `404`, alebo `500`, keď `ErrorBuilder` obsahuje `Error`. Bez chyby odpovie `data` ako JSON alebo vykreslí view s `data` ako modelom.\n\nExample: JSON\n```js\nfunction list() {\n\t// loadproducts(callback) is your own function\n\tloadproducts(this.callback());\n}\n```\n\nExample: View\n```js\nfunction list() {\n\tloadproducts(this.callback('products'));\n}\n```\n\n### controller.throw404([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému, dostupný v chybovej trase ako `controller.exception`. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#404`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Rovnaká rodina odpovedá aj inými stavmi: `throw400()`, `throw401()`, `throw403()`, `throw409()`, `throw500()`, `throw501()` a `throw503()`. Každá má alias s názvom `view400()` … `view503()`. Ak už bolo na požiadavku odpovedané, nestane sa nič.\n\nExample: Chýbajúci záznam\n```js\nfunction detail(id) {\n\tvar self = this;\n\t// findproduct(id, callback) is your own function\n\tfindproduct(id, function(err, item) {\n\t\tif (item)\n\t\t\tself.view('detail', item);\n\t\telse\n\t\t\tself.throw404();\n\t});\n}\n```\n\nExample: Vlastná stránka\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n```\n\n### controller.throw403([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému, dostupný v chybovej trase ako `controller.exception`. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#403`, ak si nejakú deklaroval. Alias: `view403()`.\n\nExample: Len pre adminov\n```js\nfunction admin() {\n\tif (!this.user.admin)\n\t\treturn this.throw403();\n\tthis.view('admin');\n}\n```\n\n### controller.throw500([error])\n\nType: `method`\n\nZaloguje chybu a odpovie chybovou stránkou 500.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error|String` | no |  | Chyba. |\n\nReturns: `Controller` Kontrolér.\n\nChybu zaloguje framework (`DEF.onError`). Potom sa spustí trasa `#500`, ak si nejakú deklaroval. Alias: `view500()`.\n\nExample: V promise\n```js\nasync function stats() {\n\ttry {\n\t\tthis.json(await loadstats());\n\t} catch (err) {\n\t\tthis.throw500(err);\n\t}\n}\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nPrečíta cookie požiadavky alebo zapíše cookie do odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String` | no |  | Hodnota na zápis. |\n| `expires` | `String` | no |  | Kedy cookie vyprší, napríklad `'7 days'`. |\n| `options` | `Object` | no |  | `domain`, `path`, `secure`, `httponly`, `samesite`. |\n\nReturns: `String|Controller` Pri čítaní hodnota, pri zápise kontrolér.\n\nS jedným argumentom vráti hodnotu cookie alebo prázdny reťazec. S hodnotou pridá hlavičku `Set-Cookie`. `expires` je text ako `'5 days'` alebo `'2 hours'`; záporný (`'-1 day'`) cookie odstráni. Namiesto `expires` môžeš odovzdať objekt možností s `expires` vnútri.\n\nMožnosti: `domain`, `path` (predvolene `/`), `secure` (predvolene konfigurácia `default_cookies_secure`), `httponly` a `samesite` (`Lax`, `Strict` alebo `None`; predvolene `Lax`, konfigurácia `default_cookies_samesite`).\n\nExample: Zápis a čítanie\n```js\nfunction login() {\n\tthis.cookie('session', 'token', '7 days', { httponly: true });\n\tthis.redirect('/');\n}\n\nfunction home() {\n\tvar session = this.cookie('session');\n\tthis.plain(session);\n}\n```\n\nExample: Odstránenie\n```js\nthis.cookie('session', '', '-1 day');\n```\n\n### controller.header(name, value)\n\nType: `method`\n\nNastaví hlavičku odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov hlavičky. |\n| `value` | `String` | yes |  | Hodnota. |\n\nReturns: `Controller` Kontrolér.\n\nExample: Hlavička\n```js\nthis.header('X-Total', '42');\nthis.json(items);\n```\n\n### controller.nocache()\n\nType: `method`\n\nVypne HTTP cache odpovede.\n\nReturns: `Controller` Kontrolér.\n\nExample: Čerstvé dáta\n```js\nfunction stats() {\n\tthis.nocache();\n\tthis.json(getstats());\n}\n```\n\n### controller.csrf()\n\nType: `method` · Since: `0.0.37`\n\nVytvorí CSRF token pre aktuálnu požiadavku.\n\nReturns: `String` Token.\n\nTrasy s flagom `csrf` overujú token z hlavičky `x-csrf-token` alebo z argumentu URL `?csrf=`. Vo views je rovnaký token `@{csrf}`.\n\nExample: Odoslanie tokenu\n```js\nexports.install = function() {\n\tROUTE('GET /api/token/', token);\n\tROUTE('POST /api/save/ csrf', save);\n};\n\nfunction token() {\n\tthis.json({ token: this.csrf() });\n}\n```\n\n### controller.autoclear([enable])\n\nType: `method`\n\nPonechá alebo odstráni nahrané súbory, keď požiadavka skončí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` súbory ponechá. |\n\nReturns: `Controller` Kontrolér.\n\n`autoclear(false)` ponechá dočasné súbory `controller.files` aj po odpovedi, pre prácu, ktorá pokračuje neskôr. `controller.clear()` ich odstráni okamžite.\n\nExample: Spracovanie neskôr\n```js\nfunction upload() {\n\tthis.autoclear(false);\n\tvar file = this.files[0];\n\tthis.success();\n\t// file.path stays on the disk: process it, then remove it\n}\n```\n\n### controller.sse(data, [eventname], [id], [retry])\n\nType: `method`\n\nPošle server-sent event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String|Object` | yes |  | Dáta udalosti. |\n| `eventname` | `String` | no |  | Názov udalosti. |\n| `id` | `String` | no |  | ID udalosti. |\n| `retry` | `Number` | no |  | Ako dlho prehliadač čaká, kým sa znova pripojí, v milisekundách. |\n\nReturns: `Boolean` `false`, keď sa udalosť nedá odoslať (klient sa odpojil alebo už bolo na požiadavku odpovedané).\n\nPrvé volanie odpovie hlavičkami `text/event-stream` a ponechá spojenie otvorené. Objekt sa serializuje ako JSON. Keď `retry` chýba, prvé volanie použije časový limit trasy. Predchádzajúce ID udalosti, ktoré poslal prehliadač, je v `controller.sseID`. Stream skončí pomocou `controller.close()`.\n\nExample: Hodiny\n```js\nexports.install = function() {\n\tROUTE('GET /clock/', clock, ['delay']);\n};\n\nfunction clock() {\n\tvar self = this;\n\tvar timer = setInterval(function() {\n\t\tif (!self.sse({ time: new Date() }))\n\t\t\tclearInterval(timer);\n\t}, 1000);\n}\n```\n\n### controller.proxy(options)\n\nType: `method`\n\nPrepošle požiadavku na inú URL a odpovie jej odpoveďou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object|String` | yes |  | Cieľová URL alebo možnosti. |\n\nReturns: `undefined` Nič.\n\nMetóda, telo, query string a hlavičky požiadavky sa pošlú na cieľ (okrem `host`, `connection`, `accept-encoding` a hlavičiek `x-forwarded-*`). Stav a telo odpovede sa vrátia späť. Pri chybe zavolá `controller.invalid(err)`.\n\nMožnosti: `url` (povinné), `method`, `headers`, `timeout` (predvolene `10000` ms) a `callback(err, response)`, ktorý sa spustí pred odpoveďou.\n\nExample: Preposlanie API\n```js\nexports.install = function() {\n\tROUTE('GET /api/weather/', weather);\n};\n\nfunction weather() {\n\tthis.proxy('https://api.example.com/weather');\n}\n```\n\n### controller.baa([label])\n\nType: `method`\n\nPrečíta Basic access autentifikáciu alebo si ju vypýta od prehliadača.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `label` | `String` | no |  | Realm, ktorý zobrazí prehliadač. |\n\nReturns: `Object|null` Bez označenia prihlasovacie údaje; s označením `null`.\n\nBez argumentu vráti `{ user, password, empty }` z hlavičky `Authorization`. S označením odpovie `401` s hlavičkou `WWW-Authenticate`, takže prehliadač zobrazí prihlasovacie okno.\n\nExample: Chránená stránka\n```js\nfunction admin() {\n\tvar auth = this.baa();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.baa('Administration');\n\t\treturn;\n\t}\n\tthis.view('admin');\n}\n```\n\n### controller.isConnected\n\nType: `property`\n\nZistí, či je klient stále pripojený.\n\nReturns: `Boolean`\n\nJe `false` po tom, ako klient zatvoril spojenie, alebo po `controller.close()`. Pri dlhej práci to over predtým, ako odpovieš.\n\nExample: Dlhá práca\n```js\nfunction report() {\n\tvar self = this;\n\t// longtask(callback) is your own function\n\tlongtask(function(err, data) {\n\t\tif (self.isConnected)\n\t\t\tself.json(data);\n\t});\n}\n```\n\n### controller.isController\n\nType: `property`\n\nPre kontrolér vždy `true`.\n\nReturns: `Boolean`\n\nHodí sa na rozlíšenie kontroléra od objektu `$` v zdieľanej funkcii.\n\nExample: Zdieľaná funkcia\n```js\nfunction getuser(ctx) {\n\treturn ctx.isController ? ctx.user : ctx.controller.user;\n}\n```\n\n### controller.secured\n\nType: `property`\n\nZistí, či požiadavka prišla cez HTTPS.\n\nReturns: `Boolean`\n\nJe `true`, keď je protokol `https:` (alebo `wss:`). Za proxy závisí od URL, ktorú vidí framework. To isté ako `req.secured`.\n\nExample: Vynútenie HTTPS\n```js\nfunction index() {\n\tif (!this.secured)\n\t\treturn this.redirect('https://' + this.req.host + this.url);\n\tthis.view('index');\n}\n```\n\n### controller.referrer\n\nType: `property`\n\nHlavička `Referer` požiadavky.\n\nReturns: `String`\n\nPrázdny reťazec, keď hlavička chýba.\n\nExample: Návrat späť\n```js\nfunction back() {\n\tthis.redirect(this.referrer || '/');\n}\n```\n\n### controller.robot\n\nType: `property`\n\nZistí, či user agent vyzerá ako bot.\n\nReturns: `Boolean`\n\nTestuje hlavičku `User-Agent` na slová ako `bot`, `crawler` a `spider`.\n\nExample: Príklad\n```js\nfunction index() {\n\tif (this.robot)\n\t\treturn this.plain('Hello robot');\n\tthis.view('index');\n}\n```\n\n### controller.ua\n\nType: `property`\n\nSpracovaný user agent ako krátky text s prehliadačom a systémom.\n\nReturns: `String`\n\nPouži `req.useragent(true)`, ak chceš objekt s prehliadačom, OS a zariadením. To isté ako `req.ua`.\n\nExample: Príklad\n```js\nfunction index() {\n\tconsole.log(this.ua);\n\tthis.view('index');\n}\n```\n\n### controller.uri\n\nType: `property`\n\nSpracovaná URL požiadavky.\n\nReturns: `Object`\n\nObjekt z `url.parse()` s `pathname`, `query`, `hostname` a ďalšími časťami.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.uri.pathname + ' ' + (this.uri.query || ''));\n}\n```\n\n### controller.split\n\nType: `property`\n\nČasti cesty URL.\n\nReturns: `String[]`\n\n`/products/shoes/` dáva `['products', 'shoes']`.\n\nExample: Príklad\n```js\n// GET /docs/{page}/\nfunction docs() {\n\tthis.plain(this.split.join(' > '));\n}\n```\n\n### controller.subdomain\n\nType: `property`\n\nSubdoména požiadavky ako pole.\n\nReturns: `String[]`\n\n`shop.eu.example.com` dáva `['shop', 'eu']`; `www` sa ignoruje. Bez subdomény je `null`.\n\nExample: Príklad\n```js\nfunction index() {\n\tvar tenant = this.subdomain ? this.subdomain[0] : 'default';\n\tthis.view('index', { tenant: tenant });\n}\n```\n\n### controller.sessionid\n\nType: `property`\n\nID relácie požiadavky.\n\nReturns: `String`\n\nNastavuje ho tvoj delegát `AUTH()` alebo mechanizmus relácií. To isté ako `req.sessionid`.\n\nExample: Príklad\n```js\nfunction logout() {\n\t// removesession(id) is your own function\n\tremovesession(this.sessionid);\n\tthis.redirect('/');\n}\n```\n\n### controller.sseID\n\nType: `property`\n\nID poslednej udalosti, ktorú prehliadač prijal.\n\nReturns: `String`\n\nHodnota hlavičky `Last-Event-ID`, ktorú prehliadač pošle, keď sa znova pripojí k trase so server-sent events, alebo `null`.\n\nExample: Príklad\n```js\nfunction events() {\n\tvar last = this.sseID;\n\tthis.sse({ resumed: !!last });\n}\n```\n\n### controller.route\n\nType: `property`\n\nTrasa, ktorej požiadavka zodpovedala.\n\nReturns: `Object`\n\nInterný objekt frameworku s URL, flagmi, schémou a možnosťami trasy. Čítaj ho, nemeň ho.\n\nExample: Príklad\n```js\nfunction index() {\n\tconsole.log(this.route.url);\n\tthis.empty();\n}\n```\n\n### controller.options\n\nType: `property`\n\nVlastné možnosti trasy.\n\nReturns: `Object`\n\nObjekt, ktorý odovzdáš do `ROUTE()` ako možnosti.\n\nExample: Príklad\n```js\nexports.install = function() {\n\tROUTE('GET /reports/', report, { title: 'Reports' });\n};\n\nfunction report() {\n\tthis.plain(this.options.title);\n}\n```\n\n### controller.flags\n\nType: `property`\n\nFlagy trasy.\n\nReturns: `String[]`\n\nPole s flagmi trasy, napríklad `['get', 'json']`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.flags);\n}\n```\n\n### controller.schema\n\nType: `property`\n\nNázov schémy trasy.\n\nReturns: `String`\n\nPre trasu ako `POST /api/users/ *Users --> save` je to `'Users'`. Prázdny reťazec, keď trasa nemá schému.\n\nExample: Príklad\n```js\nfunction action() {\n\tconsole.log(this.schema);\n\tthis.empty();\n}\n```\n\n### controller.name\n\nType: `property`\n\nNázov kontroléra.\n\nReturns: `String`\n\nNázov súboru v `/controllers/` (bez `.js`), ktorý trasu deklaroval.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.name);\n}\n```\n\n### controller.breadcrumb\n\nType: `property`\n\nDrobčeková navigácia aktuálnej položky sitemapy.\n\nReturns: `Object[]`\n\nPoložky nastavené pomocou `controller.sitemap()`; vo views je rovnaký zoznam v `@{sitemap}`.\n\nExample: Príklad\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.json(this.breadcrumb);\n}\n```\n\n### controller.jsonp(name, obj, [headers], [beautify], [replacer])\n\nType: `method`\n\nOdpovie pomocou JSONP: volaním JavaScriptovej funkcie s dátami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov JavaScriptovej funkcie. |\n| `obj` | `Object` | yes |  | Dáta. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `beautify` | `Boolean` | no | `false` | Naformátuje JSON. |\n| `replacer` | `Function` | no |  | Replacer pre `JSON.stringify()`. |\n\nReturns: `Controller` Kontrolér.\n\nTelo je `name(json)` s typom obsahu `application/x-javascript`. Bez `name` je funkcia `callback`. Na `ErrorBuilder` sa odpovie jeho chybami.\n\nExample: Názov z query stringu\n```js\nfunction data() {\n\tthis.jsonp(this.query.callback, { count: 10 });\n}\n```\n\n### controller.throw400([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#400`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Problém je v `controller.exception` chybovej trasy. Alias: `controller.view400()`.\n\nExample: Odpoveď 400\n```js\nfunction action() {\n\tthis.throw400('Bad Request');\n}\n```\n\n### controller.throw401([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#401`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Problém je v `controller.exception` chybovej trasy. Alias: `controller.view401()`.\n\nExample: Odpoveď 401\n```js\nfunction action() {\n\tthis.throw401('Unauthorized');\n}\n```\n\n### controller.throw409([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#409`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Problém je v `controller.exception` chybovej trasy. Alias: `controller.view409()`.\n\nExample: Odpoveď 409\n```js\nfunction action() {\n\tthis.throw409('Conflict');\n}\n```\n\n### controller.throw501([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#501`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Problém je v `controller.exception` chybovej trasy. Alias: `controller.view501()`.\n\nExample: Odpoveď 501\n```js\nfunction action() {\n\tthis.throw501('Not Implemented');\n}\n```\n\n### controller.throw503([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Controller` Kontrolér.\n\nSpustí trasu `#503`, ak si nejakú deklaroval; inak framework vykreslí vlastnú chybovú stránku. Problém je v `controller.exception` chybovej trasy. Alias: `controller.view503()`.\n\nExample: Odpoveď 503\n```js\nfunction action() {\n\tthis.throw503('Service Unavailable');\n}\n```\n\n### controller.view400([problem])\n\nType: `method`\n\nAlias `controller.throw400()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 400 rovnakým spôsobom.\n\nExample: To isté ako throw400()\n```js\nfunction detail() {\n\tthis.view400();\n}\n```\n\n### controller.view401([problem])\n\nType: `method`\n\nAlias `controller.throw401()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 401 rovnakým spôsobom.\n\nExample: To isté ako throw401()\n```js\nfunction detail() {\n\tthis.view401();\n}\n```\n\n### controller.view403([problem])\n\nType: `method`\n\nAlias `controller.throw403()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 403 rovnakým spôsobom.\n\nExample: To isté ako throw403()\n```js\nfunction detail() {\n\tthis.view403();\n}\n```\n\n### controller.view404([problem])\n\nType: `method`\n\nAlias `controller.throw404()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 404 rovnakým spôsobom.\n\nExample: To isté ako throw404()\n```js\nfunction detail() {\n\tthis.view404();\n}\n```\n\n### controller.view409([problem])\n\nType: `method`\n\nAlias `controller.throw409()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 409 rovnakým spôsobom.\n\nExample: To isté ako throw409()\n```js\nfunction detail() {\n\tthis.view409();\n}\n```\n\n### controller.view500([error])\n\nType: `method`\n\nAlias `controller.throw500()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Chyba, ktorú zaloguje framework. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 500 rovnakým spôsobom.\n\nExample: To isté ako throw500()\n```js\nfunction detail() {\n\tthis.view500();\n}\n```\n\n### controller.view501([problem])\n\nType: `method`\n\nAlias `controller.throw501()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 501 rovnakým spôsobom.\n\nExample: To isté ako throw501()\n```js\nfunction detail() {\n\tthis.view501();\n}\n```\n\n### controller.view503([problem])\n\nType: `method`\n\nAlias `controller.throw503()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Problém. |\n\nReturns: `Controller` Kontrolér.\n\nOdpovie chybovou stránkou 503 rovnakým spôsobom.\n\nExample: To isté ako throw503()\n```js\nfunction detail() {\n\tthis.view503();\n}\n```\n\n### controller.nocontent([headers])\n\nType: `method`\n\nOdpovie `204 No Content` bez tela.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Controller` Kontrolér.\n\nExample: Nie je čo odpovedať\n```js\nfunction ping() {\n\tthis.nocontent();\n}\n```\n\n### controller.destroy()\n\nType: `method`\n\nZatvorí spojenie bez odpovede.\n\nReturns: `Controller` Kontrolér.\n\nSocket sa zničí. Ak už bolo na požiadavku odpovedané, nestane sa nič.\n\nExample: Zahodenie požiadavky\n```js\nfunction upload() {\n\tif (this.req.headers['content-length'] > 1000000)\n\t\treturn this.destroy();\n\tthis.success();\n}\n```\n\n### controller.close([end])\n\nType: `method`\n\nUkončí odpoveď, najmä stream server-sent events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `end` | `Boolean` | no | `true` | Zavolá `res.end()`. |\n\nReturns: `Controller` Kontrolér.\n\nUkončí odpoveď `controller.sse()` a označí kontrolér ako odpojený. S `end` nastaveným na `false` sa odpoveď len označí ako dokončená.\n\nExample: Zastavenie streamu\n```js\nfunction events() {\n\tvar self = this;\n\tself.sse({ step: 1 });\n\tsetTimeout(function() {\n\t\tself.close();\n\t}, 5000);\n}\n```\n\n### controller.cancel()\n\nType: `method`\n\nOznačí kontrolér ako zrušený.\n\nReturns: `Controller` Kontrolér.\n\nNastaví `controller.isCanceled` na `true`. Ak sa zavolá v handleri `ON('controller')`, zabráni spusteniu akcie trasy, takže handler musí odpovedať sám.\n\nExample: Zastavenie požiadaviek počas údržby\n```js\nON('controller', function(controller) {\n\tif (CONF.maintenance) {\n\t\tcontroller.cancel();\n\t\tcontroller.throw503('Maintenance');\n\t}\n});\n```\n\n### controller.clear()\n\nType: `method`\n\nHneď odstráni nahrané súbory požiadavky.\n\nReturns: `Controller` Kontrolér.\n\nDočasné súbory `controller.files` sa zmažú a `body`, `query` a cookies požiadavky sa vyprázdnia.\n\nExample: Po dokončení práce\n```js\nfunction upload() {\n\tvar self = this;\n\tvar file = self.files[0];\n\tfile.move(PATH.databases(file.filename), function() {\n\t\tself.clear();\n\t\tself.success();\n\t});\n}\n```\n\n### controller.custom()\n\nType: `method`\n\nUmožní ti odpovedať sám pomocou Node.js odpovede.\n\nReturns: `Boolean` `true`, keď môžeš odpovedať.\n\nFramework označí požiadavku ako zodpovedanú a prestane na ňu čakať. Potom zapisuj do `controller.res` pomocou `writeHead()` a `end()`. Vráti `false`, keď už bolo na požiadavku odpovedané.\n\nExample: Zápis odpovede\n```js\nfunction raw() {\n\tif (this.custom()) {\n\t\tthis.res.writeHead(200, { 'Content-Type': 'text/plain' });\n\t\tthis.res.end('OK');\n\t}\n}\n```\n\n### controller.error(err)\n\nType: `method`\n\nZaloguje chybu s názvom kontroléra a URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Chyba. |\n\nReturns: `Controller` Kontrolér.\n\nChyba ide do `F.error()` a do `controller.exception`; na požiadavku sa neodpovie. Na `ErrorBuilder` sa namiesto toho odpovie ako JSON.\n\nExample: Zalogovanie a pokračovanie\n```js\nfunction action() {\n\tthis.error(new Error('Cache is empty'));\n\tthis.json([]);\n}\n```\n\n### controller.successful(callback)\n\nType: `method`\n\nVytvorí callback, ktorý odpovie chybou a ďalej odovzdá len výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Spustí sa pri úspechu s výsledkami. |\n\nReturns: `Function` Callback `(err, a, b, c)`.\n\nVrátená funkcia má tvar `(err, a, b, c)`. Pri chybe zavolá `controller.invalid(err)`; inak zavolá `callback(a, b, c)` s kontrolérom ako `this`.\n\nExample: Len cesta úspechu\n```js\nfunction detail(id) {\n\tNOSQL('products').one().where('id', id).callback(this.successful(function(item) {\n\t\tthis.view('detail', item);\n\t}));\n}\n```\n\n### controller.hostname([path])\n\nType: `method`\n\nVytvorí absolútnu URL s hostiteľom požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Cesta na pridanie. |\n\nReturns: `String` URL, napríklad `https://example.com/products/`.\n\nProtokol, názov hostiteľa a port požiadavky s pridanou cestou `path`.\n\nExample: Odkaz do e-mailu\n```js\nfunction invite() {\n\tthis.json({ url: this.hostname('/invite/' + UID() + '/') });\n}\n```\n\n### controller.image(filename, make, [headers], [callback])\n\nType: `method`\n\nOdpovie obrázkom upraveným procesorom obrázkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Obrázok. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa, keď odpoveď skončí. |\n\nReturns: `Controller` Kontrolér.\n\n`filename` je súbor v `/public/` (alebo úplná cesta s `~` na začiatku) alebo stream. `make(image)` upraví obrázok metódami `Image` (`resize()`, `quality()`, ...). Výsledok sa uloží do cache v `/tmp/`. Vyžaduje GraphicsMagick alebo ImageMagick.\n\nExample: Náhľad\n```js\nfunction thumbnail() {\n\tthis.image('/img/photo.jpg', function(image) {\n\t\timage.resize(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### controller.memorize(key, expire, [disabled], fn, [fnFrom])\n\nType: `method`\n\nUloží do cache celú odpoveď akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč v cache. |\n| `expire` | `String|Date` | yes |  | Ako dlho, napríklad `'5 minutes'`. |\n| `disabled` | `Boolean` | no | `false` | `true` preskočí cache. |\n| `fn` | `Function` | yes |  | Vytvorí odpoveď; beží s kontrolérom ako `this`. |\n| `fnFrom` | `Function` | no |  | Spustí sa pred odpoveďou z cache. |\n\nReturns: `Controller` Kontrolér.\n\nPrvé volanie spustí `fn` a uloží odpoveď (view, JSON alebo text) pod `key` na dobu `expire`. Ďalšie volania odpovedajú z cache a predtým sa spustí `fnFrom`. S `disabled` nastaveným na `true` sa cache preskočí. Ku kľúču sa pridá téma.\n\nExample: Cache domovskej stránky\n```js\nfunction index() {\n\tthis.memorize('home', '5 minutes', DEBUG, function() {\n\t\tthis.view('index');\n\t});\n}\n```\n\n### controller.description(value)\n\nType: `method`\n\nNastaví meta popis stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Popis. |\n\nReturns: `Controller` Kontrolér.\n\nV layoute ho zapíše `@{meta}`. `controller.keywords()` rovnakým spôsobom nastaví kľúčové slová a `controller.author()` autora.\n\nExample: Meta značky\n```js\nfunction index() {\n\tthis.title('Shop');\n\tthis.description('Shoes and clothes');\n\tthis.view('index');\n}\n```\n\n### controller.keywords(value)\n\nType: `method`\n\nNastaví meta kľúčové slová stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | yes |  | Kľúčové slová. |\n\nReturns: `Controller` Kontrolér.\n\nPole sa spojí čiarkami. V layoute ich zapíše `@{meta}`.\n\nExample: Kľúčové slová\n```js\nfunction index() {\n\tthis.keywords(['shoes', 'clothes']);\n\tthis.view('index');\n}\n```\n\n### controller.head([value], [...])\n\nType: `method`\n\nPridá značky do hlavičky (head) layoutu alebo ich prečíta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Názov súboru alebo HTML značka. |\n\nReturns: `Controller|String` Kontrolér, alebo HTML bez argumentov.\n\nSúbor `.css` sa stane `<link>` a súbor `.js` `<script>`; relatívne názvy smerujú do `/public/css/` a `/public/js/`. Hodnota, ktorá začína na `<`, sa pridá tak, ako je. Každá hodnota sa pridá raz. Bez argumentov vráti HTML; v layoute použi `@{head}`.\n\nExample: Súbory pre jednu stránku\n```js\nfunction editor() {\n\tthis.head('editor.css', 'editor.js');\n\tthis.view('editor');\n}\n```\n\n### controller.place(name, [value], [...])\n\nType: `method`\n\nPridá obsah na pomenované miesto layoutu alebo ho prečíta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov miesta. |\n| `value` | `String` | no |  | Obsah. |\n\nReturns: `Controller|String` Kontrolér, alebo obsah, keď je zadané len `name`.\n\nHodnota `.js` sa stane `<script>` a hodnota `.css` `<link>`; ostatné hodnoty sa pridajú tak, ako sú. V layoute použi `@{place('name')}`.\n\nExample: Skripty na konci stránky\n```js\nfunction index() {\n\tthis.place('footer', '/js/chart.js');\n\tthis.view('index');\n}\n```\n\n### controller.theme(name)\n\nType: `method`\n\nNastaví tému views tejto požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov témy. |\n\nReturns: `Controller` Kontrolér.\n\nViews, layouty a statické súbory sa potom hľadajú najprv v `/themes/{name}/`. Predvolená hodnota pochádza z `CONF.default_theme`.\n\nExample: Téma pre každého zákazníka\n```js\nfunction index() {\n\tthis.theme(this.query.dark ? 'dark' : 'default');\n\tthis.view('index');\n}\n```\n\n### controller.component(name, [settings], [model])\n\nType: `method`\n\nVykreslí komponent do HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov komponentu. |\n| `settings` | `Object` | no |  | Nastavenia komponentu. |\n| `model` | `Object` | no |  | Model; predvolene model view. |\n\nReturns: `String` HTML, alebo prázdny reťazec pre neznámy komponent.\n\nKomponent je súbor v `/components/`. Jeho CSS a JS sa pridajú do hlavičky (head) layoutu. Vo views použi `@{component('name')}`.\n\nExample: HTML komponentu\n```js\nfunction widget() {\n\tthis.html(this.component('chart', { color: 'red' }));\n}\n```\n\n### controller.helper(name, [arg], [...])\n\nType: `method`\n\nSpustí pomocnú funkciu view z `DEF.helpers`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pomocnej funkcie. |\n| `arg` | `Object` | no |  | Argumenty pre pomocnú funkciu. |\n\nReturns: `String` Výstup pomocnej funkcie.\n\nPomocná funkcia beží s kontrolérom ako `this`. Neznáma pomocná funkcia vráti prázdny reťazec.\n\nExample: Použitie pomocnej funkcie v akcii\n```js\nDEF.helpers.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\nfunction price() {\n\tthis.plain(this.helper('price', 10));\n}\n```\n\n### controller.public(name, [path])\n\nType: `method`\n\nVytvorí URL súboru v `/public/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n| `path` | `String` | no |  | Cesta pripojená k relatívnej URL. |\n\nReturns: `String` URL.\n\nRešpektuje nastavenia statických URL a tému. Rodina `controller.public_js()`, `public_css()`, `public_image()`, `public_video()`, `public_font()` a `public_download()` robí to isté pre svoj vlastný priečinok.\n\nExample: URL v JSON\n```js\nfunction config() {\n\tthis.json({ logo: this.public_image('logo.png'), file: this.public('docs/terms.pdf') });\n}\n```\n\n### controller.public_js(name, [tag])\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `js`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n| `tag` | `Boolean` | no | `false` | Vráti HTML značku. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_script`, predvolene `/js/`). S `tag` nastaveným na `true` vráti HTML značku (`<script>` alebo `<link>`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_js('app.js'));\n}\n```\n\n### controller.public_css(name, [tag])\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `css`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n| `tag` | `Boolean` | no | `false` | Vráti HTML značku. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_style`, predvolene `/css/`). S `tag` nastaveným na `true` vráti HTML značku (`<script>` alebo `<link>`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_css('app.css'));\n}\n```\n\n### controller.public_image(name)\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `img`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_image`, predvolene `/img/`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_image('logo.png'));\n}\n```\n\n### controller.public_video(name)\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `videos`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_video`, predvolene `/videos/`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_video('intro.mp4'));\n}\n```\n\n### controller.public_font(name)\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `fonts`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_font`, predvolene `/fonts/`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_font('icons.woff2'));\n}\n```\n\n### controller.public_download(name)\n\nType: `method`\n\nVytvorí URL súboru vo verejnom priečinku `download`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor. |\n\nReturns: `String` URL.\n\nPriečinok pochádza z konfigurácie (`static_url_download`, predvolene `/download/`).\n\nExample: URL súboru\n```js\nfunction index() {\n\tthis.plain(this.public_download('manual.pdf'));\n}\n```\n\n### controller.runtest(url, [name], [callback])\n\nType: `method`\n\nPridá test trasy do testov frameworku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Trasa na otestovanie. |\n| `name` | `String` | no |  | Názov testu. |\n| `callback` | `Function` | no |  | `function(result)`, ktorá pri úspechu vráti `true`. |\n\nReturns: `Object` Test.\n\nTesty jedného kontroléra bežia jeden po druhom. `url` je trasa ako `'GET /api/products/'` alebo `'API /api/ products_query'` (vtedy je názvom testu operácia). `callback(result)` dostane `{ err, value, response, name }` a vráti `true`, keď test prejde; bez neho test prejde, keď nenastane chyba.\n\nExample: Testovanie trás z trasy\n```js\nfunction selftest() {\n\tthis.runtest('GET /api/products/', function(result) {\n\t\treturn !result.err && result.value instanceof Array;\n\t});\n\tthis.success();\n}\n```\n\n### req.host\n\nType: `property`\n\nHlavička `Host` požiadavky.\n\nReturns: `String`\n\nNázov hostiteľa s portom, napríklad `example.com:8000`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.host);\n}\n```\n\n### req.secured\n\nType: `property`\n\nZistí, či požiadavka prišla cez HTTPS.\n\nReturns: `Boolean`\n\nJe `true`, keď je protokol `https:` alebo `wss:`.\n\nExample: Príklad\n```js\nMIDDLEWARE('https', function($) {\n\tif ($.req.secured)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('https://' + $.req.host + $.req.url);\n});\n```\n\n### req.isAuthorized\n\nType: `property`\n\nVýsledok autorizácie.\n\nReturns: `Boolean`\n\nJe `true`, kým sa nespustí tvoj delegát `AUTH()`; potom je `true`, keď delegát používateľa prijal, a `false`, keď ho odmietol.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.isAuthorized ? 'Signed in' : 'Guest');\n}\n```\n\n### req.isStaticFile\n\nType: `property`\n\nZistí, či požiadavka žiada statický súbor.\n\nReturns: `Boolean`\n\nJe `true`, keď má URL príponu súboru a statické súbory sú povolené. Hodí sa v `DEF.onLocale` a v middleware.\n\nExample: Príklad\n```js\nDEF.onLocale = function(req) {\n\treturn req.isStaticFile ? '' : (req.query.lang || 'en');\n};\n```\n\n### req.xhr\n\nType: `property`\n\nZistí, či požiadavka prišla z JavaScriptu.\n\nReturns: `Boolean`\n\nJe `true`, keď je hlavička `X-Requested-With` rovná `XMLHttpRequest`.\n\nExample: Príklad\n```js\nfunction index() {\n\tif (this.req.xhr)\n\t\tthis.json({ ok: true });\n\telse\n\t\tthis.view('index');\n}\n```\n\n### req.ip\n\nType: `property`\n\nIP adresa klienta.\n\nReturns: `String`\n\nZa proxy je to prvá adresa z `X-Forwarded-For`. Dá sa nastaviť.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.ip);\n}\n```\n\n### req.uri\n\nType: `property`\n\nSpracovaná URL požiadavky.\n\nReturns: `Object`\n\nObjekt z `url.parse()` s `pathname`, `query`, `hostname` a `port`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.uri.pathname);\n}\n```\n\n### req.path\n\nType: `property`\n\nČasti cesty malými písmenami.\n\nReturns: `String[]`\n\n`/Products/Shoes/` dáva `['products', 'shoes']`. `req.split` zachová pôvodnú veľkosť písmen.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.path);\n}\n```\n\n### req.split\n\nType: `property`\n\nČasti cesty URL.\n\nReturns: `String[]`\n\nČasti tak, ako boli v URL. To isté ako `controller.split`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.split);\n}\n```\n\n### req.subdomain\n\nType: `property`\n\nSubdoména ako pole alebo `null`.\n\nReturns: `String[]`\n\n`www` sa ignoruje. `a.localhost` dáva `['a']`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.subdomain);\n}\n```\n\n### req.mobile\n\nType: `property`\n\nZistí, či je user agent mobilné zariadenie.\n\nReturns: `Boolean`\n\nTestuje hlavičku `User-Agent`. Dá sa nastaviť.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.view(this.req.mobile ? 'mobile' : 'index');\n}\n```\n\n### req.robot\n\nType: `property`\n\nZistí, či user agent vyzerá ako bot.\n\nReturns: `Boolean`\n\nTestuje hlavičku `User-Agent`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.robot ? 'bot' : 'human');\n}\n```\n\n### req.ua\n\nType: `property`\n\nSpracovaný user agent ako krátky text s prehliadačom a systémom.\n\nReturns: `String`\n\nTo isté ako `req.useragent()`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.plain(this.req.ua);\n}\n```\n\n### req.query\n\nType: `property`\n\nQuery string ako objekt.\n\nReturns: `Object`\n\nSpracuje sa pri prvom čítaní a dá sa nastaviť.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.query);\n}\n```\n\n### req.body\n\nType: `property`\n\nSpracované telo požiadavky.\n\nReturns: `Object`\n\nTelo vo formáte JSON alebo formulára. To isté ako `controller.body`.\n\nExample: Príklad\n```js\nfunction save() {\n\tthis.json(this.req.body);\n}\n```\n\n### req.files\n\nType: `property`\n\nNahrané súbory.\n\nReturns: `HttpFile[]`\n\nPole objektov `HttpFile` pre trasy s flagom `upload`. To isté ako `controller.files`.\n\nExample: Príklad\n```js\nfunction upload() {\n\tthis.json(this.req.files.map(function(file) {\n\t\treturn file.filename;\n\t}));\n}\n```\n\n### req.user\n\nType: `property`\n\nPoužívateľ prijatý delegátom `AUTH()`, alebo `null`.\n\nReturns: `Object`\n\nTo isté ako `controller.user`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.user);\n}\n```\n\n### req.session\n\nType: `property`\n\nObjekt relácie požiadavky, alebo `null`.\n\nReturns: `Object`\n\nNastavuje ho tvoj delegát `AUTH()` alebo mechanizmus relácií. To isté ako `controller.session`.\n\nExample: Príklad\n```js\nfunction index() {\n\tthis.json(this.req.session);\n}\n```\n\n### req.useragent([structured])\n\nType: `method`\n\nSpracuje hlavičku `User-Agent`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Vráti objekt. |\n\nReturns: `String|Object` User agent.\n\nBez argumentu vráti krátky text s názvami nájdenými v hlavičke, napríklad prehliadačom a systémom. S `true` vráti `{ os, browser, device }`, kde `device` je `desktop`, `mobile`, `tablet` alebo `tv`. Výsledok sa uloží do cache na požiadavke.\n\nExample: Podrobnosti o zariadení\n```js\nfunction index() {\n\tthis.json(this.req.useragent(true));\n}\n```\n\n### req.cookie(name)\n\nType: `method`\n\nPrečíta cookie požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n\nReturns: `String` Hodnota.\n\nHodnota sa dekóduje. Chýbajúca cookie dáva prázdny reťazec. `controller.cookie(name)` robí to isté.\n\nExample: Čítanie cookie v middleware\n```js\nMIDDLEWARE('lang', function($) {\n\t$.req.$language = $.req.cookie('lang') || 'en';\n\t$.next();\n});\n```\n\n### req.authorization()\n\nType: `method`\n\nPrečíta hlavičku Basic autorizácie.\n\nReturns: `Object` `{ user, password, empty }`.\n\nDekóduje `Authorization: Basic ...` na `{ user, password, empty }`. `empty` je `true`, keď chýba používateľ alebo heslo.\n\nExample: Basic auth\n```js\nfunction admin() {\n\tvar auth = this.req.authorization();\n\tif (auth.empty || auth.user !== 'admin' || auth.password !== CONF.admin_password) {\n\t\tthis.header('WWW-Authenticate', 'Basic realm=\"Admin\"');\n\t\treturn this.throw401();\n\t}\n\tthis.view('admin');\n}\n```\n\n### req.authorize(callback)\n\nType: `method`\n\nSám spustí delegáta `AUTH()` pre túto požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, user, isAuthorized)`. |\n\nReturns: `Request` Požiadavka.\n\n`callback(err, user, isAuthorized)` dostane výsledok delegáta. Bez delegáta je `isAuthorized` `false`. Hodí sa pre trasy, ktoré nepoužívajú autorizačné flagy.\n\nExample: Kontrola používateľa na verejnej trase\n```js\nfunction index() {\n\tvar self = this;\n\tself.req.authorize(function(err, user, isAuthorized) {\n\t\tself.view('index', { user: isAuthorized ? user : null });\n\t});\n}\n```\n\n### req.clear()\n\nType: `method`\n\nOdstráni nahrané súbory požiadavky.\n\nReturns: `Request` Požiadavka.\n\nTo isté ako `controller.clear()`.\n\nExample: Vyčistenie súborov\n```js\nfunction upload() {\n\tthis.req.clear();\n\tthis.success();\n}\n```\n\n### req.csrf()\n\nType: `method` · Since: `0.0.37`\n\nVytvorí CSRF token pre požiadavku.\n\nReturns: `String` Token.\n\nTo isté ako `controller.csrf()`; používa `DEF.onCSRFcreate(req)`.\n\nExample: Token v middleware\n```js\nMIDDLEWARE('token', function($) {\n\t$.res.setHeader('X-CSRF-Token', $.req.csrf());\n\t$.next();\n});\n```\n\n### req.encrypt([enable])\n\nType: `method`\n\nZašifruje textovú odpoveď tejto požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `Request` Požiadavka.\n\nOdpoveď sa zašifruje pomocou `CONF.secret_encryption` a dostane hlavičku `X-Encryption: a`. `controller.encrypt([enable])` robí to isté.\n\nExample: Zašifrovanie jednej odpovede\n```js\nfunction secret() {\n\tthis.req.encrypt();\n\tthis.json({ token: UID() });\n}\n```\n\n### req.hostname([path])\n\nType: `method`\n\nVytvorí absolútnu URL s hostiteľom požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | no |  | Cesta na pridanie. |\n\nReturns: `String` URL.\n\nProtokol, názov hostiteľa a port požiadavky s pridanou cestou `path`. To isté ako `controller.hostname()`.\n\nExample: Absolútna URL\n```js\nfunction index() {\n\tthis.plain(this.req.hostname('/login/'));\n}\n```\n\n### req.nocache()\n\nType: `method`\n\nVypne HTTP cache odpovede.\n\nReturns: `Request` Požiadavka.\n\nZavolá `res.nocache()`.\n\nExample: V middleware\n```js\nMIDDLEWARE('nocache', function($) {\n\t$.req.nocache();\n\t$.next();\n});\n```\n\n### res.controller\n\nType: `property`\n\nKontrolér požiadavky.\n\nReturns: `Controller`\n\nNastaví sa, keď požiadavku obsluhuje kontrolér.\n\nExample: Príklad\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.res.controller ? 'controller' : 'no controller');\n\t$.next();\n});\n```\n\n### res.success\n\nType: `property`\n\nZistí, či bola odpoveď odoslaná.\n\nReturns: `Boolean`\n\nJe `true` po tom, ako framework na požiadavku odpovedal.\n\nExample: Príklad\n```js\nfunction action() {\n\tvar self = this;\n\tsetTimeout(function() {\n\t\tif (!self.res.success)\n\t\t\tself.empty();\n\t}, 1000);\n}\n```\n\n### res.nocompress\n\nType: `property`\n\nVypne kompresiu HTML a statických súborov pre túto odpoveď.\n\nReturns: `Boolean`\n\nS `true` framework neminifikuje HTML a statické súbory, ktoré posiela.\n\nExample: Príklad\n```js\nMIDDLEWARE('raw', function($) {\n\t$.res.nocompress = true;\n\t$.next();\n});\n```\n\n### res.json(obj)\n\nType: `method`\n\nOdpovie objektom ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Hodnota. |\n\nReturns: `Response` Odpoveď.\n\nStav pochádza z možností odpovede (predvolene `200`).\n\nExample: JSON z trasy s (req, res)\n```js\nROUTE('GET /api/ping/', function(req, res) {\n\tres.json({ ok: true });\n});\n```\n\n### res.content(code, body, type, [compress], [headers])\n\nType: `method`\n\nOdpovie telom a typom obsahu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | HTTP stav. |\n| `body` | `String` | yes |  | Telo. |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `compress` | `Boolean` | no |  | Kompresia. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Response` Odpoveď.\n\nTelá nad 4 kB sa komprimujú pomocou GZIP.\n\nExample: CSV\n```js\nROUTE('GET /export/', function(req, res) {\n\tres.content(200, 'id;name\\n1;Peter', 'text/csv');\n});\n```\n\n### res.send([code], body, [type])\n\nType: `method`\n\nOdpovie v štýle Express.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `200` | HTTP stav. |\n| `body` | `String|Object|Number` | yes |  | Telo. |\n| `type` | `String` | no |  | Typ obsahu. |\n\nReturns: `Response` Odpoveď.\n\nReťazec je `text/html`, na číslo sa odpovie textom daného stavu, objekt je JSON a na `ErrorBuilder` sa odpovie jeho chybami. Je určená pre middleware napísaný pre Express.\n\nExample: Štýl Express\n```js\nROUTE('GET /hello/', function(req, res) {\n\tres.send('<b>Hello</b>');\n});\n```\n\n### res.binary(buffer, type, [encoding], [download], [headers])\n\nType: `method`\n\nOdpovie bufferom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Dáta. |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `encoding` | `String` | no |  | Kódovanie buffera. |\n| `download` | `String` | no |  | Názov súboru na stiahnutie. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n\nReturns: `Response` Odpoveď.\n\n`download` nastaví názov súboru v `Content-Disposition`.\n\nExample: Vygenerovaný súbor\n```js\nROUTE('GET /file/', function(req, res) {\n\tres.binary(Buffer.from('Hello'), 'text/plain', 'binary', 'hello.txt');\n});\n```\n\n### res.image_nocache(input, make, [headers], [callback])\n\nType: `method`\n\nOdpovie upraveným obrázkom bez cache v `/tmp/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `input` | `String|Stream` | yes |  | Obrázok. |\n| `make` | `Function` | yes |  | `function(image)`. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa na konci. |\n\nReturns: `Response` Odpoveď.\n\nFunguje ako `res.image()`, ale výsledok sa vytvára pri každej požiadavke.\n\nExample: Obrázok s časovou značkou\n```js\nROUTE('GET /stamp/', function(req, res) {\n\tres.image_nocache(PATH.public('img/photo.jpg'), function(image) {\n\t\timage.resize(300, 200);\n\t});\n});\n```\n\n### res.nocache()\n\nType: `method`\n\nVypne HTTP cache odpovede.\n\nReturns: `Response` Odpoveď.\n\nOdstráni z požiadavky `If-None-Match` a `If-Modified-Since` a nastaví `Cache-Control: private, no-cache, no-store, max-age=0`.\n\nExample: V trase s (req, res)\n```js\nROUTE('GET /now/', function(req, res) {\n\tres.nocache();\n\tres.json({ now: new Date() });\n});\n```\n\n### res.throw409([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 409 Conflict.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Response` Odpoveď.\n\nSpustí trasu `#409`, ak si nejakú deklaroval.\n\nExample: Odpoveď 409\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw409();\n});\n```\n\n### res.throw501([problem])\n\nType: `method`\n\nOdpovie chybovou stránkou 501 Not Implemented.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis problému. |\n\nReturns: `Response` Odpoveď.\n\nSpustí trasu `#501`, ak si nejakú deklaroval.\n\nExample: Odpoveď 501\n```js\nROUTE('GET /legacy/', function(req, res) {\n\tres.throw501();\n});\n```\n","entries":[{"type":"property","name":"controller.body","signature":"controller.body","since":"","deprecated":false},{"type":"property","name":"controller.query","signature":"controller.query","since":"","deprecated":false},{"type":"property","name":"controller.params","signature":"controller.params","since":"","deprecated":false},{"type":"property","name":"controller.files","signature":"controller.files","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"controller.headers","signature":"controller.headers","since":"","deprecated":false},{"type":"property","name":"controller.ip","signature":"controller.ip","since":"","deprecated":false},{"type":"property","name":"controller.url","signature":"controller.url","since":"","deprecated":false},{"type":"property","name":"controller.mobile","signature":"controller.mobile","since":"","deprecated":false},{"type":"property","name":"controller.xhr","signature":"controller.xhr","since":"","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"controller.status","signature":"controller.status","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"property","name":"controller.exception","signature":"controller.exception","since":"","deprecated":false},{"type":"property","name":"controller.req","signature":"controller.req","since":"","deprecated":false},{"type":"method","name":"controller.json()","signature":"controller.json(obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.jsonstring()","signature":"controller.jsonstring(str, [headers])","since":"0.0.57","deprecated":false},{"type":"method","name":"controller.plain()","signature":"controller.plain(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.html()","signature":"controller.html(body, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.content()","signature":"controller.content(body, type, [headers])","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.title()","signature":"controller.title(value)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.file()","signature":"controller.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.binary()","signature":"controller.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"controller.stream()","signature":"controller.stream(stream, type, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"controller.redirect()","signature":"controller.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"controller.empty()","signature":"controller.empty([headers])","since":"","deprecated":false},{"type":"method","name":"controller.success()","signature":"controller.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"controller.invalid()","signature":"controller.invalid([status], [error])","since":"","deprecated":false},{"type":"method","name":"controller.done()","signature":"controller.done([value])","since":"","deprecated":false},{"type":"method","name":"controller.callback()","signature":"controller.callback([view])","since":"","deprecated":false},{"type":"method","name":"controller.throw404()","signature":"controller.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw403()","signature":"controller.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw500()","signature":"controller.throw500([error])","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"controller.header()","signature":"controller.header(name, value)","since":"","deprecated":false},{"type":"method","name":"controller.nocache()","signature":"controller.nocache()","since":"","deprecated":false},{"type":"method","name":"controller.csrf()","signature":"controller.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"controller.autoclear()","signature":"controller.autoclear([enable])","since":"","deprecated":false},{"type":"method","name":"controller.sse()","signature":"controller.sse(data, [eventname], [id], [retry])","since":"","deprecated":false},{"type":"method","name":"controller.proxy()","signature":"controller.proxy(options)","since":"","deprecated":false},{"type":"method","name":"controller.baa()","signature":"controller.baa([label])","since":"","deprecated":false},{"type":"property","name":"controller.isConnected","signature":"controller.isConnected","since":"","deprecated":false},{"type":"property","name":"controller.isController","signature":"controller.isController","since":"","deprecated":false},{"type":"property","name":"controller.secured","signature":"controller.secured","since":"","deprecated":false},{"type":"property","name":"controller.referrer","signature":"controller.referrer","since":"","deprecated":false},{"type":"property","name":"controller.robot","signature":"controller.robot","since":"","deprecated":false},{"type":"property","name":"controller.ua","signature":"controller.ua","since":"","deprecated":false},{"type":"property","name":"controller.uri","signature":"controller.uri","since":"","deprecated":false},{"type":"property","name":"controller.split","signature":"controller.split","since":"","deprecated":false},{"type":"property","name":"controller.subdomain","signature":"controller.subdomain","since":"","deprecated":false},{"type":"property","name":"controller.sessionid","signature":"controller.sessionid","since":"","deprecated":false},{"type":"property","name":"controller.sseID","signature":"controller.sseID","since":"","deprecated":false},{"type":"property","name":"controller.route","signature":"controller.route","since":"","deprecated":false},{"type":"property","name":"controller.options","signature":"controller.options","since":"","deprecated":false},{"type":"property","name":"controller.flags","signature":"controller.flags","since":"","deprecated":false},{"type":"property","name":"controller.schema","signature":"controller.schema","since":"","deprecated":false},{"type":"property","name":"controller.name","signature":"controller.name","since":"","deprecated":false},{"type":"property","name":"controller.breadcrumb","signature":"controller.breadcrumb","since":"","deprecated":false},{"type":"method","name":"controller.jsonp()","signature":"controller.jsonp(name, obj, [headers], [beautify], [replacer])","since":"","deprecated":false},{"type":"method","name":"controller.throw400()","signature":"controller.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw401()","signature":"controller.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw409()","signature":"controller.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw501()","signature":"controller.throw501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.throw503()","signature":"controller.throw503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view400()","signature":"controller.view400([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view401()","signature":"controller.view401([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view403()","signature":"controller.view403([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view404()","signature":"controller.view404([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view409()","signature":"controller.view409([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view500()","signature":"controller.view500([error])","since":"","deprecated":false},{"type":"method","name":"controller.view501()","signature":"controller.view501([problem])","since":"","deprecated":false},{"type":"method","name":"controller.view503()","signature":"controller.view503([problem])","since":"","deprecated":false},{"type":"method","name":"controller.nocontent()","signature":"controller.nocontent([headers])","since":"","deprecated":false},{"type":"method","name":"controller.destroy()","signature":"controller.destroy()","since":"","deprecated":false},{"type":"method","name":"controller.close()","signature":"controller.close([end])","since":"","deprecated":false},{"type":"method","name":"controller.cancel()","signature":"controller.cancel()","since":"","deprecated":false},{"type":"method","name":"controller.clear()","signature":"controller.clear()","since":"","deprecated":false},{"type":"method","name":"controller.custom()","signature":"controller.custom()","since":"","deprecated":false},{"type":"method","name":"controller.error()","signature":"controller.error(err)","since":"","deprecated":false},{"type":"method","name":"controller.successful()","signature":"controller.successful(callback)","since":"","deprecated":false},{"type":"method","name":"controller.hostname()","signature":"controller.hostname([path])","since":"","deprecated":false},{"type":"method","name":"controller.image()","signature":"controller.image(filename, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"controller.memorize()","signature":"controller.memorize(key, expire, [disabled], fn, [fnFrom])","since":"","deprecated":false},{"type":"method","name":"controller.description()","signature":"controller.description(value)","since":"","deprecated":false},{"type":"method","name":"controller.keywords()","signature":"controller.keywords(value)","since":"","deprecated":false},{"type":"method","name":"controller.head()","signature":"controller.head([value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.place()","signature":"controller.place(name, [value], [...])","since":"","deprecated":false},{"type":"method","name":"controller.theme()","signature":"controller.theme(name)","since":"","deprecated":false},{"type":"method","name":"controller.component()","signature":"controller.component(name, [settings], [model])","since":"","deprecated":false},{"type":"method","name":"controller.helper()","signature":"controller.helper(name, [arg], [...])","since":"","deprecated":false},{"type":"method","name":"controller.public()","signature":"controller.public(name, [path])","since":"","deprecated":false},{"type":"method","name":"controller.public_js()","signature":"controller.public_js(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_css()","signature":"controller.public_css(name, [tag])","since":"","deprecated":false},{"type":"method","name":"controller.public_image()","signature":"controller.public_image(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_video()","signature":"controller.public_video(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_font()","signature":"controller.public_font(name)","since":"","deprecated":false},{"type":"method","name":"controller.public_download()","signature":"controller.public_download(name)","since":"","deprecated":false},{"type":"method","name":"controller.runtest()","signature":"controller.runtest(url, [name], [callback])","since":"","deprecated":false},{"type":"property","name":"req.host","signature":"req.host","since":"","deprecated":false},{"type":"property","name":"req.secured","signature":"req.secured","since":"","deprecated":false},{"type":"property","name":"req.isAuthorized","signature":"req.isAuthorized","since":"","deprecated":false},{"type":"property","name":"req.isStaticFile","signature":"req.isStaticFile","since":"","deprecated":false},{"type":"property","name":"req.xhr","signature":"req.xhr","since":"","deprecated":false},{"type":"property","name":"req.ip","signature":"req.ip","since":"","deprecated":false},{"type":"property","name":"req.uri","signature":"req.uri","since":"","deprecated":false},{"type":"property","name":"req.path","signature":"req.path","since":"","deprecated":false},{"type":"property","name":"req.split","signature":"req.split","since":"","deprecated":false},{"type":"property","name":"req.subdomain","signature":"req.subdomain","since":"","deprecated":false},{"type":"property","name":"req.mobile","signature":"req.mobile","since":"","deprecated":false},{"type":"property","name":"req.robot","signature":"req.robot","since":"","deprecated":false},{"type":"property","name":"req.ua","signature":"req.ua","since":"","deprecated":false},{"type":"property","name":"req.query","signature":"req.query","since":"","deprecated":false},{"type":"property","name":"req.body","signature":"req.body","since":"","deprecated":false},{"type":"property","name":"req.files","signature":"req.files","since":"","deprecated":false},{"type":"property","name":"req.user","signature":"req.user","since":"","deprecated":false},{"type":"property","name":"req.session","signature":"req.session","since":"","deprecated":false},{"type":"method","name":"req.useragent()","signature":"req.useragent([structured])","since":"","deprecated":false},{"type":"method","name":"req.cookie()","signature":"req.cookie(name)","since":"","deprecated":false},{"type":"method","name":"req.authorization()","signature":"req.authorization()","since":"","deprecated":false},{"type":"method","name":"req.authorize()","signature":"req.authorize(callback)","since":"","deprecated":false},{"type":"method","name":"req.clear()","signature":"req.clear()","since":"","deprecated":false},{"type":"method","name":"req.csrf()","signature":"req.csrf()","since":"0.0.37","deprecated":false},{"type":"method","name":"req.encrypt()","signature":"req.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"req.hostname()","signature":"req.hostname([path])","since":"","deprecated":false},{"type":"method","name":"req.nocache()","signature":"req.nocache()","since":"","deprecated":false},{"type":"property","name":"res.controller","signature":"res.controller","since":"","deprecated":false},{"type":"property","name":"res.success","signature":"res.success","since":"","deprecated":false},{"type":"property","name":"res.nocompress","signature":"res.nocompress","since":"","deprecated":false},{"type":"method","name":"res.json()","signature":"res.json(obj)","since":"","deprecated":false},{"type":"method","name":"res.content()","signature":"res.content(code, body, type, [compress], [headers])","since":"","deprecated":false},{"type":"method","name":"res.send()","signature":"res.send([code], body, [type])","since":"","deprecated":false},{"type":"method","name":"res.binary()","signature":"res.binary(buffer, type, [encoding], [download], [headers])","since":"","deprecated":false},{"type":"method","name":"res.image_nocache()","signature":"res.image_nocache(input, make, [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.nocache()","signature":"res.nocache()","since":"","deprecated":false},{"type":"method","name":"res.throw409()","signature":"res.throw409([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw501()","signature":"res.throw501([problem])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabULN2Hx60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Schemas","summary":"NEWSCHEMA(), schema methods, the $ object of operations, NEWACTION() and how to run operations from code.","markdown":"---\ntitle: Schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Schemas\n\n> NEWSCHEMA(), schema methods, the $ object of operations, NEWACTION() and how to run operations from code.\n\nA schema is declared with `NEWSCHEMA()`, usually in a file of the `schemas/` folder; actions without a schema with `NEWACTION()`. Every operation receives the `$` object. The guide [Schemas and actions](../../guides/schemas/) explains how the parts work together; this page is the exact reference.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDeclares a schema: its fields, validation and operations.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the schema, used in routes (`*Users`) and in `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)` that declares fields and operations, or `null` to remove the schema. |\n\nReturns: `SchemaBuilderEntity` The new schema (nothing when it is removed).\n\nThe declaration runs at once with the schema as its argument and as `this`. A schema with the same name is replaced. Pass `null` as the declaration to remove a schema. With a function as the only argument, the schema gets a random name (dynamic schema).\n\nExample: A schema with fields and an operation\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Remove a schema\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nReturns a declared schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the schema. |\n| `callback` | `Function` | no |  | `function(err, schema)`, called when the schema exists. |\n| `timeout` | `Number` | no | `20000` | How long to wait, in milliseconds. |\n\nReturns: `SchemaBuilderEntity` The schema, or `undefined`. Nothing when a callback is given.\n\nWith a callback, it waits until the schema is declared (20 seconds by default) and calls `callback(err, schema)`.\n\nExample: Read a schema\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDeclares a field: its type, whether it is required and its error message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Name of the field, or an array of names. |\n| `type` | `Function|String|Array|Object` | yes |  | Type of the field (see above), or `null` to remove it. |\n| `required` | `Boolean|Function|String` | no | `false` | `true`; a function `(value, model)` that returns `true`, `false` or an error message; or an error message, which also makes the field required. |\n| `error` | `String` | no |  | Error message when the field is invalid. `@key` reads a resource. |\n| `xss` | `Boolean|Number` | no |  | For strings: `true` empties a value with XSS or SQL injection, `1` checks only XSS, `2` only SQL injection. |\n\nReturns: `Function` `function(value)` that sets the default value (a value or a function) and returns the schema.\n\nTypes: `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, an inline object `'name:String, age:Number'`, an enum `['a', 'b']`, a key-value object, `Array` or `'[Type]'`, and the name of another schema (`'Address'`, `'[Address]'`).\n\nA required field must not be empty: a string must have characters (and a valid value for `Email`, `URL`, `UID` and similar), a number must be greater than `0`, a boolean `true` and an array must have items. A field of another schema is always validated.\n\nThe function it returns sets the default value and returns the schema. `type` `null` removes the field. An array of names declares several fields with the same type.\n\nExample: Fields\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Default values\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nMakes a declared field required, always or only when a condition holds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the field, or several names separated by commas. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)` that returns `true` when the field must be validated; or `false` to make the field optional. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\n`fn(model, operations)` decides at each validation whether the field is validated. `operations` is an object with the names of the operations the route runs, so `operations.insert` is true on insert. `false` instead of a function makes the field optional again. Several names can be separated by commas. The field must be declared first.\n\nExample: Required only on insert\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nRemoves a declared field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the field. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nExample: Remove a field of an inherited schema\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nCopies fields, operations and settings of another schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the schema to inherit from. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nIt waits until the other schema is declared. Fields and operations the schema already has are kept.\n\nExample: Inherit\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nThe schema receives an array of items instead of one object.\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nEvery item is converted and validated. Data that is not an array becomes an empty array.\n\nExample: An array of items\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDeclares an operation with its input, query, parameters and permissions in one object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the operation, optionally with URL parameters (`read/{id:UID}`). It can be left out when `options` has `id` or `name`. |\n| `options` | `Object` | yes |  | Options of the action (see the table). |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\n`input`, `query`, `params` and `output` take an inline declaration (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` is required, `@Name` is another schema or action) or the name of a JSON schema from `jsonschemas/`. Invalid data stops the action with an error. A name like `'read/{id:UID}'` declares `params` from the name.\n\nOptions:\n\n| Option | What it does |\n| --- | --- |\n| `action` | `function($, model)`: the action. It runs with the schema as `this` |\n| `name` | A description |\n| `input` | Fields of the request body; the result is in `model` |\n| `output` | Fields of the response |\n| `query` | Fields of the query string, in `$.query` (`filter` is an alias) |\n| `params` | Fields of the URL parameters, in `$.params` |\n| `user` | `true`: only a signed-in user, otherwise `401` |\n| `sa` | `true`: only a user with `sa` or `su` |\n| `permissions` | A string or array; the user needs one of them in `user.permissions` or `user.roles` (`sa`/`su` always pass) |\n| `cache` | Caches the response: `{ query, params, user, language, expire }`; `true` or a list of field names chooses what makes the cache key, `expire` defaults to `'5 minutes'` |\n| `publish` | Publishes the input or output to TMS |\n\nA route calls the action like any other operation: `*Users --> create`.\n\nExample: Actions with input, query and permissions\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Routes\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Cache the response for 10 minutes\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nSets the save operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nUse it when one operation both creates and updates. A route calls it with `*Schema --> save`; from code use `CALL('Schema --> save')`.\n\nExample: Declare and route it\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nSets the insert operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe model is validated before the operation runs. A route calls it with `*Schema --> insert`; from code use `CALL('Schema --> insert')`.\n\nExample: Declare and route it\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nSets the update operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe whole model is validated; the id usually comes from the URL in `$.id`. A route calls it with `*Schema --> update`; from code use `CALL('Schema --> update')`.\n\nExample: Declare and route it\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nSets the patch operation, which changes only the fields that were sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nOnly the sent fields are converted and validated, and their names are in `$.keys`. A route calls it with `*Schema --> patch`; from code use `CALL('Schema --> patch')`.\n\nExample: Declare and route it\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nSets the read operation. `schema.setGet()` is an alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nA route calls it with `*Schema --> read` or `--> get`.\n\nExample: Declare and route it\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nSets the query operation, which lists items. `schema.setList()` is an alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nA route calls it with `*Schema --> query` or `--> list`. The `filter` converts the query string into `$.filter`.\n\nExample: A list with a filter\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nSets the remove operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The operation, `function($, model)`. It runs with the schema as `this`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nA route calls it with `*Schema --> remove`; from code use `CALL('Schema --> remove')`.\n\nExample: Declare and route it\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nAdds an operation with your own name. `schema.add()` is an alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the operation. |\n| `fn` | `Function|String` | yes |  | `function($, model)`, or `'Schema --> name'`. |\n| `filter` | `String` | no |  | Fields of the query string, for example `'page:Number, limit:Number'`. The operation reads them converted in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nInstead of a function you can give `'Schema --> name'` to reuse an operation of another schema.\n\nExample: A custom operation\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Reuse an operation of another schema\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nAdds a function that runs before every operation of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nCall `next()` to continue. `next(true)` stops, so the middleware must answer itself, for example with `$.invalid()`. Several middleware run in the order they were added.\n\nExample: Only for signed-in users\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nSets the resource file with the error messages of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the resource file in `resources/`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nA field without its own message reads the key with its name from this resource. `schema.setPrefix(prefix)` adds a prefix to the keys.\n\nExample: Messages from a resource\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nSets a function that runs every minute. `schema.setService()` is an alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)`; `counter` counts the minutes. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nExample: Clean every hour\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nSets a function that runs when the schema is removed or replaced.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nExample: Free resources\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nEnds the operation and answers with a value or an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | The response, or an error. |\n\nAn `Error` or an `ErrorBuilder` answers with that error. `$.callback(err, value)` also works, so you can pass `$.callback` to functions that call back with `(err, response)`. In a schema operation, `$.callback()` without a value answers with the model.\n\nExample: Answer with data\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nEnds the operation and answers `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | The result. |\n| `value` | `Object` | no |  | A value sent as `value`. |\n\nReturns: `SchemaOptions` `$`.\n\nWith one argument that is not a boolean, it is the value. `$.success(false)` answers `{ \"success\": false }`.\n\nExample: Answer with the new id\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nEnds the operation with an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Name of the field, a message, a status code or an error. |\n| `message` | `String` | no |  | The error message. `@key` reads a resource. |\n\nReturns: `SchemaOptions|Function` `$`, or a callback when called without arguments.\n\n`$.invalid('email')` reports an invalid field with its default message, `$.invalid('email', 'Wrong email')` with your message, `$.invalid('Something went wrong')` a message without a field and `$.invalid(404)` a status code. An `Error` or `ErrorBuilder` is also accepted. Without arguments it returns a function `(err)` that ends the operation with that error.\n\nExample: Errors\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nReturns a callback `(err, response)` that ends the operation with success or with the error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` to send the response, or a value to send. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` answers `{ \"success\": true }`, `$.done(true)` puts the response in `value` and `$.done(something)` puts `something` in `value`.\n\nExample: Answer after a database call\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nReturns a callback that ends the operation on an error and otherwise runs `fn`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, run with `$` as `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Continue only without an error\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nRuns a function with a Node.js style callback and returns a promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | A function whose last argument is `callback(err, response)`. |\n| `a, b, c` | `Object` | no |  | Arguments for `fn`. |\n\nReturns: `Promise` Resolves with the response.\n\nThe arguments are passed to `fn` before the callback. On an error, the operation ends with it and the promise never resolves.\n\nExample: Await a callback function\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nEnds the operation and redirects the request to another URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The target URL. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Redirect\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nRuns another action or operation from inside an operation, with the same controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Operation of this schema, `Schema --> operation` or an action name. |\n| `model` | `Object` | no |  | Data for the operation. |\n\nReturns: `SchemaCall` The same object as `CALL()`.\n\nA name without `-->` is an operation of the current schema. A `+`, `-` or `#` prefix sets the method (POST, GET or PATCH). It is `CALL()` bound to the current request, so it returns the same object with `.callback()` and `.promise()`.\n\nExample: Call another operation\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nListens to an event of the operation: `error`, `response` or `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` or `end`. |\n| `fn` | `Function` | yes |  | The listener. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` gets the errors, `response` the response and `end` both `(err, response)`. They fire when a schema operation called with a single operation ends.\n\nExample: Log the end of an operation\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nThe validated model of the operation.\n\nReturns: `Object`\n\nIt contains only the declared fields, converted to their types. Operations also get it as the second argument. `$.value` is an alias.\n\nExample: Read the model\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nThe query string of the request.\n\nReturns: `Object`\n\nIn an action with the `query` option, the fields are converted and validated.\n\nExample: Read the query\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nThe dynamic parameters of the route URL.\n\nReturns: `Object`\n\nIn an action with the `params` option, they are converted and validated.\n\nExample: Read a parameter\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nThe first dynamic parameter of the route URL, usually the id.\n\nReturns: `String`\n\nExample: Read by id\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nThe signed-in user of the request, or `null`.\n\nReturns: `Object`\n\nActions with `user`, `sa` or `permissions` check it before they run. `$.session` holds the session.\n\nExample: Save the author\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nIn a `PATCH` request, the names of the fields that were sent; otherwise `null`.\n\nReturns: `Array`\n\nOnly these fields are converted and validated.\n\nExample: Patch only the sent fields\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nThe query string converted with the `filter` of the operation.\n\nReturns: `Object`\n\nThe filter is the second argument of `schema.setQuery()` and the other set methods. Without a filter it is the query as it came.\n\nExample: Typed query\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nThe controller of the request, or nothing when the operation runs from code.\n\nReturns: `Controller`\n\n`$` also reads some properties of the controller directly: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` and `$.sessionid`.\n\nExample: Read the request\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nThe responses of the previous operations when a route or `CALL()` runs several of them.\n\nReturns: `Object`\n\n`$.response(name)` returns one of them.\n\nExample: Use the result of a previous operation\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDeclares an action that does not belong to a schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the action, for example `Users/create`. It can be left out when `options` has `id` or `name`. |\n| `options` | `Object` | yes |  | Options of the action. |\n\nReturns: `Object` The action, with a `remove()` method.\n\nIt takes the same options as `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) and also:\n\n| Option | What it does |\n| --- | --- |\n| `route` | `'API /api/'` declares an API route for the action. The API name is the action name in lowercase with `_` instead of `/`, with `+` when the action has `input` and `-` otherwise |\n| `csrf`, `encrypt`, `compress` | Like `schema.csrf()`, `schema.encrypt()` and `schema.compress()` |\n\nThe action runs with `$` as `this`. Declaring an action with an existing name replaces it, and `action.remove()` removes it with its route. A route calls an action with `-->` and no schema.\n\nExample: An action and its route\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: An action with its own API route\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nRuns actions or schema operations from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Action name or `Schema --> operations`, optionally with a `+`, `-` or `#` prefix. |\n| `model` | `Object` | no |  | Data for the operation. It is validated. |\n| `controller` | `Controller|SchemaOptions` | no |  | The request to run with, or a `$`. |\n\nReturns: `SchemaCall` An object with the methods in the table.\n\n`name` is an action (`Users/create`), several actions separated by spaces, or `Schema --> operations`. A `+`, `-` or `#` prefix sets the method (POST, GET or PATCH); without it, the call is POST when there is a model. The call starts on the next tick, so set its options first:\n\n| Method | What it sets |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` and `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (or the user of a `$`) and the language |\n| `.controller(ctrl)` | The controller (or the controller of a `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Ends `$` on an error, otherwise runs `fn(response)` |\n| `.promise([$])` | Returns a promise; with `$`, an error ends that operation |\n| `.debug()` | Prints the input and the result to the console |\n\nWith several operations the response is an object with the result of each one.\n\nExample: Run an action\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await a schema operation\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nRuns schema operations from code. `$ACTION()` is an alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` with a method prefix. |\n| `model` | `Object` | no |  | Data for the operation. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | The request, or an object with `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` A promise when there is no callback.\n\n`name` is `+Schema --> operations` (or `-`, `#`, or a method like `POST Schema --> insert`). Instead of a controller you can pass an object with `query`, `params`, `user`, `session`, `body`, `headers` and `id`. Without a callback it returns a promise. For actions declared with `NEWACTION()`, use `CALL()`.\n\nExample: Insert from code\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: With a query and a user\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nConverts and validates a model with a schema, without running any operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name of the schema. |\n| `model` | `Object` | yes |  | Data to validate. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` only converts the data. |\n| `controller` | `Controller` | no |  | A controller that gets the error instead of the promise. |\n\nReturns: `Promise` The validated model, when there is no callback.\n\nWithout a callback it returns a promise.\n\nExample: Validate data\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nRuns an operation of a schema, added with `schema.addOperation()`, from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | The name of the schema. |\n| `name` | `String` | yes |  | The name given in `schema.addOperation()`. |\n| `options` | `Object` | no |  | Custom options, available as `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | The controller, or a `$` object. |\n\nReturns: `Boolean` `true` when the schema exists.\n\n`schema.addOperation(name, operation, [filter])` links a name in the schema to a global operation declared with `NEWOPERATION()`. `$OPERATION()` runs it: the schema calls `OPERATION(operation, $.model, $.callback, schemaName, $)`, so the operation answers through the schema and shares its controller.\n\nThe model is not prepared or validated: `$.model` is an empty object, and the options arrive as `$.options`. Schema middleware still runs. When `options` is a function, it is the callback. A missing schema calls the callback with the error `Schema \"name\" not found.`; a schema without the operation answers with `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nDo not confuse it with `OPERATION()`, which runs a global operation directly.\n\nExample: Link and run an operation\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nRuns a task of a schema, added with `schema.addTask()`, from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | The name of the schema. |\n| `name` | `String` | yes |  | The name given in `schema.addTask()`. |\n| `options` | `Object` | no |  | Custom options, available as `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | The controller, or a `$` object. |\n\nReturns: `Boolean` `true` when the schema exists.\n\n`schema.addTask(name, task, [filter], [callback])` links a name in the schema to a task step declared with `NEWTASK()` (`task` is `'name/step'`). `$TASK()` runs it: the schema starts `TASK(task, $.callback, $)` with `$.model` as the value of the task. With the `callback` of `addTask()`, the schema calls `callback($, err, response)` instead and you answer yourself.\n\nThe model is not prepared or validated: `$.model` is an empty object, and the options arrive as `$.options`. When `options` is a function, it is the callback. A missing schema calls the callback with the error `Schema \"name\" not found.`\n\nExample: Link and run a task\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nReturns an object with random data that matches a schema, for tests and demos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | A schema name, an inline declaration or an object of types. |\n| `onlyrequired` | `Boolean` | no | `false` | Fills only the required fields. |\n\nReturns: `Object` The fake model.\n\n`schema` is the name of a schema, an inline declaration like `'name:String, email:Email'` or an object like `{ id: UID, name: 'String(30)' }`. Each field gets a random value of its type: emails, phones, ZIP codes, URLs, identifiers (`UID`, `GUID`), numbers, dates, booleans and strings (cut by the declared length, at most 30 characters). Arrays get two items, enums and key-value lists one of their values, and fields of another schema a nested fake object.\n\nSome field names give realistic values: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nWith `onlyrequired`, only required fields of a named schema are filled.\n\nExample: From a schema\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Inline\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nAdds an extension to the `query` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `query` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `query` operation. Alias: `schema.setListExtension()`.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nAdds an extension to the `read` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `read` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `read` operation. Alias: `schema.setGetExtension()`.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nAdds an extension to the `insert` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `insert` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `insert` operation.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nAdds an extension to the `update` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `update` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `update` operation.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nAdds an extension to the `patch` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `patch` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `patch` operation.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nAdds an extension to the `remove` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `remove` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `remove` operation.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nAdds an extension to the `save` operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` is the options of the running operation, `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing the `save` operation, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same the `save` operation.\n\nExample: Extend an operation from a plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nAdds an extension to a workflow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the workflow. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` is the value passed to `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nAn extension is a function `function($, data, next)` that you add to an existing workflow, usually from another file or a plugin. Extensions do not run on their own: the operation runs them when it calls `$.extend(data, [callback])`, in the order they were added. With a callback, each extension must call `next()`; without one, `next` does nothing. Several extensions can be added to the same workflow. Alias: `schema.addExtension()`.\n\nExample: Extend a workflow\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nRuns the extensions of the current operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | A value passed to every extension as its second argument. |\n| `callback` | `Function` | no |  | Runs after the last extension. |\n\nReturns: `Boolean` `true` when extensions exist, otherwise `undefined`.\n\nIt runs the extensions added with `schema.setSaveExtension()`, `schema.addWorkflowExtension()` and the others for the running operation. Without `callback`, all extensions run at once. With `callback`, they run one by one (each calls `next()`) and `callback` runs at the end, also when there are no extensions. The method returns `true` when the operation has extensions.\n\nExample: Wait for the extensions\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nRequires a valid CSRF token for every route of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe routes of the schema then work like routes with the `csrf` flag: the token from `controller.csrf()` must arrive in the `x-csrf-token` header or the `?csrf=` argument. An invalid token answers the error `Invalid CSRF token`.\n\nExample: Protect a form\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nEncrypts the responses of the routes of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nText responses are encrypted with `CONF.secret_encryption` and get the header `X-Encryption: a`. Without `secret_encryption` in the configuration nothing is encrypted.\n\nExample: Encrypted answers\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nLeaves out `null` and `undefined` values from the JSON responses of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe JSON answer of the routes of the schema is serialized without the keys whose value is `null` or `undefined`, so it is smaller.\n\nExample: Smaller JSON\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nCopies fields that the schema does not define.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | A name, a list separated by commas or an array of names. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe listed fields are copied from the input into the model as they are: without conversion and without validation. One string with names separated by commas works too.\n\nExample: Free-form metadata\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nAdds an asynchronous check of one field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | How long the result is kept, for example `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe check runs after the validation, only when the field has a value. `fn($)` gets `$.value`, `$.model`, `$.name`, `$.user`, `$.query` and the other request values. Call `$.next([value])` (or `$.success([value])`) to accept the value, optionally with a new one, or `$.invalid(error)` to reject it; a rejected field is set to `null`. With `cache` (an expiration such as `'5 minutes'`) the result for the same value is kept in the cache.\n\nExample: Check a country code\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nRemoves all fields of the schema.\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nIt removes the defined fields, the required fields, the checks of `schema.verify()` and the fields of `schema.allow()`. The operations stay.\n\nExample: Define the fields again\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nNames the primary key of the schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe name is stored in `schema.primary`, and `schema.inherit()` copies it. The framework does not use it in the operations: it is information for your own code.\n\nExample: A primary key\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nSets a function that runs when an operation or the validation of the schema ends with errors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\n`fn(error, model, type, [name])` gets the `ErrorBuilder`, the model, the type of the operation (`'make'` for the validation, `'save'`, `'workflow'`, ...) and the name of a workflow. You can read or change the errors before they are answered.\n\nExample: Log invalid input\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nAdds an operation of the schema that runs a task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the operation. |\n| `task` | `String` | yes |  | The task in the form `'name/start'`. |\n| `filter` | `String` | no |  | Fields of the query string. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nCalling the operation (for example `CALL('Schema --> name')` or `*Schema --> name` in a route) runs `TASK(task)` with the model as its value. The answer of the task is the answer of the operation. With `callback($, err, response)` you answer yourself.\n\nExample: A schema operation that runs a task\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nAdds an operation of the schema that runs an operation of `NEWOPERATION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the operation in the schema. |\n| `operation` | `String` | yes |  | The name of the operation from `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Fields of the query string. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nCalling the schema operation (for example `*Schema --> name` in a route) runs `OPERATION(operation)` with the model as its value, and its answer is the answer of the schema operation.\n\nExample: Reuse an operation\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nReads or replaces the list of values of an enum field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `value` | `Array|Object` | no |  | A new list of values. |\n\nReturns: `Array|Object` The current list, or `undefined` for other fields.\n\nIt works for fields defined with an array (enum) or an object (key-value). With `value` the list is replaced.\n\nExample: Values loaded later\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nDescribes the fields of the schema.\n\nReturns: `Object` The description of the fields.\n\nIt returns an object with one key per field and its `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...), and `required` and `length` when they are set. Useful to describe the schema to a client.\n\nExample: Send the fields to a client\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nPrepares and validates a model from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | The input. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` The prepared model (before the asynchronous checks).\n\nIt converts the input by the fields of the schema, validates it and runs the checks of `schema.verify()`. `callback(err, model)` gets the `ErrorBuilder` or the prepared model. Alias: `schema.load()`.\n\nExample: Validate a value\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nValidates a model without converting it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | The model. |\n\nReturns: `ErrorBuilder` The errors; `.is` is `true` when there are some.\n\nIt checks the required fields and the validation of every field. It does not run the checks of `schema.verify()`.\n\nExample: Check a model\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nCreates a model with the default values of the fields.\n\nReturns: `Object` A new model.\n\nEach field gets its default: `0` for numbers, `''` for strings, `false` for booleans, `NOW` for dates, `[]` for arrays and a default model for a field of another schema. Alias: `schema.create()`.\n\nExample: An empty form\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nRemoves the schema.\n\nReturns: `undefined` Nothing.\n\nThe schema is removed from the list of schemas and its function of `schema.setDestroy()` runs.\n\nExample: Remove a schema\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nRuns a workflow of the schema from code with a model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the workflow. |\n| `model` | `Object` | yes |  | The input. |\n| `options` | `Object` | no |  | A value available as `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | A controller or `$` to take the user and the request from. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\nThe model is prepared and validated first, like in a route. `schema.workflow2(name, [options], callback, [controller])` runs it without a model and without validation. For most code `CALL()` and `EXEC()` are simpler.\n\nExample: Run a workflow\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nRuns the `query` operation from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | A value available as `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | A controller or `$`. |\n\nReturns: `SchemaBuilderEntity` The schema, for chaining.\n\n`schema.read()` (alias `schema.get()`) and `schema.remove()` work the same way for the `read` and `remove` operations. These run without a model.\n\nExample: List from code\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabULN2Hx60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Schemas","summary":"NEWSCHEMA(), Methoden von Schemas, das Objekt $ von Operationen, NEWACTION() und wie du Operationen aus Code ausführst.","markdown":"---\ntitle: Schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Schemas\n\n> NEWSCHEMA(), Methoden von Schemas, das Objekt $ von Operationen, NEWACTION() und wie du Operationen aus Code ausführst.\n\nEin Schema wird mit `NEWSCHEMA()` deklariert, meist in einer Datei des Ordners `schemas/`; Aktionen ohne Schema mit `NEWACTION()`. Jede Operation erhält das Objekt `$`. Der Leitfaden [Schemas und Aktionen](../../guides/schemas/) erklärt, wie die Teile zusammenarbeiten; diese Seite ist die genaue Referenz.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDeklariert ein Schema: seine Felder, seine Validierung und seine Operationen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Schemas, verwendet in Routen (`*Users`) und in `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)`, die Felder und Operationen deklariert, oder `null`, um das Schema zu entfernen. |\n\nReturns: `SchemaBuilderEntity` Das neue Schema (nichts, wenn es entfernt wird).\n\nDie Deklaration läuft sofort, mit dem Schema als Argument und als `this`. Ein Schema mit demselben Namen wird ersetzt. Übergib `null` als Deklaration, um ein Schema zu entfernen. Mit einer Funktion als einzigem Argument erhält das Schema einen zufälligen Namen (dynamisches Schema).\n\nExample: Ein Schema mit Feldern und einer Operation\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Ein Schema entfernen\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nGibt ein deklariertes Schema zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Schemas. |\n| `callback` | `Function` | no |  | `function(err, schema)`, aufgerufen, wenn das Schema existiert. |\n| `timeout` | `Number` | no | `20000` | Wie lange gewartet wird, in Millisekunden. |\n\nReturns: `SchemaBuilderEntity` Das Schema oder `undefined`. Nichts, wenn ein Callback angegeben ist.\n\nMit einem Callback wartet sie, bis das Schema deklariert ist (standardmäßig 20 Sekunden), und ruft `callback(err, schema)` auf.\n\nExample: Ein Schema lesen\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDeklariert ein Feld: seinen Typ, ob es Pflicht ist, und seine Fehlermeldung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Name des Feldes oder ein Array von Namen. |\n| `type` | `Function|String|Array|Object` | yes |  | Typ des Feldes (siehe oben) oder `null`, um es zu entfernen. |\n| `required` | `Boolean|Function|String` | no | `false` | `true`; eine Funktion `(value, model)`, die `true`, `false` oder eine Fehlermeldung zurückgibt; oder eine Fehlermeldung, die das Feld ebenfalls zum Pflichtfeld macht. |\n| `error` | `String` | no |  | Fehlermeldung, wenn das Feld ungültig ist. `@key` liest eine Ressource. |\n| `xss` | `Boolean|Number` | no |  | Für Strings: `true` leert einen Wert mit XSS oder SQL-Injection, `1` prüft nur XSS, `2` nur SQL-Injection. |\n\nReturns: `Function` `function(value)`, die den Standardwert setzt (einen Wert oder eine Funktion) und das Schema zurückgibt.\n\nTypen: `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, ein Inline-Objekt `'name:String, age:Number'`, ein Enum `['a', 'b']`, ein Schlüssel-Wert-Objekt, `Array` oder `'[Type]'` und der Name eines anderen Schemas (`'Address'`, `'[Address]'`).\n\nEin Pflichtfeld darf nicht leer sein: Ein String muss Zeichen haben (und bei `Email`, `URL`, `UID` und Ähnlichen einen gültigen Wert), eine Zahl muss größer als `0` sein, ein Boolean `true`, und ein Array muss Elemente haben. Ein Feld eines anderen Schemas wird immer validiert.\n\nDie zurückgegebene Funktion setzt den Standardwert und gibt das Schema zurück. `type` `null` entfernt das Feld. Ein Array von Namen deklariert mehrere Felder mit demselben Typ.\n\nExample: Felder\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Standardwerte\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nMacht ein deklariertes Feld zum Pflichtfeld, immer oder nur unter einer Bedingung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes oder mehrere durch Kommas getrennte Namen. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)`, die `true` zurückgibt, wenn das Feld validiert werden muss; oder `false`, um das Feld optional zu machen. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\n`fn(model, operations)` entscheidet bei jeder Validierung, ob das Feld validiert wird. `operations` ist ein Objekt mit den Namen der Operationen, die die Route ausführt, sodass `operations.insert` beim Einfügen wahr ist. `false` statt einer Funktion macht das Feld wieder optional. Mehrere Namen können durch Kommas getrennt werden. Das Feld muss zuerst deklariert sein.\n\nExample: Nur beim Einfügen Pflicht\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nEntfernt ein deklariertes Feld.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nExample: Ein Feld eines geerbten Schemas entfernen\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nKopiert Felder, Operationen und Einstellungen eines anderen Schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Schemas, von dem geerbt wird. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nSie wartet, bis das andere Schema deklariert ist. Felder und Operationen, die das Schema bereits hat, bleiben erhalten.\n\nExample: Erben\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nDas Schema empfängt ein Array von Elementen statt eines einzelnen Objekts.\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nJedes Element wird konvertiert und validiert. Daten, die kein Array sind, werden zu einem leeren Array.\n\nExample: Ein Array von Elementen\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDeklariert eine Operation mit ihrer Eingabe, Query, ihren Parametern und Berechtigungen in einem Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Operation, optional mit URL-Parametern (`read/{id:UID}`). Er kann weggelassen werden, wenn `options` `id` oder `name` enthält. |\n| `options` | `Object` | yes |  | Optionen der Aktion (siehe Tabelle). |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\n`input`, `query`, `params` und `output` nehmen eine Inline-Deklaration (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` ist Pflicht, `@Name` ist ein anderes Schema oder eine andere Aktion) oder den Namen eines JSON-Schemas aus `jsonschemas/`. Ungültige Daten stoppen die Aktion mit einem Fehler. Ein Name wie `'read/{id:UID}'` deklariert `params` aus dem Namen.\n\nOptionen:\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `action` | `function($, model)`: die Aktion. Sie läuft mit dem Schema als `this` |\n| `name` | Eine Beschreibung |\n| `input` | Felder des Bodys der Anfrage; das Ergebnis steht in `model` |\n| `output` | Felder der Antwort |\n| `query` | Felder des Query-Strings, in `$.query` (`filter` ist ein Alias) |\n| `params` | Felder der URL-Parameter, in `$.params` |\n| `user` | `true`: nur ein angemeldeter Benutzer, sonst `401` |\n| `sa` | `true`: nur ein Benutzer mit `sa` oder `su` |\n| `permissions` | Ein String oder Array; der Benutzer braucht eine davon in `user.permissions` oder `user.roles` (`sa`/`su` kommen immer durch) |\n| `cache` | Speichert die Antwort im Cache: `{ query, params, user, language, expire }`; `true` oder eine Liste von Feldnamen legt fest, was den Cache-Schlüssel bildet, `expire` ist standardmäßig `'5 minutes'` |\n| `publish` | Veröffentlicht die Eingabe oder Ausgabe an TMS |\n\nEine Route ruft die Aktion wie jede andere Operation auf: `*Users --> create`.\n\nExample: Aktionen mit Eingabe, Query und Berechtigungen\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Routen\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Die Antwort 10 Minuten lang cachen\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nSetzt die Operation save.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nVerwende sie, wenn eine einzige Operation sowohl erstellt als auch aktualisiert. Eine Route ruft sie mit `*Schema --> save` auf; aus Code verwendest du `CALL('Schema --> save')`.\n\nExample: Deklarieren und routen\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nSetzt die Operation insert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDas Modell wird validiert, bevor die Operation läuft. Eine Route ruft sie mit `*Schema --> insert` auf; aus Code verwendest du `CALL('Schema --> insert')`.\n\nExample: Deklarieren und routen\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nSetzt die Operation update.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDas ganze Modell wird validiert; die ID kommt meist aus der URL in `$.id`. Eine Route ruft sie mit `*Schema --> update` auf; aus Code verwendest du `CALL('Schema --> update')`.\n\nExample: Deklarieren und routen\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nSetzt die Operation patch, die nur die gesendeten Felder ändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nNur die gesendeten Felder werden konvertiert und validiert, und ihre Namen stehen in `$.keys`. Eine Route ruft sie mit `*Schema --> patch` auf; aus Code verwendest du `CALL('Schema --> patch')`.\n\nExample: Deklarieren und routen\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nSetzt die Operation read. `schema.setGet()` ist ein Alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Route ruft sie mit `*Schema --> read` oder `--> get` auf.\n\nExample: Deklarieren und routen\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nSetzt die Operation query, die Elemente auflistet. `schema.setList()` ist ein Alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Route ruft sie mit `*Schema --> query` oder `--> list` auf. Der `filter` konvertiert den Query-String in `$.filter`.\n\nExample: Eine Liste mit einem Filter\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nSetzt die Operation remove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Operation, `function($, model)`. Sie läuft mit dem Schema als `this`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Route ruft sie mit `*Schema --> remove` auf; aus Code verwendest du `CALL('Schema --> remove')`.\n\nExample: Deklarieren und routen\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nFügt eine Operation mit eigenem Namen hinzu. `schema.add()` ist ein Alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Operation. |\n| `fn` | `Function|String` | yes |  | `function($, model)` oder `'Schema --> name'`. |\n| `filter` | `String` | no |  | Felder des Query-Strings, zum Beispiel `'page:Number, limit:Number'`. Die Operation liest sie konvertiert in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nStatt einer Funktion kannst du `'Schema --> name'` angeben, um eine Operation eines anderen Schemas wiederzuverwenden.\n\nExample: Eine eigene Operation\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Eine Operation eines anderen Schemas wiederverwenden\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nFügt eine Funktion hinzu, die vor jeder Operation des Schemas läuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nRufe `next()` auf, um fortzufahren. `next(true)` stoppt; die Middleware muss dann selbst antworten, zum Beispiel mit `$.invalid()`. Mehrere Middleware laufen in der Reihenfolge, in der sie hinzugefügt wurden.\n\nExample: Nur für angemeldete Benutzer\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nSetzt die Ressourcendatei mit den Fehlermeldungen des Schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Ressourcendatei in `resources/`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEin Feld ohne eigene Meldung liest den Schlüssel mit seinem Namen aus dieser Ressource. `schema.setPrefix(prefix)` fügt den Schlüsseln ein Präfix hinzu.\n\nExample: Meldungen aus einer Ressource\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nSetzt eine Funktion, die jede Minute läuft. `schema.setService()` ist ein Alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)`; `counter` zählt die Minuten. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nExample: Jede Stunde aufräumen\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nSetzt eine Funktion, die läuft, wenn das Schema entfernt oder ersetzt wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nExample: Ressourcen freigeben\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nBeendet die Operation und antwortet mit einem Wert oder einem Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | Die Antwort oder ein Fehler. |\n\nEin `Error` oder ein `ErrorBuilder` antwortet mit diesem Fehler. `$.callback(err, value)` funktioniert ebenfalls, sodass du `$.callback` an Funktionen übergeben kannst, die mit `(err, response)` zurückrufen. In einer Schema-Operation antwortet `$.callback()` ohne Wert mit dem Modell.\n\nExample: Mit Daten antworten\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nBeendet die Operation und antwortet mit `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Das Ergebnis. |\n| `value` | `Object` | no |  | Ein Wert, der als `value` gesendet wird. |\n\nReturns: `SchemaOptions` `$`.\n\nMit einem einzigen Argument, das kein Boolean ist, ist dieses der Wert. `$.success(false)` antwortet mit `{ \"success\": false }`.\n\nExample: Mit der neuen ID antworten\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nBeendet die Operation mit einem Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Name des Feldes, eine Meldung, ein Statuscode oder ein Fehler. |\n| `message` | `String` | no |  | Die Fehlermeldung. `@key` liest eine Ressource. |\n\nReturns: `SchemaOptions|Function` `$`, oder ohne Argumente aufgerufen ein Callback.\n\n`$.invalid('email')` meldet ein ungültiges Feld mit seiner Standardmeldung, `$.invalid('email', 'Wrong email')` mit deiner Meldung, `$.invalid('Something went wrong')` eine Meldung ohne Feld und `$.invalid(404)` einen Statuscode. Ein `Error` oder `ErrorBuilder` wird ebenfalls akzeptiert. Ohne Argumente gibt sie eine Funktion `(err)` zurück, die die Operation mit diesem Fehler beendet.\n\nExample: Fehler\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nGibt einen Callback `(err, response)` zurück, der die Operation mit Erfolg oder mit dem Fehler beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true`, um die Antwort zu senden, oder ein zu sendender Wert. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` antwortet mit `{ \"success\": true }`, `$.done(true)` legt die Antwort in `value` ab, und `$.done(something)` legt `something` in `value` ab.\n\nExample: Nach einem Datenbankaufruf antworten\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nGibt einen Callback zurück, der die Operation bei einem Fehler beendet und sonst `fn` ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, ausgeführt mit `$` als `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Nur ohne Fehler fortfahren\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nFührt eine Funktion mit einem Callback im Node.js-Stil aus und gibt eine Promise zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Eine Funktion, deren letztes Argument `callback(err, response)` ist. |\n| `a, b, c` | `Object` | no |  | Argumente für `fn`. |\n\nReturns: `Promise` Wird mit der Antwort aufgelöst.\n\nDie Argumente werden vor dem Callback an `fn` übergeben. Bei einem Fehler endet die Operation damit, und die Promise wird nie aufgelöst.\n\nExample: Auf eine Callback-Funktion warten\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nBeendet die Operation und leitet die Anfrage auf eine andere URL weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Ziel-URL. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Weiterleiten\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nFührt eine andere Aktion oder Operation innerhalb einer Operation aus, mit demselben Controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Operation dieses Schemas, `Schema --> operation` oder ein Aktionsname. |\n| `model` | `Object` | no |  | Daten für die Operation. |\n\nReturns: `SchemaCall` Dasselbe Objekt wie `CALL()`.\n\nEin Name ohne `-->` ist eine Operation des aktuellen Schemas. Ein Präfix `+`, `-` oder `#` setzt die Methode (POST, GET oder PATCH). Es ist `CALL()`, gebunden an die aktuelle Anfrage, daher gibt es dasselbe Objekt mit `.callback()` und `.promise()` zurück.\n\nExample: Eine andere Operation aufrufen\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nLauscht auf ein Event der Operation: `error`, `response` oder `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` oder `end`. |\n| `fn` | `Function` | yes |  | Der Listener. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` erhält die Fehler, `response` die Antwort und `end` beides `(err, response)`. Sie werden ausgelöst, wenn eine Schema-Operation endet, die mit einer einzigen Operation aufgerufen wurde.\n\nExample: Das Ende einer Operation protokollieren\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nDas validierte Modell der Operation.\n\nReturns: `Object`\n\nEs enthält nur die deklarierten Felder, in ihre Typen konvertiert. Operationen erhalten es auch als zweites Argument. `$.value` ist ein Alias.\n\nExample: Das Modell lesen\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nDer Query-String der Anfrage.\n\nReturns: `Object`\n\nIn einer Aktion mit der Option `query` werden die Felder konvertiert und validiert.\n\nExample: Die Query lesen\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nDie dynamischen Parameter der URL der Route.\n\nReturns: `Object`\n\nIn einer Aktion mit der Option `params` werden sie konvertiert und validiert.\n\nExample: Einen Parameter lesen\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nDer erste dynamische Parameter der URL der Route, meist die ID.\n\nReturns: `String`\n\nExample: Nach ID lesen\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nDer angemeldete Benutzer der Anfrage oder `null`.\n\nReturns: `Object`\n\nAktionen mit `user`, `sa` oder `permissions` prüfen ihn, bevor sie laufen. `$.session` enthält die Session.\n\nExample: Den Autor speichern\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nBei einer `PATCH`-Anfrage die Namen der gesendeten Felder; sonst `null`.\n\nReturns: `Array`\n\nNur diese Felder werden konvertiert und validiert.\n\nExample: Nur die gesendeten Felder patchen\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nDer Query-String, mit dem `filter` der Operation konvertiert.\n\nReturns: `Object`\n\nDer Filter ist das zweite Argument von `schema.setQuery()` und den anderen set-Methoden. Ohne Filter ist es die Query, so wie sie gekommen ist.\n\nExample: Typisierte Query\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nDer Controller der Anfrage, oder nichts, wenn die Operation aus Code läuft.\n\nReturns: `Controller`\n\n`$` liest außerdem einige Eigenschaften des Controllers direkt: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` und `$.sessionid`.\n\nExample: Die Anfrage lesen\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nDie Antworten der vorherigen Operationen, wenn eine Route oder `CALL()` mehrere davon ausführt.\n\nReturns: `Object`\n\n`$.response(name)` gibt eine davon zurück.\n\nExample: Das Ergebnis einer vorherigen Operation verwenden\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDeklariert eine Aktion, die zu keinem Schema gehört.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Aktion, zum Beispiel `Users/create`. Er kann weggelassen werden, wenn `options` `id` oder `name` enthält. |\n| `options` | `Object` | yes |  | Optionen der Aktion. |\n\nReturns: `Object` Die Aktion, mit einer Methode `remove()`.\n\nSie akzeptiert dieselben Optionen wie `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) und zusätzlich:\n\n| Option | Was sie bewirkt |\n| --- | --- |\n| `route` | `'API /api/'` deklariert eine API-Route für die Aktion. Der API-Name ist der Name der Aktion in Kleinbuchstaben, mit `_` statt `/`, mit `+`, wenn die Aktion `input` hat, und sonst mit `-` |\n| `csrf`, `encrypt`, `compress` | Wie `schema.csrf()`, `schema.encrypt()` und `schema.compress()` |\n\nDie Aktion läuft mit `$` als `this`. Deklarierst du eine Aktion mit einem bereits vorhandenen Namen, wird sie ersetzt, und `action.remove()` entfernt sie samt ihrer Route. Eine Route ruft eine Aktion mit `-->` und ohne Schema auf.\n\nExample: Eine Aktion und ihre Route\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: Eine Aktion mit eigener API-Route\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nFührt Aktionen oder Schema-Operationen aus Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Aktion oder `Schema --> operations`, optional mit einem Präfix `+`, `-` oder `#`. |\n| `model` | `Object` | no |  | Daten für die Operation. Sie werden validiert. |\n| `controller` | `Controller|SchemaOptions` | no |  | Die Anfrage, mit der ausgeführt wird, oder ein `$`. |\n\nReturns: `SchemaCall` Ein Objekt mit den Methoden aus der Tabelle.\n\n`name` ist eine Aktion (`Users/create`), mehrere durch Leerzeichen getrennte Aktionen oder `Schema --> operations`. Ein Präfix `+`, `-` oder `#` setzt die Methode (POST, GET oder PATCH); ohne Präfix ist der Aufruf POST, wenn es ein Modell gibt. Der Aufruf startet im nächsten Tick, also setze vorher seine Optionen:\n\n| Methode | Was sie setzt |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` und `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (oder den Benutzer eines `$`) und die Sprache |\n| `.controller(ctrl)` | Den Controller (oder den Controller eines `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Beendet `$` bei einem Fehler, sonst führt es `fn(response)` aus |\n| `.promise([$])` | Gibt ein Promise zurück; mit `$` beendet ein Fehler diese Operation |\n| `.debug()` | Gibt die Eingabe und das Ergebnis in der Konsole aus |\n\nBei mehreren Operationen ist die Antwort ein Objekt mit dem Ergebnis jeder einzelnen.\n\nExample: Eine Aktion ausführen\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Auf eine Schema-Operation warten\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nFührt Schema-Operationen aus Code aus. `$ACTION()` ist ein Alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` mit einem Methodenpräfix. |\n| `model` | `Object` | no |  | Daten für die Operation. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Die Anfrage oder ein Objekt mit `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` Ein Promise, wenn es keinen Callback gibt.\n\n`name` ist `+Schema --> operations` (oder `-`, `#` oder eine Methode wie `POST Schema --> insert`). Statt eines Controllers kannst du ein Objekt mit `query`, `params`, `user`, `session`, `body`, `headers` und `id` übergeben. Ohne Callback gibt sie ein Promise zurück. Für Aktionen, die mit `NEWACTION()` deklariert wurden, verwendest du `CALL()`.\n\nExample: Aus Code einfügen\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Mit einer Query und einem Benutzer\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nKonvertiert und validiert ein Modell mit einem Schema, ohne eine Operation auszuführen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name des Schemas. |\n| `model` | `Object` | yes |  | Zu validierende Daten. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` konvertiert die Daten nur. |\n| `controller` | `Controller` | no |  | Ein Controller, der den Fehler statt des Promise erhält. |\n\nReturns: `Promise` Das validierte Modell, wenn es keinen Callback gibt.\n\nOhne Callback gibt sie ein Promise zurück.\n\nExample: Daten validieren\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nFührt eine mit `schema.addOperation()` hinzugefügte Operation eines Schemas aus Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Der Name des Schemas. |\n| `name` | `String` | yes |  | Der in `schema.addOperation()` angegebene Name. |\n| `options` | `Object` | no |  | Eigene Optionen, verfügbar als `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Der Controller oder ein `$`-Objekt. |\n\nReturns: `Boolean` `true`, wenn das Schema existiert.\n\n`schema.addOperation(name, operation, [filter])` verknüpft einen Namen im Schema mit einer globalen Operation, die mit `NEWOPERATION()` deklariert wurde. `$OPERATION()` führt sie aus: Das Schema ruft `OPERATION(operation, $.model, $.callback, schemaName, $)` auf, sodass die Operation über das Schema antwortet und dessen Controller teilt.\n\nDas Modell wird weder vorbereitet noch validiert: `$.model` ist ein leeres Objekt, und die Optionen kommen als `$.options` an. Die Middleware des Schemas läuft trotzdem. Ist `options` eine Funktion, ist sie der Callback. Ein fehlendes Schema ruft den Callback mit dem Fehler `Schema \"name\" not found.` auf; ein Schema ohne die Operation antwortet mit `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nVerwechsle sie nicht mit `OPERATION()`, das eine globale Operation direkt ausführt.\n\nExample: Eine Operation verknüpfen und ausführen\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nFührt einen mit `schema.addTask()` hinzugefügten Task eines Schemas aus Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Der Name des Schemas. |\n| `name` | `String` | yes |  | Der in `schema.addTask()` angegebene Name. |\n| `options` | `Object` | no |  | Eigene Optionen, verfügbar als `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Der Controller oder ein `$`-Objekt. |\n\nReturns: `Boolean` `true`, wenn das Schema existiert.\n\n`schema.addTask(name, task, [filter], [callback])` verknüpft einen Namen im Schema mit einem Task-Schritt, der mit `NEWTASK()` deklariert wurde (`task` ist `'name/step'`). `$TASK()` führt ihn aus: Das Schema startet `TASK(task, $.callback, $)` mit `$.model` als Wert des Tasks. Mit dem `callback` von `addTask()` ruft das Schema stattdessen `callback($, err, response)` auf, und du antwortest selbst.\n\nDas Modell wird weder vorbereitet noch validiert: `$.model` ist ein leeres Objekt, und die Optionen kommen als `$.options` an. Ist `options` eine Funktion, ist sie der Callback. Ein fehlendes Schema ruft den Callback mit dem Fehler `Schema \"name\" not found.` auf.\n\nExample: Einen Task verknüpfen und ausführen\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nGibt ein Objekt mit Zufallsdaten zurück, das zu einem Schema passt, für Tests und Demos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Ein Schemaname, eine Inline-Deklaration oder ein Objekt mit Typen. |\n| `onlyrequired` | `Boolean` | no | `false` | Füllt nur die Pflichtfelder. |\n\nReturns: `Object` Das Fake-Modell.\n\n`schema` ist der Name eines Schemas, eine Inline-Deklaration wie `'name:String, email:Email'` oder ein Objekt wie `{ id: UID, name: 'String(30)' }`. Jedes Feld erhält einen Zufallswert seines Typs: E-Mails, Telefonnummern, Postleitzahlen, URLs, Bezeichner (`UID`, `GUID`), Zahlen, Datumswerte, Booleans und Strings (auf die deklarierte Länge gekürzt, höchstens 30 Zeichen). Arrays erhalten zwei Elemente, Enums und Schlüssel-Wert-Listen einen ihrer Werte, und Felder eines anderen Schemas ein verschachteltes Fake-Objekt.\n\nEinige Feldnamen ergeben realistische Werte: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nMit `onlyrequired` werden nur die Pflichtfelder eines benannten Schemas gefüllt.\n\nExample: Aus einem Schema\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Inline\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nFügt der Operation `query` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `query` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `query` können mehrere Erweiterungen hinzugefügt werden. Alias: `schema.setListExtension()`.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nFügt der Operation `read` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `read` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `read` können mehrere Erweiterungen hinzugefügt werden. Alias: `schema.setGetExtension()`.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nFügt der Operation `insert` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `insert` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `insert` können mehrere Erweiterungen hinzugefügt werden.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nFügt der Operation `update` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `update` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `update` können mehrere Erweiterungen hinzugefügt werden.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nFügt der Operation `patch` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `patch` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `patch` können mehrere Erweiterungen hinzugefügt werden.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nFügt der Operation `remove` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `remove` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `remove` können mehrere Erweiterungen hinzugefügt werden.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nFügt der Operation `save` eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sind die Optionen der laufenden Operation, `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einer bestehenden Operation `save` hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Derselben Operation `save` können mehrere Erweiterungen hinzugefügt werden.\n\nExample: Eine Operation aus einem Plugin erweitern\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nFügt einem Workflow eine Erweiterung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Workflows. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` ist der an `$.extend()` übergebene Wert. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nEine Erweiterung ist eine Funktion `function($, data, next)`, die du einem bestehenden Workflow hinzufügst, meist aus einer anderen Datei oder einem Plugin. Erweiterungen laufen nicht von selbst: Die Operation führt sie aus, wenn sie `$.extend(data, [callback])` aufruft, in der Reihenfolge, in der sie hinzugefügt wurden. Mit einem Callback muss jede Erweiterung `next()` aufrufen; ohne Callback bewirkt `next` nichts. Demselben Workflow können mehrere Erweiterungen hinzugefügt werden. Alias: `schema.addExtension()`.\n\nExample: Einen Workflow erweitern\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nFührt die Erweiterungen der aktuellen Operation aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ein Wert, der jeder Erweiterung als zweites Argument übergeben wird. |\n| `callback` | `Function` | no |  | Läuft nach der letzten Erweiterung. |\n\nReturns: `Boolean` `true`, wenn Erweiterungen existieren, sonst `undefined`.\n\nSie führt die Erweiterungen aus, die mit `schema.setSaveExtension()`, `schema.addWorkflowExtension()` und den anderen für die laufende Operation hinzugefügt wurden. Ohne `callback` laufen alle Erweiterungen auf einmal. Mit `callback` laufen sie nacheinander (jede ruft `next()` auf), und `callback` läuft am Ende, auch wenn es keine Erweiterungen gibt. Die Methode gibt `true` zurück, wenn die Operation Erweiterungen hat.\n\nExample: Auf die Erweiterungen warten\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nVerlangt für jede Route des Schemas ein gültiges CSRF-Token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` schaltet es aus. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDie Routen des Schemas arbeiten dann wie Routen mit dem Flag `csrf`: Das Token aus `controller.csrf()` muss im Header `x-csrf-token` oder im Argument `?csrf=` ankommen. Ein ungültiges Token beantwortet sie mit dem Fehler `Invalid CSRF token`.\n\nExample: Ein Formular schützen\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nVerschlüsselt die Antworten der Routen des Schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` schaltet es aus. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nTextantworten werden mit `CONF.secret_encryption` verschlüsselt und erhalten den Header `X-Encryption: a`. Ohne `secret_encryption` in der Konfiguration wird nichts verschlüsselt.\n\nExample: Verschlüsselte Antworten\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nLässt `null`- und `undefined`-Werte in den JSON-Antworten des Schemas weg.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` schaltet es aus. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDie JSON-Antwort der Routen des Schemas wird ohne die Schlüssel serialisiert, deren Wert `null` oder `undefined` ist, und ist dadurch kleiner.\n\nExample: Kleineres JSON\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nKopiert Felder, die das Schema nicht definiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | Ein Name, eine durch Kommas getrennte Liste oder ein Array von Namen. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDie aufgeführten Felder werden unverändert aus der Eingabe ins Modell kopiert: ohne Konvertierung und ohne Validierung. Ein einzelner String mit durch Kommas getrennten Namen funktioniert ebenfalls.\n\nExample: Freie Metadaten\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nFügt eine asynchrone Prüfung eines Feldes hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | Wie lange das Ergebnis gehalten wird, zum Beispiel `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDie Prüfung läuft nach der Validierung, nur wenn das Feld einen Wert hat. `fn($)` erhält `$.value`, `$.model`, `$.name`, `$.user`, `$.query` und die anderen Werte der Anfrage. Rufe `$.next([value])` (oder `$.success([value])`) auf, um den Wert zu akzeptieren, optional mit einem neuen, oder `$.invalid(error)`, um ihn abzulehnen; ein abgelehntes Feld wird auf `null` gesetzt. Mit `cache` (eine Ablaufzeit wie `'5 minutes'`) wird das Ergebnis für denselben Wert im Cache gehalten.\n\nExample: Einen Ländercode prüfen\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nEntfernt alle Felder des Schemas.\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nSie entfernt die definierten Felder, die Pflichtfelder, die Prüfungen von `schema.verify()` und die Felder von `schema.allow()`. Die Operationen bleiben erhalten.\n\nExample: Die Felder neu definieren\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nBenennt den Primärschlüssel des Schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDer Name wird in `schema.primary` gespeichert, und `schema.inherit()` kopiert ihn. Das Framework verwendet ihn in den Operationen nicht: Er ist eine Information für deinen eigenen Code.\n\nExample: Ein Primärschlüssel\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nSetzt eine Funktion, die läuft, wenn eine Operation oder die Validierung des Schemas mit Fehlern endet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\n`fn(error, model, type, [name])` erhält den `ErrorBuilder`, das Modell, den Typ der Operation (`'make'` für die Validierung, `'save'`, `'workflow'`, ...) und den Namen eines Workflows. Du kannst die Fehler lesen oder ändern, bevor sie beantwortet werden.\n\nExample: Ungültige Eingaben protokollieren\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nFügt eine Operation des Schemas hinzu, die einen Task ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Operation. |\n| `task` | `String` | yes |  | Der Task in der Form `'name/start'`. |\n| `filter` | `String` | no |  | Felder des Query-Strings. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDer Aufruf der Operation (zum Beispiel `CALL('Schema --> name')` oder `*Schema --> name` in einer Route) führt `TASK(task)` mit dem Modell als Wert aus. Die Antwort des Tasks ist die Antwort der Operation. Mit `callback($, err, response)` antwortest du selbst.\n\nExample: Eine Schema-Operation, die einen Task ausführt\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nFügt eine Operation des Schemas hinzu, die eine Operation von `NEWOPERATION()` ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Operation im Schema. |\n| `operation` | `String` | yes |  | Der Name der Operation aus `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Felder des Query-Strings. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDer Aufruf der Schema-Operation (zum Beispiel `*Schema --> name` in einer Route) führt `OPERATION(operation)` mit dem Modell als Wert aus, und deren Antwort ist die Antwort der Schema-Operation.\n\nExample: Eine Operation wiederverwenden\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nLiest oder ersetzt die Werteliste eines Enum-Feldes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `value` | `Array|Object` | no |  | Eine neue Werteliste. |\n\nReturns: `Array|Object` Die aktuelle Liste, oder `undefined` für andere Felder.\n\nSie funktioniert für Felder, die mit einem Array (Enum) oder einem Objekt (Schlüssel-Wert) definiert sind. Mit `value` wird die Liste ersetzt.\n\nExample: Später geladene Werte\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nBeschreibt die Felder des Schemas.\n\nReturns: `Object` Die Beschreibung der Felder.\n\nSie gibt ein Objekt mit einem Schlüssel pro Feld und dessen `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...) zurück, sowie `required` und `length`, wenn sie gesetzt sind. Nützlich, um einem Client das Schema zu beschreiben.\n\nExample: Die Felder an einen Client senden\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nBereitet ein Modell aus Code vor und validiert es.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Die Eingabe. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` Das vorbereitete Modell (vor den asynchronen Prüfungen).\n\nSie konvertiert die Eingabe anhand der Felder des Schemas, validiert sie und führt die Prüfungen von `schema.verify()` aus. `callback(err, model)` erhält den `ErrorBuilder` oder das vorbereitete Modell. Alias: `schema.load()`.\n\nExample: Einen Wert validieren\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nValidiert ein Modell, ohne es zu konvertieren.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Das Modell. |\n\nReturns: `ErrorBuilder` Die Fehler; `.is` ist `true`, wenn es welche gibt.\n\nSie prüft die Pflichtfelder und die Validierung jedes Feldes. Die Prüfungen von `schema.verify()` führt sie nicht aus.\n\nExample: Ein Modell prüfen\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nErstellt ein Modell mit den Standardwerten der Felder.\n\nReturns: `Object` Ein neues Modell.\n\nJedes Feld erhält seinen Standardwert: `0` für Zahlen, `''` für Strings, `false` für Booleans, `NOW` für Datumswerte, `[]` für Arrays und ein Standardmodell für ein Feld eines anderen Schemas. Alias: `schema.create()`.\n\nExample: Ein leeres Formular\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nEntfernt das Schema.\n\nReturns: `undefined` Nichts.\n\nDas Schema wird aus der Liste der Schemas entfernt, und seine Funktion aus `schema.setDestroy()` läuft.\n\nExample: Ein Schema entfernen\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nFührt einen Workflow des Schemas aus Code mit einem Modell aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Workflows. |\n| `model` | `Object` | yes |  | Die Eingabe. |\n| `options` | `Object` | no |  | Ein Wert, verfügbar als `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Ein Controller oder `$`, von dem Benutzer und Anfrage übernommen werden. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\nDas Modell wird zuerst vorbereitet und validiert, wie in einer Route. `schema.workflow2(name, [options], callback, [controller])` führt ihn ohne Modell und ohne Validierung aus. Für den meisten Code sind `CALL()` und `EXEC()` einfacher.\n\nExample: Einen Workflow ausführen\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nFührt die Operation `query` aus Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Ein Wert, verfügbar als `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Ein Controller oder `$`. |\n\nReturns: `SchemaBuilderEntity` Das Schema, zur Verkettung.\n\n`schema.read()` (Alias `schema.get()`) und `schema.remove()` funktionieren auf dieselbe Weise für die Operationen `read` und `remove`. Diese laufen ohne Modell.\n\nExample: Aus Code auflisten\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabULN2Hx60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Esquemas","summary":"NEWSCHEMA(), los métodos del esquema, el objeto $ de las operaciones, NEWACTION() y cómo ejecutar operaciones desde el código.","markdown":"---\ntitle: Esquemas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Esquemas\n\n> NEWSCHEMA(), los métodos del esquema, el objeto $ de las operaciones, NEWACTION() y cómo ejecutar operaciones desde el código.\n\nUn esquema se declara con `NEWSCHEMA()`, normalmente en un archivo de la carpeta `schemas/`; las acciones sin esquema, con `NEWACTION()`. Cada operación recibe el objeto `$`. La guía [Esquemas y acciones](../../guides/schemas/) explica cómo funcionan juntas las partes; esta página es la referencia exacta.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDeclara un esquema: sus campos, su validación y sus operaciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del esquema, usado en las rutas (`*Users`) y en `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)` que declara los campos y las operaciones, o `null` para eliminar el esquema. |\n\nReturns: `SchemaBuilderEntity` El nuevo esquema (nada cuando se elimina).\n\nLa declaración se ejecuta de inmediato con el esquema como argumento y como `this`. Un esquema con el mismo nombre se reemplaza. Pasa `null` como declaración para eliminar un esquema. Con una función como único argumento, el esquema recibe un nombre aleatorio (esquema dinámico).\n\nExample: Un esquema con campos y una operación\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Eliminar un esquema\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nDevuelve un esquema declarado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del esquema. |\n| `callback` | `Function` | no |  | `function(err, schema)`, llamada cuando el esquema existe. |\n| `timeout` | `Number` | no | `20000` | Cuánto esperar, en milisegundos. |\n\nReturns: `SchemaBuilderEntity` El esquema, o `undefined`. Nada cuando se pasa un callback.\n\nCon un callback, espera hasta que el esquema se declare (20 segundos por defecto) y llama a `callback(err, schema)`.\n\nExample: Leer un esquema\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDeclara un campo: su tipo, si es obligatorio y su mensaje de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nombre del campo, o un array de nombres. |\n| `type` | `Function|String|Array|Object` | yes |  | Tipo del campo (ver arriba), o `null` para eliminarlo. |\n| `required` | `Boolean|Function|String` | no | `false` | `true`; una función `(value, model)` que devuelve `true`, `false` o un mensaje de error; o un mensaje de error, que además hace el campo obligatorio. |\n| `error` | `String` | no |  | Mensaje de error cuando el campo no es válido. `@key` lee un recurso. |\n| `xss` | `Boolean|Number` | no |  | Para strings: `true` vacía un valor con XSS o inyección SQL, `1` comprueba solo XSS, `2` solo inyección SQL. |\n\nReturns: `Function` `function(value)` que establece el valor por defecto (un valor o una función) y devuelve el esquema.\n\nTipos: `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, un objeto en línea `'name:String, age:Number'`, un enum `['a', 'b']`, un objeto clave-valor, `Array` o `'[Type]'`, y el nombre de otro esquema (`'Address'`, `'[Address]'`).\n\nUn campo obligatorio no debe estar vacío: un string debe tener caracteres (y un valor válido para `Email`, `URL`, `UID` y similares), un número debe ser mayor que `0`, un booleano `true` y un array debe tener elementos. Un campo de otro esquema siempre se valida.\n\nLa función que devuelve establece el valor por defecto y devuelve el esquema. `type` `null` elimina el campo. Un array de nombres declara varios campos con el mismo tipo.\n\nExample: Campos\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Valores por defecto\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nHace obligatorio un campo declarado, siempre o solo cuando se cumple una condición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo, o varios nombres separados por comas. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)` que devuelve `true` cuando el campo debe validarse; o `false` para hacer el campo opcional. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\n`fn(model, operations)` decide en cada validación si el campo se valida. `operations` es un objeto con los nombres de las operaciones que ejecuta la ruta, así que `operations.insert` es verdadero al insertar. `false` en lugar de una función vuelve a hacer el campo opcional. Se pueden separar varios nombres con comas. El campo debe declararse antes.\n\nExample: Obligatorio solo al insertar\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nElimina un campo declarado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nExample: Eliminar un campo de un esquema heredado\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nCopia los campos, las operaciones y los ajustes de otro esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del esquema del que heredar. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nEspera hasta que el otro esquema se declare. Se conservan los campos y las operaciones que el esquema ya tiene.\n\nExample: Heredar\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nEl esquema recibe un array de elementos en lugar de un objeto.\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nCada elemento se convierte y se valida. Los datos que no son un array se convierten en un array vacío.\n\nExample: Un array de elementos\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDeclara una operación con su entrada, query, parámetros y permisos en un solo objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la operación, opcionalmente con parámetros de URL (`read/{id:UID}`). Se puede omitir cuando `options` tiene `id` o `name`. |\n| `options` | `Object` | yes |  | Opciones de la acción (ver la tabla). |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\n`input`, `query`, `params` y `output` aceptan una declaración en línea (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` es obligatorio, `@Name` es otro esquema o acción) o el nombre de un esquema JSON de `jsonschemas/`. Los datos no válidos detienen la acción con un error. Un nombre como `'read/{id:UID}'` declara `params` a partir del nombre.\n\nOpciones:\n\n| Opción | Qué hace |\n| --- | --- |\n| `action` | `function($, model)`: la acción. Se ejecuta con el esquema como `this` |\n| `name` | Una descripción |\n| `input` | Campos del cuerpo de la petición; el resultado está en `model` |\n| `output` | Campos de la respuesta |\n| `query` | Campos de la query string, en `$.query` (`filter` es un alias) |\n| `params` | Campos de los parámetros de URL, en `$.params` |\n| `user` | `true`: solo un usuario autenticado; si no, `401` |\n| `sa` | `true`: solo un usuario con `sa` o `su` |\n| `permissions` | Un string o un array; el usuario necesita uno de ellos en `user.permissions` o `user.roles` (`sa`/`su` siempre pasan) |\n| `cache` | Guarda la respuesta en caché: `{ query, params, user, language, expire }`; `true` o una lista de nombres de campo elige qué forma la clave de caché, `expire` es `'5 minutes'` por defecto |\n| `publish` | Publica la entrada o la salida en TMS |\n\nUna ruta llama a la acción como a cualquier otra operación: `*Users --> create`.\n\nExample: Acciones con entrada, query y permisos\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Rutas\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Guardar la respuesta en caché durante 10 minutos\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nEstablece la operación save.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nÚsala cuando una sola operación crea y actualiza. Una ruta la llama con `*Schema --> save`; desde el código usa `CALL('Schema --> save')`.\n\nExample: Declararla y enrutarla\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nEstablece la operación insert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nEl modelo se valida antes de que se ejecute la operación. Una ruta la llama con `*Schema --> insert`; desde el código usa `CALL('Schema --> insert')`.\n\nExample: Declararla y enrutarla\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nEstablece la operación update.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nSe valida todo el modelo; el id suele venir de la URL en `$.id`. Una ruta la llama con `*Schema --> update`; desde el código usa `CALL('Schema --> update')`.\n\nExample: Declararla y enrutarla\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nEstablece la operación patch, que cambia solo los campos enviados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nSolo los campos enviados se convierten y se validan, y sus nombres están en `$.keys`. Una ruta la llama con `*Schema --> patch`; desde el código usa `CALL('Schema --> patch')`.\n\nExample: Declararla y enrutarla\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nEstablece la operación read. `schema.setGet()` es un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna ruta la llama con `*Schema --> read` o `--> get`.\n\nExample: Declararla y enrutarla\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nEstablece la operación query, que lista elementos. `schema.setList()` es un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna ruta la llama con `*Schema --> query` o `--> list`. El `filter` convierte la query string en `$.filter`.\n\nExample: Una lista con un filtro\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nEstablece la operación remove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La operación, `function($, model)`. Se ejecuta con el esquema como `this`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna ruta la llama con `*Schema --> remove`; desde el código usa `CALL('Schema --> remove')`.\n\nExample: Declararla y enrutarla\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nAñade una operación con tu propio nombre. `schema.add()` es un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la operación. |\n| `fn` | `Function|String` | yes |  | `function($, model)`, o `'Schema --> name'`. |\n| `filter` | `String` | no |  | Campos de la query string, por ejemplo `'page:Number, limit:Number'`. La operación los lee convertidos en `$.filter`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nEn lugar de una función puedes dar `'Schema --> name'` para reutilizar una operación de otro esquema.\n\nExample: Una operación propia\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Reutilizar una operación de otro esquema\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nAñade una función que se ejecuta antes de cada operación del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLlama a `next()` para continuar. `next(true)` detiene la ejecución, así que el middleware debe responder por sí mismo, por ejemplo con `$.invalid()`. Varios middleware se ejecutan en el orden en que se añadieron.\n\nExample: Solo para usuarios autenticados\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nEstablece el archivo de recursos con los mensajes de error del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del archivo de recursos en `resources/`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUn campo sin mensaje propio lee de este recurso la clave con su nombre. `schema.setPrefix(prefix)` añade un prefijo a las claves.\n\nExample: Mensajes desde un recurso\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nEstablece una función que se ejecuta cada minuto. `schema.setService()` es un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)`; `counter` cuenta los minutos. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nExample: Limpiar cada hora\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nEstablece una función que se ejecuta cuando el esquema se elimina o se reemplaza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nExample: Liberar recursos\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina la operación y responde con un valor o un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | La respuesta, o un error. |\n\nUn `Error` o un `ErrorBuilder` responde con ese error. `$.callback(err, value)` también funciona, así que puedes pasar `$.callback` a funciones que devuelven `(err, response)`. En una operación de esquema, `$.callback()` sin valor responde con el modelo.\n\nExample: Responder con datos\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermina la operación y responde `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | El resultado. |\n| `value` | `Object` | no |  | Un valor enviado como `value`. |\n\nReturns: `SchemaOptions` `$`.\n\nCon un argumento que no es booleano, ese argumento es el valor. `$.success(false)` responde `{ \"success\": false }`.\n\nExample: Responder con el nuevo id\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nTermina la operación con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Nombre del campo, un mensaje, un código de estado o un error. |\n| `message` | `String` | no |  | El mensaje de error. `@key` lee un recurso. |\n\nReturns: `SchemaOptions|Function` `$`, o un callback cuando se llama sin argumentos.\n\n`$.invalid('email')` indica un campo no válido con su mensaje por defecto, `$.invalid('email', 'Wrong email')` con tu mensaje, `$.invalid('Something went wrong')` un mensaje sin campo y `$.invalid(404)` un código de estado. También acepta un `Error` o un `ErrorBuilder`. Sin argumentos devuelve una función `(err)` que termina la operación con ese error.\n\nExample: Errores\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nDevuelve un callback `(err, response)` que termina la operación con éxito o con el error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` para enviar la respuesta, o un valor para enviar. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` responde `{ \"success\": true }`, `$.done(true)` pone la respuesta en `value` y `$.done(something)` pone `something` en `value`.\n\nExample: Responder tras una llamada a la base de datos\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nDevuelve un callback que termina la operación si hay un error y, si no, ejecuta `fn`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, ejecutada con `$` como `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Continuar solo si no hay error\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nEjecuta una función con un callback al estilo de Node.js y devuelve una promesa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una función cuyo último argumento es `callback(err, response)`. |\n| `a, b, c` | `Object` | no |  | Argumentos para `fn`. |\n\nReturns: `Promise` Se resuelve con la respuesta.\n\nLos argumentos se pasan a `fn` antes del callback. Si hay un error, la operación termina con él y la promesa nunca se resuelve.\n\nExample: Esperar con await una función con callback\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermina la operación y redirige la petición a otra URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de destino. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Redirigir\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nEjecuta otra acción u operación desde dentro de una operación, con el mismo controlador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Operación de este esquema, `Schema --> operation` o un nombre de acción. |\n| `model` | `Object` | no |  | Datos para la operación. |\n\nReturns: `SchemaCall` El mismo objeto que `CALL()`.\n\nUn nombre sin `-->` es una operación del esquema actual. Un prefijo `+`, `-` o `#` establece el método (POST, GET o PATCH). Es `CALL()` vinculado a la petición actual, así que devuelve el mismo objeto con `.callback()` y `.promise()`.\n\nExample: Llamar a otra operación\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nEscucha un evento de la operación: `error`, `response` o `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` o `end`. |\n| `fn` | `Function` | yes |  | El listener. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` recibe los errores, `response` la respuesta y `end` ambos `(err, response)`. Se disparan cuando termina una operación de esquema llamada con una sola operación.\n\nExample: Registrar el final de una operación\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nEl modelo validado de la operación.\n\nReturns: `Object`\n\nContiene solo los campos declarados, convertidos a sus tipos. Las operaciones también lo reciben como segundo argumento. `$.value` es un alias.\n\nExample: Leer el modelo\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nLa query string de la petición.\n\nReturns: `Object`\n\nEn una acción con la opción `query`, los campos se convierten y se validan.\n\nExample: Leer la query\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nLos parámetros dinámicos de la URL de la ruta.\n\nReturns: `Object`\n\nEn una acción con la opción `params`, se convierten y se validan.\n\nExample: Leer un parámetro\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nEl primer parámetro dinámico de la URL de la ruta, normalmente el id.\n\nReturns: `String`\n\nExample: Leer por id\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nEl usuario autenticado de la petición, o `null`.\n\nReturns: `Object`\n\nLas acciones con `user`, `sa` o `permissions` lo comprueban antes de ejecutarse. `$.session` contiene la sesión.\n\nExample: Guardar el autor\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nEn una petición `PATCH`, los nombres de los campos enviados; si no, `null`.\n\nReturns: `Array`\n\nSolo estos campos se convierten y se validan.\n\nExample: Modificar solo los campos enviados\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertida con el `filter` de la operación.\n\nReturns: `Object`\n\nEl filtro es el segundo argumento de `schema.setQuery()` y de los demás métodos set. Sin filtro, es la query tal como llegó.\n\nExample: Query tipada\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nEl controlador de la petición, o nada cuando la operación se ejecuta desde el código.\n\nReturns: `Controller`\n\n`$` también lee directamente algunas propiedades del controlador: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` y `$.sessionid`.\n\nExample: Leer la petición\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nLas respuestas de las operaciones anteriores cuando una ruta o `CALL()` ejecuta varias.\n\nReturns: `Object`\n\n`$.response(name)` devuelve una de ellas.\n\nExample: Usar el resultado de una operación anterior\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDeclara una acción que no pertenece a un esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la acción, por ejemplo `Users/create`. Se puede omitir cuando `options` tiene `id` o `name`. |\n| `options` | `Object` | yes |  | Opciones de la acción. |\n\nReturns: `Object` La acción, con un método `remove()`.\n\nAcepta las mismas opciones que `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) y además:\n\n| Opción | Qué hace |\n| --- | --- |\n| `route` | `'API /api/'` declara una ruta API para la acción. El nombre en la API es el nombre de la acción en minúsculas con `_` en lugar de `/`, con `+` cuando la acción tiene `input` y `-` en caso contrario |\n| `csrf`, `encrypt`, `compress` | Como `schema.csrf()`, `schema.encrypt()` y `schema.compress()` |\n\nLa acción se ejecuta con `$` como `this`. Declarar una acción con un nombre existente la reemplaza, y `action.remove()` la elimina junto con su ruta. Una ruta llama a una acción con `-->` y sin esquema.\n\nExample: Una acción y su ruta\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: Una acción con su propia ruta API\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nEjecuta acciones u operaciones de esquema desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la acción o `Schema --> operations`, opcionalmente con un prefijo `+`, `-` o `#`. |\n| `model` | `Object` | no |  | Datos para la operación. Se validan. |\n| `controller` | `Controller|SchemaOptions` | no |  | La petición con la que ejecutar, o un `$`. |\n\nReturns: `SchemaCall` Un objeto con los métodos de la tabla.\n\n`name` es una acción (`Users/create`), varias acciones separadas por espacios, o `Schema --> operations`. Un prefijo `+`, `-` o `#` establece el método (POST, GET o PATCH); sin él, la llamada es POST cuando hay un modelo. La llamada empieza en el siguiente tick, así que establece antes sus opciones:\n\n| Método | Qué establece |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` y `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (o el usuario de un `$`) y el idioma |\n| `.controller(ctrl)` | El controlador (o el controlador de un `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Termina `$` si hay un error; si no, ejecuta `fn(response)` |\n| `.promise([$])` | Devuelve una promesa; con `$`, un error termina esa operación |\n| `.debug()` | Imprime en la consola la entrada y el resultado |\n\nCon varias operaciones, la respuesta es un objeto con el resultado de cada una.\n\nExample: Ejecutar una acción\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Esperar (await) una operación de esquema\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nEjecuta operaciones de esquema desde el código. `$ACTION()` es un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` con un prefijo de método. |\n| `model` | `Object` | no |  | Datos para la operación. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | La petición, o un objeto con `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` Una promesa cuando no hay callback.\n\n`name` es `+Schema --> operations` (o `-`, `#`, o un método como `POST Schema --> insert`). En lugar de un controlador puedes pasar un objeto con `query`, `params`, `user`, `session`, `body`, `headers` e `id`. Sin callback devuelve una promesa. Para las acciones declaradas con `NEWACTION()`, usa `CALL()`.\n\nExample: Insertar desde el código\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Con una query y un usuario\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nConvierte y valida un modelo con un esquema, sin ejecutar ninguna operación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nombre del esquema. |\n| `model` | `Object` | yes |  | Datos a validar. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` solo convierte los datos. |\n| `controller` | `Controller` | no |  | Un controlador que recibe el error en lugar de la promesa. |\n\nReturns: `Promise` El modelo validado, cuando no hay callback.\n\nSin callback devuelve una promesa.\n\nExample: Validar datos\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nEjecuta desde el código una operación de un esquema, añadida con `schema.addOperation()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | El nombre del esquema. |\n| `name` | `String` | yes |  | El nombre dado en `schema.addOperation()`. |\n| `options` | `Object` | no |  | Opciones propias, disponibles como `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | El controlador, o un objeto `$`. |\n\nReturns: `Boolean` `true` cuando el esquema existe.\n\n`schema.addOperation(name, operation, [filter])` vincula un nombre del esquema a una operación global declarada con `NEWOPERATION()`. `$OPERATION()` la ejecuta: el esquema llama a `OPERATION(operation, $.model, $.callback, schemaName, $)`, así que la operación responde a través del esquema y comparte su controlador.\n\nEl modelo no se prepara ni se valida: `$.model` es un objeto vacío y las opciones llegan como `$.options`. El middleware del esquema se sigue ejecutando. Cuando `options` es una función, es el callback. Si el esquema no existe, se llama al callback con el error `Schema \"name\" not found.`; un esquema sin la operación responde con `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nNo la confundas con `OPERATION()`, que ejecuta directamente una operación global.\n\nExample: Vincular y ejecutar una operación\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nEjecuta desde el código una tarea de un esquema, añadida con `schema.addTask()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | El nombre del esquema. |\n| `name` | `String` | yes |  | El nombre dado en `schema.addTask()`. |\n| `options` | `Object` | no |  | Opciones propias, disponibles como `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | El controlador, o un objeto `$`. |\n\nReturns: `Boolean` `true` cuando el esquema existe.\n\n`schema.addTask(name, task, [filter], [callback])` vincula un nombre del esquema a un paso de tarea declarado con `NEWTASK()` (`task` es `'name/step'`). `$TASK()` la ejecuta: el esquema inicia `TASK(task, $.callback, $)` con `$.model` como valor de la tarea. Con el `callback` de `addTask()`, el esquema llama en su lugar a `callback($, err, response)` y respondes tú.\n\nEl modelo no se prepara ni se valida: `$.model` es un objeto vacío y las opciones llegan como `$.options`. Cuando `options` es una función, es el callback. Si el esquema no existe, se llama al callback con el error `Schema \"name\" not found.`\n\nExample: Vincular y ejecutar una tarea\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nDevuelve un objeto con datos aleatorios que encajan con un esquema, para pruebas y demos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Un nombre de esquema, una declaración en línea o un objeto de tipos. |\n| `onlyrequired` | `Boolean` | no | `false` | Rellena solo los campos obligatorios. |\n\nReturns: `Object` El modelo falso.\n\n`schema` es el nombre de un esquema, una declaración en línea como `'name:String, email:Email'` o un objeto como `{ id: UID, name: 'String(30)' }`. Cada campo recibe un valor aleatorio de su tipo: emails, teléfonos, códigos postales, URLs, identificadores (`UID`, `GUID`), números, fechas, booleanos y strings (cortados a la longitud declarada, como máximo 30 caracteres). Los arrays reciben dos elementos, los enums y las listas clave-valor uno de sus valores, y los campos de otro esquema un objeto falso anidado.\n\nAlgunos nombres de campo dan valores realistas: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nCon `onlyrequired`, solo se rellenan los campos obligatorios de un esquema con nombre.\n\nExample: A partir de un esquema\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: En línea\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `query`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `query` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `query`. Alias: `schema.setListExtension()`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `read`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `read` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `read`. Alias: `schema.setGetExtension()`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `insert`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `insert` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `insert`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `update`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `update` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `update`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `patch`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `patch` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `patch`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `remove`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `remove` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `remove`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nAñade una extensión a la operación `save`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` son las opciones de la operación en curso, `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a la operación `save` existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones a la misma operación `save`.\n\nExample: Extender una operación desde un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nAñade una extensión a un workflow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del workflow. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` es el valor pasado a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nUna extensión es una función `function($, data, next)` que añades a un workflow existente, normalmente desde otro archivo o un plugin. Las extensiones no se ejecutan solas: la operación las ejecuta cuando llama a `$.extend(data, [callback])`, en el orden en que se añadieron. Con un callback, cada extensión debe llamar a `next()`; sin él, `next` no hace nada. Se pueden añadir varias extensiones al mismo workflow. Alias: `schema.addExtension()`.\n\nExample: Extender un workflow\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nEjecuta las extensiones de la operación actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Un valor que se pasa a cada extensión como segundo argumento. |\n| `callback` | `Function` | no |  | Se ejecuta después de la última extensión. |\n\nReturns: `Boolean` `true` cuando existen extensiones; si no, `undefined`.\n\nEjecuta las extensiones añadidas con `schema.setSaveExtension()`, `schema.addWorkflowExtension()` y las demás para la operación en curso. Sin `callback`, todas las extensiones se ejecutan a la vez. Con `callback`, se ejecutan una a una (cada una llama a `next()`) y `callback` se ejecuta al final, también cuando no hay extensiones. El método devuelve `true` cuando la operación tiene extensiones.\n\nExample: Esperar a las extensiones\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nExige un token CSRF válido en cada ruta del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLas rutas del esquema funcionan entonces como rutas con el flag `csrf`: el token de `controller.csrf()` debe llegar en la cabecera `x-csrf-token` o en el argumento `?csrf=`. Un token no válido responde con el error `Invalid CSRF token`.\n\nExample: Proteger un formulario\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nCifra las respuestas de las rutas del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLas respuestas de texto se cifran con `CONF.secret_encryption` y reciben la cabecera `X-Encryption: a`. Sin `secret_encryption` en la configuración no se cifra nada.\n\nExample: Respuestas cifradas\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nOmite los valores `null` y `undefined` de las respuestas JSON del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLa respuesta JSON de las rutas del esquema se serializa sin las claves cuyo valor es `null` o `undefined`, así que es más pequeña.\n\nExample: JSON más pequeño\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nCopia campos que el esquema no define.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | Un nombre, una lista separada por comas o un array de nombres. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLos campos indicados se copian de la entrada al modelo tal cual: sin conversión y sin validación. También funciona un string con nombres separados por comas.\n\nExample: Metadatos libres\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nAñade una comprobación asíncrona de un campo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | Cuánto tiempo se guarda el resultado, por ejemplo `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLa comprobación se ejecuta después de la validación, solo cuando el campo tiene un valor. `fn($)` recibe `$.value`, `$.model`, `$.name`, `$.user`, `$.query` y los demás valores de la petición. Llama a `$.next([value])` (o `$.success([value])`) para aceptar el valor, opcionalmente con uno nuevo, o a `$.invalid(error)` para rechazarlo; un campo rechazado se establece a `null`. Con `cache` (una expiración como `'5 minutes'`) el resultado para el mismo valor se guarda en la caché.\n\nExample: Comprobar un código de país\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nElimina todos los campos del esquema.\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nElimina los campos definidos, los campos obligatorios, las comprobaciones de `schema.verify()` y los campos de `schema.allow()`. Las operaciones se mantienen.\n\nExample: Definir de nuevo los campos\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nIndica la clave primaria del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nEl nombre se guarda en `schema.primary`, y `schema.inherit()` lo copia. El framework no lo usa en las operaciones: es información para tu propio código.\n\nExample: Una clave primaria\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nEstablece una función que se ejecuta cuando una operación o la validación del esquema termina con errores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\n`fn(error, model, type, [name])` recibe el `ErrorBuilder`, el modelo, el tipo de la operación (`'make'` para la validación, `'save'`, `'workflow'`, ...) y el nombre de un workflow. Puedes leer o cambiar los errores antes de que se respondan.\n\nExample: Registrar entradas no válidas\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nAñade una operación del esquema que ejecuta una tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la operación. |\n| `task` | `String` | yes |  | La tarea con la forma `'name/start'`. |\n| `filter` | `String` | no |  | Campos de la query string. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLlamar a la operación (por ejemplo `CALL('Schema --> name')` o `*Schema --> name` en una ruta) ejecuta `TASK(task)` con el modelo como valor. La respuesta de la tarea es la respuesta de la operación. Con `callback($, err, response)` respondes tú.\n\nExample: Una operación de esquema que ejecuta una tarea\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nAñade una operación del esquema que ejecuta una operación de `NEWOPERATION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la operación en el esquema. |\n| `operation` | `String` | yes |  | El nombre de la operación de `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Campos de la query string. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nLlamar a la operación del esquema (por ejemplo `*Schema --> name` en una ruta) ejecuta `OPERATION(operation)` con el modelo como valor, y su respuesta es la respuesta de la operación del esquema.\n\nExample: Reutilizar una operación\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nLee o reemplaza la lista de valores de un campo enum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `value` | `Array|Object` | no |  | Una nueva lista de valores. |\n\nReturns: `Array|Object` La lista actual, o `undefined` para otros campos.\n\nFunciona con campos definidos con un array (enum) o un objeto (clave-valor). Con `value`, la lista se reemplaza.\n\nExample: Valores cargados más tarde\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nDescribe los campos del esquema.\n\nReturns: `Object` La descripción de los campos.\n\nDevuelve un objeto con una clave por campo y su `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...), y `required` y `length` cuando están definidos. Útil para describir el esquema a un cliente.\n\nExample: Enviar los campos a un cliente\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nPrepara y valida un modelo desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | La entrada. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` El modelo preparado (antes de las comprobaciones asíncronas).\n\nConvierte la entrada según los campos del esquema, la valida y ejecuta las comprobaciones de `schema.verify()`. `callback(err, model)` recibe el `ErrorBuilder` o el modelo preparado. Alias: `schema.load()`.\n\nExample: Validar un valor\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nValida un modelo sin convertirlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | El modelo. |\n\nReturns: `ErrorBuilder` Los errores; `.is` es `true` cuando hay alguno.\n\nComprueba los campos obligatorios y la validación de cada campo. No ejecuta las comprobaciones de `schema.verify()`.\n\nExample: Comprobar un modelo\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nCrea un modelo con los valores por defecto de los campos.\n\nReturns: `Object` Un modelo nuevo.\n\nCada campo recibe su valor por defecto: `0` para números, `''` para strings, `false` para booleanos, `NOW` para fechas, `[]` para arrays y un modelo por defecto para un campo de otro esquema. Alias: `schema.create()`.\n\nExample: Un formulario vacío\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nElimina el esquema.\n\nReturns: `undefined` Nada.\n\nEl esquema se quita de la lista de esquemas y se ejecuta su función de `schema.setDestroy()`.\n\nExample: Eliminar un esquema\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nEjecuta desde el código un workflow del esquema con un modelo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del workflow. |\n| `model` | `Object` | yes |  | La entrada. |\n| `options` | `Object` | no |  | Un valor disponible como `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un controlador o `$` del que tomar el usuario y la petición. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\nPrimero se prepara y se valida el modelo, como en una ruta. `schema.workflow2(name, [options], callback, [controller])` lo ejecuta sin modelo y sin validación. Para la mayoría del código, `CALL()` y `EXEC()` son más sencillos.\n\nExample: Ejecutar un workflow\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nEjecuta la operación `query` desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Un valor disponible como `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un controlador o `$`. |\n\nReturns: `SchemaBuilderEntity` El esquema, para encadenar.\n\n`schema.read()` (alias `schema.get()`) y `schema.remove()` funcionan igual para las operaciones `read` y `remove`. Se ejecutan sin modelo.\n\nExample: Listar desde el código\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabULN2Hx60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Schémas","summary":"NEWSCHEMA(), les méthodes des schémas, l'objet $ des opérations, NEWACTION() et la manière d'exécuter des opérations depuis le code.","markdown":"---\ntitle: \"Schémas\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Schémas\n\n> NEWSCHEMA(), les méthodes des schémas, l'objet $ des opérations, NEWACTION() et la manière d'exécuter des opérations depuis le code.\n\nUn schéma est déclaré avec `NEWSCHEMA()`, généralement dans un fichier du dossier `schemas/` ; les actions sans schéma avec `NEWACTION()`. Chaque opération reçoit l'objet `$`. Le guide [Schémas et actions](../../guides/schemas/) explique comment les éléments fonctionnent ensemble ; cette page en est la référence exacte.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDéclare un schéma : ses champs, sa validation et ses opérations.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du schéma, utilisé dans les routes (`*Users`) et dans `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)` qui déclare les champs et les opérations, ou `null` pour supprimer le schéma. |\n\nReturns: `SchemaBuilderEntity` Le nouveau schéma (rien lorsqu'il est supprimé).\n\nLa déclaration s'exécute immédiatement avec le schéma comme argument et comme `this`. Un schéma portant le même nom est remplacé. Passe `null` comme déclaration pour supprimer un schéma. Avec une fonction comme seul argument, le schéma reçoit un nom aléatoire (schéma dynamique).\n\nExample: Un schéma avec des champs et une opération\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Supprimer un schéma\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nRenvoie un schéma déclaré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du schéma. |\n| `callback` | `Function` | no |  | `function(err, schema)`, appelée lorsque le schéma existe. |\n| `timeout` | `Number` | no | `20000` | Durée d'attente, en millisecondes. |\n\nReturns: `SchemaBuilderEntity` Le schéma, ou `undefined`. Rien lorsqu'un callback est fourni.\n\nAvec un callback, elle attend que le schéma soit déclaré (20 secondes par défaut) et appelle `callback(err, schema)`.\n\nExample: Lire un schéma\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDéclare un champ : son type, s'il est obligatoire et son message d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nom du champ, ou un tableau de noms. |\n| `type` | `Function|String|Array|Object` | yes |  | Type du champ (voir ci-dessus), ou `null` pour le supprimer. |\n| `required` | `Boolean|Function|String` | no | `false` | `true` ; une fonction `(value, model)` qui renvoie `true`, `false` ou un message d'erreur ; ou un message d'erreur, qui rend aussi le champ obligatoire. |\n| `error` | `String` | no |  | Message d'erreur lorsque le champ est invalide. `@key` lit une ressource. |\n| `xss` | `Boolean|Number` | no |  | Pour les chaînes : `true` vide une valeur contenant du XSS ou une injection SQL, `1` vérifie uniquement le XSS, `2` uniquement l'injection SQL. |\n\nReturns: `Function` `function(value)` qui définit la valeur par défaut (une valeur ou une fonction) et renvoie le schéma.\n\nTypes : `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, un objet en ligne `'name:String, age:Number'`, une énumération `['a', 'b']`, un objet clé-valeur, `Array` ou `'[Type]'`, et le nom d'un autre schéma (`'Address'`, `'[Address]'`).\n\nUn champ obligatoire ne doit pas être vide : une chaîne doit contenir des caractères (et une valeur valide pour `Email`, `URL`, `UID` et similaires), un nombre doit être supérieur à `0`, un booléen doit valoir `true` et un tableau doit contenir des éléments. Un champ d'un autre schéma est toujours validé.\n\nLa fonction qu'elle renvoie définit la valeur par défaut et renvoie le schéma. Un `type` `null` supprime le champ. Un tableau de noms déclare plusieurs champs du même type.\n\nExample: Champs\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Valeurs par défaut\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nRend obligatoire un champ déclaré, toujours ou uniquement lorsqu'une condition est remplie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ, ou plusieurs noms séparés par des virgules. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)` qui renvoie `true` lorsque le champ doit être validé ; ou `false` pour rendre le champ facultatif. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\n`fn(model, operations)` décide à chaque validation si le champ est validé. `operations` est un objet contenant les noms des opérations que la route exécute, donc `operations.insert` est vrai lors d'une insertion. `false` à la place d'une fonction rend le champ à nouveau facultatif. Plusieurs noms peuvent être séparés par des virgules. Le champ doit être déclaré au préalable.\n\nExample: Obligatoire uniquement lors de l'insertion\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nSupprime un champ déclaré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nExample: Supprimer un champ d'un schéma hérité\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nCopie les champs, les opérations et les paramètres d'un autre schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du schéma dont hériter. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nElle attend que l'autre schéma soit déclaré. Les champs et les opérations que le schéma possède déjà sont conservés.\n\nExample: Hériter\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nLe schéma reçoit un tableau d'éléments au lieu d'un seul objet.\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nChaque élément est converti et validé. Des données qui ne sont pas un tableau deviennent un tableau vide.\n\nExample: Un tableau d'éléments\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDéclare une opération avec son entrée, sa query, ses paramètres et ses permissions dans un seul objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'opération, éventuellement avec des paramètres d'URL (`read/{id:UID}`). Il peut être omis lorsque `options` contient `id` ou `name`. |\n| `options` | `Object` | yes |  | Options de l'action (voir le tableau). |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\n`input`, `query`, `params` et `output` acceptent une déclaration en ligne (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'` ; `*` signifie obligatoire, `@Name` est un autre schéma ou une autre action) ou le nom d'un schéma JSON de `jsonschemas/`. Des données invalides arrêtent l'action avec une erreur. Un nom comme `'read/{id:UID}'` déclare `params` à partir du nom.\n\nOptions :\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `action` | `function($, model)` : l'action. Elle s'exécute avec le schéma comme `this` |\n| `name` | Une description |\n| `input` | Champs du corps de la requête ; le résultat se trouve dans `model` |\n| `output` | Champs de la réponse |\n| `query` | Champs de la query string, dans `$.query` (`filter` est un alias) |\n| `params` | Champs des paramètres d'URL, dans `$.params` |\n| `user` | `true` : uniquement un utilisateur connecté, sinon `401` |\n| `sa` | `true` : uniquement un utilisateur avec `sa` ou `su` |\n| `permissions` | Une chaîne ou un tableau ; l'utilisateur doit avoir l'une d'elles dans `user.permissions` ou `user.roles` (`sa`/`su` passent toujours) |\n| `cache` | Met la réponse en cache : `{ query, params, user, language, expire }` ; `true` ou une liste de noms de champs choisit ce qui compose la clé du cache, `expire` vaut par défaut `'5 minutes'` |\n| `publish` | Publie l'entrée ou la sortie vers TMS |\n\nUne route appelle l'action comme n'importe quelle autre opération : `*Users --> create`.\n\nExample: Actions avec entrée, query et permissions\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Routes\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Mettre la réponse en cache pendant 10 minutes\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération save.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUtilise-la lorsqu'une même opération crée et met à jour. Une route l'appelle avec `*Schema --> save` ; depuis le code, utilise `CALL('Schema --> save')`.\n\nExample: La déclarer et la router\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération insert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLe modèle est validé avant l'exécution de l'opération. Une route l'appelle avec `*Schema --> insert` ; depuis le code, utilise `CALL('Schema --> insert')`.\n\nExample: La déclarer et la router\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération update.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLe modèle entier est validé ; l'id provient généralement de l'URL dans `$.id`. Une route l'appelle avec `*Schema --> update` ; depuis le code, utilise `CALL('Schema --> update')`.\n\nExample: La déclarer et la router\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération patch, qui ne modifie que les champs envoyés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nSeuls les champs envoyés sont convertis et validés, et leurs noms se trouvent dans `$.keys`. Une route l'appelle avec `*Schema --> patch` ; depuis le code, utilise `CALL('Schema --> patch')`.\n\nExample: La déclarer et la router\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération read. `schema.setGet()` est un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne route l'appelle avec `*Schema --> read` ou `--> get`.\n\nExample: La déclarer et la router\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération query, qui liste des éléments. `schema.setList()` est un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne route l'appelle avec `*Schema --> query` ou `--> list`. Le `filter` convertit la query string dans `$.filter`.\n\nExample: Une liste avec un filtre\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nDéfinit l'opération remove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'opération, `function($, model)`. Elle s'exécute avec le schéma comme `this`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne route l'appelle avec `*Schema --> remove` ; depuis le code, utilise `CALL('Schema --> remove')`.\n\nExample: La déclarer et la router\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nAjoute une opération avec le nom de ton choix. `schema.add()` est un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'opération. |\n| `fn` | `Function|String` | yes |  | `function($, model)`, ou `'Schema --> name'`. |\n| `filter` | `String` | no |  | Champs de la query string, par exemple `'page:Number, limit:Number'`. L'opération les lit convertis dans `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nÀ la place d'une fonction, tu peux donner `'Schema --> name'` pour réutiliser une opération d'un autre schéma.\n\nExample: Une opération personnalisée\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Réutiliser une opération d'un autre schéma\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nAjoute une fonction qui s'exécute avant chaque opération du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nAppelle `next()` pour continuer. `next(true)` arrête l'exécution ; le middleware doit donc répondre lui-même, par exemple avec `$.invalid()`. Plusieurs middleware s'exécutent dans l'ordre où ils ont été ajoutés.\n\nExample: Uniquement pour les utilisateurs connectés\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nDéfinit le fichier de ressources contenant les messages d'erreur du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du fichier de ressources dans `resources/`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUn champ sans message propre lit la clé portant son nom dans cette ressource. `schema.setPrefix(prefix)` ajoute un préfixe aux clés.\n\nExample: Messages depuis une ressource\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nDéfinit une fonction qui s'exécute chaque minute. `schema.setService()` est un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)` ; `counter` compte les minutes. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nExample: Nettoyer toutes les heures\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nDéfinit une fonction qui s'exécute lorsque le schéma est supprimé ou remplacé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nExample: Libérer des ressources\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermine l'opération et répond avec une valeur ou une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | La réponse, ou une erreur. |\n\nUne `Error` ou un `ErrorBuilder` répond avec cette erreur. `$.callback(err, value)` fonctionne aussi, tu peux donc passer `$.callback` aux fonctions qui rappellent avec `(err, response)`. Dans une opération de schéma, `$.callback()` sans valeur répond avec le modèle.\n\nExample: Répondre avec des données\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermine l'opération et répond `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Le résultat. |\n| `value` | `Object` | no |  | Une valeur envoyée comme `value`. |\n\nReturns: `SchemaOptions` `$`.\n\nAvec un seul argument qui n'est pas un booléen, celui-ci est la valeur. `$.success(false)` répond `{ \"success\": false }`.\n\nExample: Répondre avec le nouvel id\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nTermine l'opération avec une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Nom du champ, un message, un code de statut ou une erreur. |\n| `message` | `String` | no |  | Le message d'erreur. `@key` lit une ressource. |\n\nReturns: `SchemaOptions|Function` `$`, ou un callback lorsqu'elle est appelée sans arguments.\n\n`$.invalid('email')` signale un champ invalide avec son message par défaut, `$.invalid('email', 'Wrong email')` avec ton message, `$.invalid('Something went wrong')` un message sans champ et `$.invalid(404)` un code de statut. Une `Error` ou un `ErrorBuilder` est aussi accepté. Sans arguments, elle renvoie une fonction `(err)` qui termine l'opération avec cette erreur.\n\nExample: Erreurs\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nRenvoie un callback `(err, response)` qui termine l'opération par un succès ou par l'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` pour envoyer la réponse, ou une valeur à envoyer. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` répond `{ \"success\": true }`, `$.done(true)` place la réponse dans `value` et `$.done(something)` place `something` dans `value`.\n\nExample: Répondre après un appel à la base de données\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nRenvoie un callback qui termine l'opération en cas d'erreur et exécute sinon `fn`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, exécutée avec `$` comme `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Continuer uniquement sans erreur\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nExécute une fonction avec un callback de style Node.js et renvoie une promesse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Une fonction dont le dernier argument est `callback(err, response)`. |\n| `a, b, c` | `Object` | no |  | Arguments pour `fn`. |\n\nReturns: `Promise` Résolue avec la réponse.\n\nLes arguments sont passés à `fn` avant le callback. En cas d'erreur, l'opération se termine avec celle-ci et la promesse n'est jamais résolue.\n\nExample: Attendre une fonction à callback avec await\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermine l'opération et redirige la requête vers une autre URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL cible. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Rediriger\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nExécute une autre action ou opération depuis une opération, avec le même contrôleur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Opération de ce schéma, `Schema --> operation` ou un nom d'action. |\n| `model` | `Object` | no |  | Données pour l'opération. |\n\nReturns: `SchemaCall` Le même objet que `CALL()`.\n\nUn nom sans `-->` désigne une opération du schéma courant. Un préfixe `+`, `-` ou `#` définit la méthode (POST, GET ou PATCH). C'est `CALL()` lié à la requête courante ; elle renvoie donc le même objet avec `.callback()` et `.promise()`.\n\nExample: Appeler une autre opération\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nÉcoute un événement de l'opération : `error`, `response` ou `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` ou `end`. |\n| `fn` | `Function` | yes |  | L'écouteur. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` reçoit les erreurs, `response` la réponse et `end` les deux `(err, response)`. Ils se déclenchent à la fin d'une opération de schéma appelée avec une seule opération.\n\nExample: Journaliser la fin d'une opération\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nLe modèle validé de l'opération.\n\nReturns: `Object`\n\nIl ne contient que les champs déclarés, convertis dans leurs types. Les opérations le reçoivent aussi en deuxième argument. `$.value` est un alias.\n\nExample: Lire le modèle\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nLa query string de la requête.\n\nReturns: `Object`\n\nDans une action avec l'option `query`, les champs sont convertis et validés.\n\nExample: Lire la query\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nLes paramètres dynamiques de l'URL de la route.\n\nReturns: `Object`\n\nDans une action avec l'option `params`, ils sont convertis et validés.\n\nExample: Lire un paramètre\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nLe premier paramètre dynamique de l'URL de la route, généralement l'id.\n\nReturns: `String`\n\nExample: Lire par id\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nL'utilisateur connecté de la requête, ou `null`.\n\nReturns: `Object`\n\nLes actions avec `user`, `sa` ou `permissions` le vérifient avant de s'exécuter. `$.session` contient la session.\n\nExample: Enregistrer l'auteur\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nDans une requête `PATCH`, les noms des champs envoyés ; sinon `null`.\n\nReturns: `Array`\n\nSeuls ces champs sont convertis et validés.\n\nExample: Ne modifier que les champs envoyés\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertie avec le `filter` de l'opération.\n\nReturns: `Object`\n\nLe filtre est le deuxième argument de `schema.setQuery()` et des autres méthodes set. Sans filtre, c'est la query telle qu'elle est arrivée.\n\nExample: Query typée\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nLe contrôleur de la requête, ou rien lorsque l'opération s'exécute depuis le code.\n\nReturns: `Controller`\n\n`$` lit aussi directement certaines propriétés du contrôleur : `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` et `$.sessionid`.\n\nExample: Lire la requête\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nLes réponses des opérations précédentes lorsqu'une route ou `CALL()` en exécute plusieurs.\n\nReturns: `Object`\n\n`$.response(name)` renvoie l'une d'elles.\n\nExample: Utiliser le résultat d'une opération précédente\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDéclare une action qui n'appartient à aucun schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'action, par exemple `Users/create`. Il peut être omis lorsque `options` contient `id` ou `name`. |\n| `options` | `Object` | yes |  | Options de l'action. |\n\nReturns: `Object` L'action, avec une méthode `remove()`.\n\nElle accepte les mêmes options que `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) ainsi que :\n\n| Option | Ce qu'elle fait |\n| --- | --- |\n| `route` | `'API /api/'` déclare une route API pour l'action. Le nom de l'API est le nom de l'action en minuscules avec `_` à la place de `/`, avec `+` lorsque l'action a un `input` et `-` sinon |\n| `csrf`, `encrypt`, `compress` | Comme `schema.csrf()`, `schema.encrypt()` et `schema.compress()` |\n\nL'action s'exécute avec `$` comme `this`. Déclarer une action avec un nom existant la remplace, et `action.remove()` la supprime avec sa route. Une route appelle une action avec `-->` et sans schéma.\n\nExample: Une action et sa route\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: Une action avec sa propre route API\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nExécute des actions ou des opérations de schéma depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom d'action ou `Schema --> operations`, éventuellement avec un préfixe `+`, `-` ou `#`. |\n| `model` | `Object` | no |  | Données pour l'opération. Elles sont validées. |\n| `controller` | `Controller|SchemaOptions` | no |  | La requête avec laquelle s'exécuter, ou un `$`. |\n\nReturns: `SchemaCall` Un objet avec les méthodes du tableau.\n\n`name` est une action (`Users/create`), plusieurs actions séparées par des espaces, ou `Schema --> operations`. Un préfixe `+`, `-` ou `#` définit la méthode (POST, GET ou PATCH) ; sans préfixe, l'appel est en POST lorsqu'il y a un modèle. L'appel démarre au tick suivant, définis donc ses options auparavant :\n\n| Méthode | Ce qu'elle définit |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` et `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (ou l'utilisateur d'un `$`) et la langue |\n| `.controller(ctrl)` | Le contrôleur (ou le contrôleur d'un `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Termine `$` en cas d'erreur, sinon exécute `fn(response)` |\n| `.promise([$])` | Renvoie une promesse ; avec `$`, une erreur termine cette opération |\n| `.debug()` | Affiche l'entrée et le résultat dans la console |\n\nAvec plusieurs opérations, la réponse est un objet contenant le résultat de chacune.\n\nExample: Exécuter une action\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Attendre une opération de schéma\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nExécute des opérations de schéma depuis le code. `$ACTION()` est un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` avec un préfixe de méthode. |\n| `model` | `Object` | no |  | Données pour l'opération. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | La requête, ou un objet avec `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` Une promesse lorsqu'il n'y a pas de callback.\n\n`name` est `+Schema --> operations` (ou `-`, `#`, ou une méthode comme `POST Schema --> insert`). À la place d'un contrôleur, tu peux passer un objet avec `query`, `params`, `user`, `session`, `body`, `headers` et `id`. Sans callback, elle renvoie une promesse. Pour les actions déclarées avec `NEWACTION()`, utilise `CALL()`.\n\nExample: Insérer depuis le code\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Avec une query et un utilisateur\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nConvertit et valide un modèle avec un schéma, sans exécuter d'opération.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nom du schéma. |\n| `model` | `Object` | yes |  | Données à valider. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` se contente de convertir les données. |\n| `controller` | `Controller` | no |  | Un contrôleur qui reçoit l'erreur à la place de la promesse. |\n\nReturns: `Promise` Le modèle validé, lorsqu'il n'y a pas de callback.\n\nSans callback, elle renvoie une promesse.\n\nExample: Valider des données\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nExécute depuis le code une opération d'un schéma, ajoutée avec `schema.addOperation()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Le nom du schéma. |\n| `name` | `String` | yes |  | Le nom donné dans `schema.addOperation()`. |\n| `options` | `Object` | no |  | Options personnalisées, disponibles dans `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Le contrôleur, ou un objet `$`. |\n\nReturns: `Boolean` `true` lorsque le schéma existe.\n\n`schema.addOperation(name, operation, [filter])` associe un nom du schéma à une opération globale déclarée avec `NEWOPERATION()`. `$OPERATION()` l'exécute : le schéma appelle `OPERATION(operation, $.model, $.callback, schemaName, $)`, si bien que l'opération répond via le schéma et partage son contrôleur.\n\nLe modèle n'est ni préparé ni validé : `$.model` est un objet vide, et les options arrivent dans `$.options`. Le middleware du schéma s'exécute quand même. Lorsque `options` est une fonction, c'est le callback. Un schéma absent appelle le callback avec l'erreur `Schema \"name\" not found.` ; un schéma sans l'opération répond `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nNe la confonds pas avec `OPERATION()`, qui exécute directement une opération globale.\n\nExample: Associer et exécuter une opération\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nExécute depuis le code une tâche d'un schéma, ajoutée avec `schema.addTask()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Le nom du schéma. |\n| `name` | `String` | yes |  | Le nom donné dans `schema.addTask()`. |\n| `options` | `Object` | no |  | Options personnalisées, disponibles dans `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Le contrôleur, ou un objet `$`. |\n\nReturns: `Boolean` `true` lorsque le schéma existe.\n\n`schema.addTask(name, task, [filter], [callback])` associe un nom du schéma à une étape de tâche déclarée avec `NEWTASK()` (`task` vaut `'name/step'`). `$TASK()` l'exécute : le schéma lance `TASK(task, $.callback, $)` avec `$.model` comme valeur de la tâche. Avec le `callback` de `addTask()`, le schéma appelle à la place `callback($, err, response)` et tu réponds toi-même.\n\nLe modèle n'est ni préparé ni validé : `$.model` est un objet vide, et les options arrivent dans `$.options`. Lorsque `options` est une fonction, c'est le callback. Un schéma absent appelle le callback avec l'erreur `Schema \"name\" not found.`\n\nExample: Associer et exécuter une tâche\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nRenvoie un objet avec des données aléatoires correspondant à un schéma, pour les tests et les démos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Un nom de schéma, une déclaration en ligne ou un objet de types. |\n| `onlyrequired` | `Boolean` | no | `false` | Ne remplit que les champs obligatoires. |\n\nReturns: `Object` Le modèle factice.\n\n`schema` est le nom d'un schéma, une déclaration en ligne comme `'name:String, email:Email'` ou un objet comme `{ id: UID, name: 'String(30)' }`. Chaque champ reçoit une valeur aléatoire de son type : e-mails, téléphones, codes postaux, URL, identifiants (`UID`, `GUID`), nombres, dates, booléens et chaînes (coupées à la longueur déclarée, 30 caractères au maximum). Les tableaux reçoivent deux éléments, les énumérations et les listes clé-valeur l'une de leurs valeurs, et les champs d'un autre schéma un objet factice imbriqué.\n\nCertains noms de champs donnent des valeurs réalistes : `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nAvec `onlyrequired`, seuls les champs obligatoires d'un schéma nommé sont remplis.\n\nExample: Depuis un schéma\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: En ligne\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `query`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `query` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `query`. Alias : `schema.setListExtension()`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `read`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `read` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `read`. Alias : `schema.setGetExtension()`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `insert`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `insert` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `insert`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `update`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `update` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `update`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `patch`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `patch` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `patch`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `remove`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `remove` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `remove`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nAjoute une extension à l'opération `save`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` correspond aux options de l'opération en cours, `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à l'opération `save` existante, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées à la même opération `save`.\n\nExample: Étendre une opération depuis un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nAjoute une extension à un workflow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du workflow. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` est la valeur passée à `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nUne extension est une fonction `function($, data, next)` que tu ajoutes à un workflow existant, généralement depuis un autre fichier ou un plugin. Les extensions ne s'exécutent pas d'elles-mêmes : l'opération les exécute lorsqu'elle appelle `$.extend(data, [callback])`, dans l'ordre où elles ont été ajoutées. Avec un callback, chaque extension doit appeler `next()` ; sans callback, `next` ne fait rien. Plusieurs extensions peuvent être ajoutées au même workflow. Alias : `schema.addExtension()`.\n\nExample: Étendre un workflow\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nExécute les extensions de l'opération courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Une valeur passée à chaque extension comme deuxième argument. |\n| `callback` | `Function` | no |  | S'exécute après la dernière extension. |\n\nReturns: `Boolean` `true` lorsque des extensions existent, sinon `undefined`.\n\nElle exécute les extensions ajoutées avec `schema.setSaveExtension()`, `schema.addWorkflowExtension()` et les autres pour l'opération en cours. Sans `callback`, toutes les extensions s'exécutent en même temps. Avec `callback`, elles s'exécutent une par une (chacune appelle `next()`) et `callback` s'exécute à la fin, même lorsqu'il n'y a pas d'extensions. La méthode renvoie `true` lorsque l'opération a des extensions.\n\nExample: Attendre les extensions\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nExige un jeton CSRF valide pour toutes les routes du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLes routes du schéma fonctionnent alors comme des routes avec le flag `csrf` : le jeton de `controller.csrf()` doit arriver dans l'en-tête `x-csrf-token` ou dans l'argument `?csrf=`. Un jeton invalide renvoie l'erreur `Invalid CSRF token`.\n\nExample: Protéger un formulaire\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nChiffre les réponses des routes du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLes réponses texte sont chiffrées avec `CONF.secret_encryption` et reçoivent l'en-tête `X-Encryption: a`. Sans `secret_encryption` dans la configuration, rien n'est chiffré.\n\nExample: Réponses chiffrées\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nOmet les valeurs `null` et `undefined` des réponses JSON du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLa réponse JSON des routes du schéma est sérialisée sans les clés dont la valeur est `null` ou `undefined`, elle est donc plus petite.\n\nExample: JSON plus petit\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nCopie des champs que le schéma ne définit pas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | Un nom, une liste séparée par des virgules ou un tableau de noms. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLes champs listés sont copiés tels quels de l'entrée vers le modèle : sans conversion et sans validation. Une seule chaîne avec des noms séparés par des virgules fonctionne aussi.\n\nExample: Métadonnées libres\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nAjoute une vérification asynchrone d'un champ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | La durée de conservation du résultat, par exemple `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLa vérification s'exécute après la validation, uniquement lorsque le champ a une valeur. `fn($)` reçoit `$.value`, `$.model`, `$.name`, `$.user`, `$.query` et les autres valeurs de la requête. Appelle `$.next([value])` (ou `$.success([value])`) pour accepter la valeur, éventuellement avec une nouvelle, ou `$.invalid(error)` pour la rejeter ; un champ rejeté est mis à `null`. Avec `cache` (une durée d'expiration comme `'5 minutes'`), le résultat pour une même valeur est conservé dans le cache.\n\nExample: Vérifier un code de pays\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nSupprime tous les champs du schéma.\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nElle supprime les champs définis, les champs obligatoires, les vérifications de `schema.verify()` et les champs de `schema.allow()`. Les opérations sont conservées.\n\nExample: Redéfinir les champs\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nNomme la clé primaire du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLe nom est stocké dans `schema.primary`, et `schema.inherit()` le copie. Le framework ne l'utilise pas dans les opérations : c'est une information pour ton propre code.\n\nExample: Une clé primaire\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nDéfinit une fonction qui s'exécute lorsqu'une opération ou la validation du schéma se termine avec des erreurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\n`fn(error, model, type, [name])` reçoit l'`ErrorBuilder`, le modèle, le type de l'opération (`'make'` pour la validation, `'save'`, `'workflow'`, ...) et le nom d'un workflow. Tu peux lire ou modifier les erreurs avant qu'elles soient renvoyées.\n\nExample: Journaliser les entrées invalides\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nAjoute une opération du schéma qui exécute une tâche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'opération. |\n| `task` | `String` | yes |  | La tâche sous la forme `'name/start'`. |\n| `filter` | `String` | no |  | Champs de la query string. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nAppeler l'opération (par exemple `CALL('Schema --> name')` ou `*Schema --> name` dans une route) exécute `TASK(task)` avec le modèle comme valeur. La réponse de la tâche est la réponse de l'opération. Avec `callback($, err, response)`, tu réponds toi-même.\n\nExample: Une opération de schéma qui exécute une tâche\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nAjoute une opération du schéma qui exécute une opération de `NEWOPERATION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'opération dans le schéma. |\n| `operation` | `String` | yes |  | Le nom de l'opération de `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Champs de la query string. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nAppeler l'opération du schéma (par exemple `*Schema --> name` dans une route) exécute `OPERATION(operation)` avec le modèle comme valeur, et sa réponse est la réponse de l'opération du schéma.\n\nExample: Réutiliser une opération\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nLit ou remplace la liste des valeurs d'un champ énuméré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `value` | `Array|Object` | no |  | Une nouvelle liste de valeurs. |\n\nReturns: `Array|Object` La liste actuelle, ou `undefined` pour les autres champs.\n\nElle fonctionne pour les champs définis avec un tableau (énumération) ou un objet (clé-valeur). Avec `value`, la liste est remplacée.\n\nExample: Valeurs chargées plus tard\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nDécrit les champs du schéma.\n\nReturns: `Object` La description des champs.\n\nElle renvoie un objet avec une clé par champ et son `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...), ainsi que `required` et `length` lorsqu'ils sont définis. Utile pour décrire le schéma à un client.\n\nExample: Envoyer les champs à un client\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nPrépare et valide un modèle depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | L'entrée. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` Le modèle préparé (avant les vérifications asynchrones).\n\nElle convertit l'entrée selon les champs du schéma, la valide et exécute les vérifications de `schema.verify()`. `callback(err, model)` reçoit l'`ErrorBuilder` ou le modèle préparé. Alias : `schema.load()`.\n\nExample: Valider une valeur\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nValide un modèle sans le convertir.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Le modèle. |\n\nReturns: `ErrorBuilder` Les erreurs ; `.is` vaut `true` lorsqu'il y en a.\n\nElle vérifie les champs obligatoires et la validation de chaque champ. Elle n'exécute pas les vérifications de `schema.verify()`.\n\nExample: Vérifier un modèle\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nCrée un modèle avec les valeurs par défaut des champs.\n\nReturns: `Object` Un nouveau modèle.\n\nChaque champ reçoit sa valeur par défaut : `0` pour les nombres, `''` pour les chaînes, `false` pour les booléens, `NOW` pour les dates, `[]` pour les tableaux et un modèle par défaut pour un champ d'un autre schéma. Alias : `schema.create()`.\n\nExample: Un formulaire vide\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nSupprime le schéma.\n\nReturns: `undefined` Rien.\n\nLe schéma est retiré de la liste des schémas et sa fonction de `schema.setDestroy()` s'exécute.\n\nExample: Supprimer un schéma\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nExécute un workflow du schéma depuis le code avec un modèle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du workflow. |\n| `model` | `Object` | yes |  | L'entrée. |\n| `options` | `Object` | no |  | Une valeur disponible dans `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un contrôleur ou un `$` dont prendre l'utilisateur et la requête. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\nLe modèle est d'abord préparé et validé, comme dans une route. `schema.workflow2(name, [options], callback, [controller])` l'exécute sans modèle et sans validation. Pour la plupart du code, `CALL()` et `EXEC()` sont plus simples.\n\nExample: Exécuter un workflow\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nExécute l'opération `query` depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Une valeur disponible dans `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un contrôleur ou un `$`. |\n\nReturns: `SchemaBuilderEntity` Le schéma, pour le chaînage.\n\n`schema.read()` (alias `schema.get()`) et `schema.remove()` fonctionnent de la même façon pour les opérations `read` et `remove`. Elles s'exécutent sans modèle.\n\nExample: Lister depuis le code\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabULN2Hx60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Schemi","summary":"NEWSCHEMA(), i metodi dello schema, l'oggetto $ delle operazioni, NEWACTION() e come eseguire le operazioni dal codice.","markdown":"---\ntitle: Schemi\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Schemi\n\n> NEWSCHEMA(), i metodi dello schema, l'oggetto $ delle operazioni, NEWACTION() e come eseguire le operazioni dal codice.\n\nUno schema si dichiara con `NEWSCHEMA()`, di solito in un file della cartella `schemas/`; le azioni senza schema con `NEWACTION()`. Ogni operazione riceve l'oggetto `$`. La guida [Schemi e azioni](../../guides/schemas/) spiega come le parti lavorano insieme; questa pagina è il riferimento esatto.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDichiara uno schema: i suoi campi, la validazione e le operazioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dello schema, usato nelle route (`*Users`) e in `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)` che dichiara campi e operazioni, oppure `null` per rimuovere lo schema. |\n\nReturns: `SchemaBuilderEntity` Il nuovo schema (niente quando viene rimosso).\n\nLa dichiarazione viene eseguita subito con lo schema come argomento e come `this`. Uno schema con lo stesso nome viene sostituito. Passa `null` come dichiarazione per rimuovere uno schema. Con una funzione come unico argomento, lo schema riceve un nome casuale (schema dinamico).\n\nExample: Uno schema con campi e un'operazione\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Rimuovere uno schema\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nRestituisce uno schema dichiarato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dello schema. |\n| `callback` | `Function` | no |  | `function(err, schema)`, chiamata quando lo schema esiste. |\n| `timeout` | `Number` | no | `20000` | Quanto attendere, in millisecondi. |\n\nReturns: `SchemaBuilderEntity` Lo schema, oppure `undefined`. Niente quando viene passata una callback.\n\nCon una callback, attende che lo schema sia dichiarato (20 secondi per impostazione predefinita) e chiama `callback(err, schema)`.\n\nExample: Leggere uno schema\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDichiara un campo: il suo tipo, se è obbligatorio e il suo messaggio di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nome del campo, oppure un array di nomi. |\n| `type` | `Function|String|Array|Object` | yes |  | Tipo del campo (vedi sopra), oppure `null` per rimuoverlo. |\n| `required` | `Boolean|Function|String` | no | `false` | `true`; una funzione `(value, model)` che restituisce `true`, `false` o un messaggio di errore; oppure un messaggio di errore, che rende anche il campo obbligatorio. |\n| `error` | `String` | no |  | Messaggio di errore quando il campo non è valido. `@key` legge una risorsa. |\n| `xss` | `Boolean|Number` | no |  | Per le stringhe: `true` svuota un valore con XSS o SQL injection, `1` controlla solo XSS, `2` solo SQL injection. |\n\nReturns: `Function` `function(value)` che imposta il valore predefinito (un valore o una funzione) e restituisce lo schema.\n\nTipi: `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, un oggetto inline `'name:String, age:Number'`, un enum `['a', 'b']`, un oggetto chiave-valore, `Array` o `'[Type]'`, e il nome di un altro schema (`'Address'`, `'[Address]'`).\n\nUn campo obbligatorio non deve essere vuoto: una stringa deve avere caratteri (e un valore valido per `Email`, `URL`, `UID` e simili), un numero deve essere maggiore di `0`, un booleano `true` e un array deve avere elementi. Un campo di un altro schema viene sempre validato.\n\nLa funzione che restituisce imposta il valore predefinito e restituisce lo schema. `type` `null` rimuove il campo. Un array di nomi dichiara più campi con lo stesso tipo.\n\nExample: Campi\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Valori predefiniti\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nRende obbligatorio un campo dichiarato, sempre o solo quando vale una condizione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo, oppure più nomi separati da virgole. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)` che restituisce `true` quando il campo deve essere validato; oppure `false` per rendere il campo facoltativo. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\n`fn(model, operations)` decide a ogni validazione se il campo viene validato. `operations` è un oggetto con i nomi delle operazioni che la route esegue, quindi `operations.insert` è vero in inserimento. `false` al posto di una funzione rende di nuovo il campo facoltativo. Più nomi possono essere separati da virgole. Il campo deve essere dichiarato prima.\n\nExample: Obbligatorio solo in inserimento\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nRimuove un campo dichiarato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nExample: Rimuovere un campo di uno schema ereditato\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nCopia campi, operazioni e impostazioni di un altro schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dello schema da cui ereditare. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nAttende che l'altro schema sia dichiarato. I campi e le operazioni che lo schema ha già vengono mantenuti.\n\nExample: Ereditare\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nLo schema riceve un array di elementi invece di un solo oggetto.\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nOgni elemento viene convertito e validato. I dati che non sono un array diventano un array vuoto.\n\nExample: Un array di elementi\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDichiara un'operazione con il suo input, la query, i parametri e i permessi in un solo oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'operazione, facoltativamente con parametri dell'URL (`read/{id:UID}`). Può essere omesso quando `options` ha `id` o `name`. |\n| `options` | `Object` | yes |  | Opzioni dell'azione (vedi la tabella). |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\n`input`, `query`, `params` e `output` accettano una dichiarazione inline (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` è obbligatorio, `@Name` è un altro schema o un'altra azione) oppure il nome di un JSON schema da `jsonschemas/`. Dati non validi fermano l'azione con un errore. Un nome come `'read/{id:UID}'` dichiara `params` a partire dal nome.\n\nOpzioni:\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `action` | `function($, model)`: l'azione. Viene eseguita con lo schema come `this` |\n| `name` | Una descrizione |\n| `input` | Campi del corpo della richiesta; il risultato è in `model` |\n| `output` | Campi della risposta |\n| `query` | Campi della query string, in `$.query` (`filter` è un alias) |\n| `params` | Campi dei parametri dell'URL, in `$.params` |\n| `user` | `true`: solo un utente autenticato, altrimenti `401` |\n| `sa` | `true`: solo un utente con `sa` o `su` |\n| `permissions` | Una stringa o un array; l'utente ne ha bisogno di uno in `user.permissions` o `user.roles` (`sa`/`su` passano sempre) |\n| `cache` | Mette in cache la risposta: `{ query, params, user, language, expire }`; `true` o un elenco di nomi di campi sceglie cosa forma la chiave della cache, `expire` è `'5 minutes'` per impostazione predefinita |\n| `publish` | Pubblica l'input o l'output su TMS |\n\nUna route chiama l'azione come qualsiasi altra operazione: `*Users --> create`.\n\nExample: Azioni con input, query e permessi\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Route\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Mettere in cache la risposta per 10 minuti\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nImposta l'operazione di salvataggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUsala quando una sola operazione sia crea sia aggiorna. Una route la chiama con `*Schema --> save`; dal codice usa `CALL('Schema --> save')`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nImposta l'operazione di inserimento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nIl modello viene validato prima che l'operazione venga eseguita. Una route la chiama con `*Schema --> insert`; dal codice usa `CALL('Schema --> insert')`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nImposta l'operazione di aggiornamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nViene validato l'intero modello; l'id di solito arriva dall'URL in `$.id`. Una route la chiama con `*Schema --> update`; dal codice usa `CALL('Schema --> update')`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nImposta l'operazione patch, che modifica solo i campi inviati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nSolo i campi inviati vengono convertiti e validati, e i loro nomi sono in `$.keys`. Una route la chiama con `*Schema --> patch`; dal codice usa `CALL('Schema --> patch')`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nImposta l'operazione di lettura. `schema.setGet()` è un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUna route la chiama con `*Schema --> read` o `--> get`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nImposta l'operazione query, che elenca gli elementi. `schema.setList()` è un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUna route la chiama con `*Schema --> query` o `--> list`. Il `filter` converte la query string in `$.filter`.\n\nExample: Un elenco con un filtro\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nImposta l'operazione di rimozione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | L'operazione, `function($, model)`. Viene eseguita con lo schema come `this`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUna route la chiama con `*Schema --> remove`; dal codice usa `CALL('Schema --> remove')`.\n\nExample: Dichiararla e collegarla a una route\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nAggiunge un'operazione con un nome scelto da te. `schema.add()` è un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'operazione. |\n| `fn` | `Function|String` | yes |  | `function($, model)`, oppure `'Schema --> name'`. |\n| `filter` | `String` | no |  | Campi della query string, per esempio `'page:Number, limit:Number'`. L'operazione li legge convertiti in `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nAl posto di una funzione puoi indicare `'Schema --> name'` per riutilizzare un'operazione di un altro schema.\n\nExample: Un'operazione personalizzata\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Riutilizzare un'operazione di un altro schema\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nAggiunge una funzione che viene eseguita prima di ogni operazione dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nChiama `next()` per continuare. `next(true)` si ferma, quindi il middleware deve rispondere da sé, per esempio con `$.invalid()`. Più middleware vengono eseguiti nell'ordine in cui sono stati aggiunti.\n\nExample: Solo per utenti autenticati\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nImposta il file di risorse con i messaggi di errore dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del file di risorse in `resources/`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn campo senza un proprio messaggio legge da questa risorsa la chiave con il suo nome. `schema.setPrefix(prefix)` aggiunge un prefisso alle chiavi.\n\nExample: Messaggi da una risorsa\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nImposta una funzione che viene eseguita ogni minuto. `schema.setService()` è un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)`; `counter` conta i minuti. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nExample: Pulire ogni ora\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nImposta una funzione che viene eseguita quando lo schema viene rimosso o sostituito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nExample: Liberare risorse\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina l'operazione e risponde con un valore o con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | La risposta, oppure un errore. |\n\nUn `Error` o un `ErrorBuilder` risponde con quell'errore. Funziona anche `$.callback(err, value)`, quindi puoi passare `$.callback` alle funzioni che richiamano con `(err, response)`. In un'operazione di schema, `$.callback()` senza valore risponde con il modello.\n\nExample: Rispondere con dati\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermina l'operazione e risponde `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Il risultato. |\n| `value` | `Object` | no |  | Un valore inviato come `value`. |\n\nReturns: `SchemaOptions` `$`.\n\nCon un solo argomento che non è un booleano, quello è il valore. `$.success(false)` risponde `{ \"success\": false }`.\n\nExample: Rispondere con il nuovo id\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nTermina l'operazione con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Nome del campo, un messaggio, un codice di stato o un errore. |\n| `message` | `String` | no |  | Il messaggio di errore. `@key` legge una risorsa. |\n\nReturns: `SchemaOptions|Function` `$`, oppure una callback quando viene chiamato senza argomenti.\n\n`$.invalid('email')` segnala un campo non valido con il suo messaggio predefinito, `$.invalid('email', 'Wrong email')` con il tuo messaggio, `$.invalid('Something went wrong')` un messaggio senza campo e `$.invalid(404)` un codice di stato. Sono accettati anche un `Error` o un `ErrorBuilder`. Senza argomenti restituisce una funzione `(err)` che termina l'operazione con quell'errore.\n\nExample: Errori\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nRestituisce una callback `(err, response)` che termina l'operazione con un successo o con l'errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` per inviare la risposta, oppure un valore da inviare. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` risponde `{ \"success\": true }`, `$.done(true)` mette la risposta in `value` e `$.done(something)` mette `something` in `value`.\n\nExample: Rispondere dopo una chiamata al database\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nRestituisce una callback che termina l'operazione in caso di errore e altrimenti esegue `fn`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, eseguita con `$` come `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Continuare solo senza errori\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nEsegue una funzione con una callback in stile Node.js e restituisce una promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una funzione il cui ultimo argomento è `callback(err, response)`. |\n| `a, b, c` | `Object` | no |  | Argomenti per `fn`. |\n\nReturns: `Promise` Si risolve con la risposta.\n\nGli argomenti vengono passati a `fn` prima della callback. In caso di errore, l'operazione termina con quell'errore e la promise non viene mai risolta.\n\nExample: Attendere una funzione con callback\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermina l'operazione e reindirizza la richiesta a un altro URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di destinazione. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Redirect\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nEsegue un'altra azione o operazione dall'interno di un'operazione, con lo stesso controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Operazione di questo schema, `Schema --> operation` oppure il nome di un'azione. |\n| `model` | `Object` | no |  | Dati per l'operazione. |\n\nReturns: `SchemaCall` Lo stesso oggetto di `CALL()`.\n\nUn nome senza `-->` è un'operazione dello schema corrente. Un prefisso `+`, `-` o `#` imposta il metodo (POST, GET o PATCH). È `CALL()` legato alla richiesta corrente, quindi restituisce lo stesso oggetto con `.callback()` e `.promise()`.\n\nExample: Chiamare un'altra operazione\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nAscolta un evento dell'operazione: `error`, `response` o `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` o `end`. |\n| `fn` | `Function` | yes |  | Il listener. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` riceve gli errori, `response` la risposta ed `end` entrambi `(err, response)`. Si attivano quando termina un'operazione di schema chiamata con una sola operazione.\n\nExample: Registrare la fine di un'operazione\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nIl modello validato dell'operazione.\n\nReturns: `Object`\n\nContiene solo i campi dichiarati, convertiti nei loro tipi. Le operazioni lo ricevono anche come secondo argomento. `$.value` è un alias.\n\nExample: Leggere il modello\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nLa query string della richiesta.\n\nReturns: `Object`\n\nIn un'azione con l'opzione `query`, i campi vengono convertiti e validati.\n\nExample: Leggere la query\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nI parametri dinamici dell'URL della route.\n\nReturns: `Object`\n\nIn un'azione con l'opzione `params`, vengono convertiti e validati.\n\nExample: Leggere un parametro\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nIl primo parametro dinamico dell'URL della route, di solito l'id.\n\nReturns: `String`\n\nExample: Leggere per id\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nL'utente autenticato della richiesta, oppure `null`.\n\nReturns: `Object`\n\nLe azioni con `user`, `sa` o `permissions` lo verificano prima di essere eseguite. `$.session` contiene la sessione.\n\nExample: Salvare l'autore\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nIn una richiesta `PATCH`, i nomi dei campi inviati; altrimenti `null`.\n\nReturns: `Array`\n\nSolo questi campi vengono convertiti e validati.\n\nExample: Applicare patch solo ai campi inviati\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertita con il `filter` dell'operazione.\n\nReturns: `Object`\n\nIl filtro è il secondo argomento di `schema.setQuery()` e degli altri metodi set. Senza filtro è la query così come è arrivata.\n\nExample: Query tipizzata\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nIl controller della richiesta, oppure niente quando l'operazione viene eseguita dal codice.\n\nReturns: `Controller`\n\n`$` legge anche alcune proprietà del controller direttamente: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` e `$.sessionid`.\n\nExample: Leggere la richiesta\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nLe risposte delle operazioni precedenti quando una route o `CALL()` ne esegue più di una.\n\nReturns: `Object`\n\n`$.response(name)` ne restituisce una.\n\nExample: Usare il risultato di un'operazione precedente\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDichiara un'azione che non appartiene a uno schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'azione, per esempio `Users/create`. Può essere omesso quando `options` ha `id` o `name`. |\n| `options` | `Object` | yes |  | Opzioni dell'azione. |\n\nReturns: `Object` L'azione, con un metodo `remove()`.\n\nAccetta le stesse opzioni di `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) e inoltre:\n\n| Opzione | Cosa fa |\n| --- | --- |\n| `route` | `'API /api/'` dichiara una route API per l'azione. Il nome API è il nome dell'azione in minuscolo con `_` al posto di `/`, con `+` quando l'azione ha `input` e `-` altrimenti |\n| `csrf`, `encrypt`, `compress` | Come `schema.csrf()`, `schema.encrypt()` e `schema.compress()` |\n\nL'azione viene eseguita con `$` come `this`. Dichiarare un'azione con un nome già esistente la sostituisce, e `action.remove()` la rimuove insieme alla sua route. Una route chiama un'azione con `-->` e senza schema.\n\nExample: Un'azione e la sua route\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: Un'azione con la propria route API\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nEsegue azioni od operazioni di schema dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'azione o `Schema --> operations`, facoltativamente con un prefisso `+`, `-` o `#`. |\n| `model` | `Object` | no |  | Dati per l'operazione. Vengono validati. |\n| `controller` | `Controller|SchemaOptions` | no |  | La richiesta con cui eseguire, oppure un `$`. |\n\nReturns: `SchemaCall` Un oggetto con i metodi della tabella.\n\n`name` è un'azione (`Users/create`), più azioni separate da spazi, oppure `Schema --> operations`. Un prefisso `+`, `-` o `#` imposta il metodo (POST, GET o PATCH); senza prefisso, la chiamata è POST quando c'è un modello. La chiamata parte al tick successivo, quindi imposta prima le sue opzioni:\n\n| Metodo | Cosa imposta |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` e `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (o l'utente di un `$`) e la lingua |\n| `.controller(ctrl)` | Il controller (o il controller di un `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Termina `$` in caso di errore, altrimenti esegue `fn(response)` |\n| `.promise([$])` | Restituisce una promise; con `$`, un errore termina quell'operazione |\n| `.debug()` | Stampa l'input e il risultato nella console |\n\nCon più operazioni la risposta è un oggetto con il risultato di ciascuna.\n\nExample: Eseguire un'azione\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Attendere un'operazione di schema con await\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nEsegue operazioni di schema dal codice. `$ACTION()` è un alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` con un prefisso di metodo. |\n| `model` | `Object` | no |  | Dati per l'operazione. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | La richiesta, oppure un oggetto con `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` Una promise quando non c'è una callback.\n\n`name` è `+Schema --> operations` (oppure `-`, `#`, o un metodo come `POST Schema --> insert`). Al posto di un controller puoi passare un oggetto con `query`, `params`, `user`, `session`, `body`, `headers` e `id`. Senza callback restituisce una promise. Per le azioni dichiarate con `NEWACTION()`, usa `CALL()`.\n\nExample: Inserire dal codice\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Con una query e un utente\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nConverte e valida un modello con uno schema, senza eseguire alcuna operazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nome dello schema. |\n| `model` | `Object` | yes |  | Dati da validare. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` si limita a convertire i dati. |\n| `controller` | `Controller` | no |  | Un controller che riceve l'errore al posto della promise. |\n\nReturns: `Promise` Il modello validato, quando non c'è una callback.\n\nSenza callback restituisce una promise.\n\nExample: Validare dati\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nEsegue dal codice un'operazione di uno schema, aggiunta con `schema.addOperation()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Il nome dello schema. |\n| `name` | `String` | yes |  | Il nome indicato in `schema.addOperation()`. |\n| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Il controller, oppure un oggetto `$`. |\n\nReturns: `Boolean` `true` quando lo schema esiste.\n\n`schema.addOperation(name, operation, [filter])` collega un nome nello schema a un'operazione globale dichiarata con `NEWOPERATION()`. `$OPERATION()` la esegue: lo schema chiama `OPERATION(operation, $.model, $.callback, schemaName, $)`, quindi l'operazione risponde attraverso lo schema e ne condivide il controller.\n\nIl modello non viene preparato né validato: `$.model` è un oggetto vuoto, e le opzioni arrivano come `$.options`. I middleware dello schema vengono comunque eseguiti. Quando `options` è una funzione, è la callback. Uno schema mancante chiama la callback con l'errore `Schema \"name\" not found.`; uno schema senza l'operazione risponde con `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nNon confonderlo con `OPERATION()`, che esegue direttamente un'operazione globale.\n\nExample: Collegare ed eseguire un'operazione\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nEsegue dal codice un task di uno schema, aggiunto con `schema.addTask()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Il nome dello schema. |\n| `name` | `String` | yes |  | Il nome indicato in `schema.addTask()`. |\n| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Il controller, oppure un oggetto `$`. |\n\nReturns: `Boolean` `true` quando lo schema esiste.\n\n`schema.addTask(name, task, [filter], [callback])` collega un nome nello schema a un passo di un task dichiarato con `NEWTASK()` (`task` è `'name/step'`). `$TASK()` lo esegue: lo schema avvia `TASK(task, $.callback, $)` con `$.model` come valore del task. Con la `callback` di `addTask()`, lo schema chiama invece `callback($, err, response)` e rispondi tu.\n\nIl modello non viene preparato né validato: `$.model` è un oggetto vuoto, e le opzioni arrivano come `$.options`. Quando `options` è una funzione, è la callback. Uno schema mancante chiama la callback con l'errore `Schema \"name\" not found.`\n\nExample: Collegare ed eseguire un task\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nRestituisce un oggetto con dati casuali che corrispondono a uno schema, per test e demo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Il nome di uno schema, una dichiarazione inline o un oggetto di tipi. |\n| `onlyrequired` | `Boolean` | no | `false` | Compila solo i campi obbligatori. |\n\nReturns: `Object` Il modello fittizio.\n\n`schema` è il nome di uno schema, una dichiarazione inline come `'name:String, email:Email'` o un oggetto come `{ id: UID, name: 'String(30)' }`. Ogni campo riceve un valore casuale del suo tipo: email, numeri di telefono, CAP, URL, identificatori (`UID`, `GUID`), numeri, date, booleani e stringhe (tagliate alla lunghezza dichiarata, al massimo 30 caratteri). Gli array ricevono due elementi, gli enum e gli elenchi chiave-valore uno dei loro valori, e i campi di un altro schema un oggetto fittizio annidato.\n\nAlcuni nomi di campo danno valori realistici: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nCon `onlyrequired` vengono compilati solo i campi obbligatori di uno schema con nome.\n\nExample: Da uno schema\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Inline\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `query`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `query` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `query`. Alias: `schema.setListExtension()`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `read`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `read` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `read`. Alias: `schema.setGetExtension()`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `insert`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `insert` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `insert`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `update`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `update` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `update`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `patch`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `patch` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `patch`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `remove`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `remove` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `remove`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nAggiunge un'estensione all'operazione `save`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sono le opzioni dell'operazione in esecuzione, `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un'operazione `save` esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni alla stessa operazione `save`.\n\nExample: Estendere un'operazione da un plugin\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nAggiunge un'estensione a un workflow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del workflow. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` è il valore passato a `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nUn'estensione è una funzione `function($, data, next)` che aggiungi a un workflow esistente, di solito da un altro file o da un plugin. Le estensioni non vengono eseguite da sole: l'operazione le esegue quando chiama `$.extend(data, [callback])`, nell'ordine in cui sono state aggiunte. Con una callback, ogni estensione deve chiamare `next()`; senza, `next` non fa nulla. Si possono aggiungere più estensioni allo stesso workflow. Alias: `schema.addExtension()`.\n\nExample: Estendere un workflow\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nEsegue le estensioni dell'operazione corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Un valore passato a ogni estensione come secondo argomento. |\n| `callback` | `Function` | no |  | Viene eseguita dopo l'ultima estensione. |\n\nReturns: `Boolean` `true` quando esistono estensioni, altrimenti `undefined`.\n\nEsegue le estensioni aggiunte con `schema.setSaveExtension()`, `schema.addWorkflowExtension()` e gli altri metodi per l'operazione in esecuzione. Senza `callback`, tutte le estensioni vengono eseguite insieme. Con `callback`, vengono eseguite una alla volta (ognuna chiama `next()`) e `callback` viene eseguita alla fine, anche quando non ci sono estensioni. Il metodo restituisce `true` quando l'operazione ha estensioni.\n\nExample: Attendere le estensioni\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nRichiede un token CSRF valido per ogni route dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` la disattiva. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nLe route dello schema funzionano allora come le route con il flag `csrf`: il token di `controller.csrf()` deve arrivare nell'header `x-csrf-token` o nell'argomento `?csrf=`. Un token non valido risponde con l'errore `Invalid CSRF token`.\n\nExample: Proteggere un form\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nCifra le risposte delle route dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` la disattiva. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nLe risposte testuali vengono cifrate con `CONF.secret_encryption` e ricevono l'header `X-Encryption: a`. Senza `secret_encryption` nella configurazione non viene cifrato nulla.\n\nExample: Risposte cifrate\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nEsclude i valori `null` e `undefined` dalle risposte JSON dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` la disattiva. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nLa risposta JSON delle route dello schema viene serializzata senza le chiavi il cui valore è `null` o `undefined`, quindi è più piccola.\n\nExample: JSON più piccolo\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nCopia campi che lo schema non definisce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | Un nome, un elenco separato da virgole o un array di nomi. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nI campi elencati vengono copiati dall'input nel modello così come sono: senza conversione e senza validazione. Funziona anche una sola stringa con i nomi separati da virgole.\n\nExample: Metadati liberi\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nAggiunge un controllo asincrono di un campo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | Per quanto tempo viene mantenuto il risultato, per esempio `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nIl controllo viene eseguito dopo la validazione, solo quando il campo ha un valore. `fn($)` riceve `$.value`, `$.model`, `$.name`, `$.user`, `$.query` e gli altri valori della richiesta. Chiama `$.next([value])` (o `$.success([value])`) per accettare il valore, facoltativamente con uno nuovo, oppure `$.invalid(error)` per rifiutarlo; un campo rifiutato viene impostato a `null`. Con `cache` (una scadenza come `'5 minutes'`) il risultato per lo stesso valore viene mantenuto in cache.\n\nExample: Verificare un codice paese\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nRimuove tutti i campi dello schema.\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nRimuove i campi definiti, i campi obbligatori, i controlli di `schema.verify()` e i campi di `schema.allow()`. Le operazioni restano.\n\nExample: Definire di nuovo i campi\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nIndica la chiave primaria dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nIl nome viene salvato in `schema.primary`, e `schema.inherit()` lo copia. Il framework non lo usa nelle operazioni: è un'informazione per il tuo codice.\n\nExample: Una chiave primaria\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nImposta una funzione che viene eseguita quando un'operazione o la validazione dello schema termina con errori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\n`fn(error, model, type, [name])` riceve l'`ErrorBuilder`, il modello, il tipo dell'operazione (`'make'` per la validazione, `'save'`, `'workflow'`, ...) e il nome di un workflow. Puoi leggere o modificare gli errori prima che vengano restituiti.\n\nExample: Registrare l'input non valido\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nAggiunge un'operazione dello schema che esegue un task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'operazione. |\n| `task` | `String` | yes |  | Il task nella forma `'name/start'`. |\n| `filter` | `String` | no |  | Campi della query string. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nChiamare l'operazione (per esempio `CALL('Schema --> name')` o `*Schema --> name` in una route) esegue `TASK(task)` con il modello come valore. La risposta del task è la risposta dell'operazione. Con `callback($, err, response)` rispondi tu.\n\nExample: Un'operazione di schema che esegue un task\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nAggiunge un'operazione dello schema che esegue un'operazione di `NEWOPERATION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'operazione nello schema. |\n| `operation` | `String` | yes |  | Il nome dell'operazione di `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Campi della query string. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nChiamare l'operazione dello schema (per esempio `*Schema --> name` in una route) esegue `OPERATION(operation)` con il modello come valore, e la sua risposta è la risposta dell'operazione dello schema.\n\nExample: Riutilizzare un'operazione\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nLegge o sostituisce l'elenco dei valori di un campo enum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `value` | `Array|Object` | no |  | Un nuovo elenco di valori. |\n\nReturns: `Array|Object` L'elenco corrente, oppure `undefined` per gli altri campi.\n\nFunziona per i campi definiti con un array (enum) o con un oggetto (chiave-valore). Con `value` l'elenco viene sostituito.\n\nExample: Valori caricati in seguito\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nDescrive i campi dello schema.\n\nReturns: `Object` La descrizione dei campi.\n\nRestituisce un oggetto con una chiave per campo e il suo `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...), più `required` e `length` quando sono impostati. Utile per descrivere lo schema a un client.\n\nExample: Inviare i campi a un client\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nPrepara e valida un modello dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | L'input. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` Il modello preparato (prima dei controlli asincroni).\n\nConverte l'input secondo i campi dello schema, lo valida ed esegue i controlli di `schema.verify()`. `callback(err, model)` riceve l'`ErrorBuilder` o il modello preparato. Alias: `schema.load()`.\n\nExample: Validare un valore\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nValida un modello senza convertirlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Il modello. |\n\nReturns: `ErrorBuilder` Gli errori; `.is` è `true` quando ce ne sono.\n\nVerifica i campi obbligatori e la validazione di ogni campo. Non esegue i controlli di `schema.verify()`.\n\nExample: Verificare un modello\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nCrea un modello con i valori predefiniti dei campi.\n\nReturns: `Object` Un nuovo modello.\n\nOgni campo riceve il suo valore predefinito: `0` per i numeri, `''` per le stringhe, `false` per i booleani, `NOW` per le date, `[]` per gli array e un modello predefinito per un campo di un altro schema. Alias: `schema.create()`.\n\nExample: Un form vuoto\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nRimuove lo schema.\n\nReturns: `undefined` Niente.\n\nLo schema viene rimosso dall'elenco degli schemi e viene eseguita la sua funzione di `schema.setDestroy()`.\n\nExample: Rimuovere uno schema\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nEsegue dal codice un workflow dello schema con un modello.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del workflow. |\n| `model` | `Object` | yes |  | L'input. |\n| `options` | `Object` | no |  | Un valore disponibile come `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un controller o un `$` da cui prendere l'utente e la richiesta. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\nIl modello viene prima preparato e validato, come in una route. `schema.workflow2(name, [options], callback, [controller])` lo esegue senza modello e senza validazione. Per la maggior parte del codice `CALL()` ed `EXEC()` sono più semplici.\n\nExample: Eseguire un workflow\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nEsegue l'operazione `query` dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Un valore disponibile come `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Un controller o un `$`. |\n\nReturns: `SchemaBuilderEntity` Lo schema, per il concatenamento.\n\n`schema.read()` (alias `schema.get()`) e `schema.remove()` funzionano nello stesso modo per le operazioni `read` e `remove`. Queste vengono eseguite senza modello.\n\nExample: Elencare dal codice\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabULN2Hx60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Schémy","summary":"NEWSCHEMA(), metódy schémy, objekt $ operácií, NEWACTION() a ako spúšťať operácie z kódu.","markdown":"---\ntitle: \"Schémy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/schemas/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Schémy\n\n> NEWSCHEMA(), metódy schémy, objekt $ operácií, NEWACTION() a ako spúšťať operácie z kódu.\n\nSchéma sa deklaruje pomocou `NEWSCHEMA()`, zvyčajne v súbore priečinka `schemas/`; akcie bez schémy pomocou `NEWACTION()`. Každá operácia dostane objekt `$`. Príručka [Schémy a akcie](../../guides/schemas/) vysvetľuje, ako časti spolupracujú; táto stránka je presná referencia.\n\n## API\n\n### NEWSCHEMA(name, [declaration])\n\nType: `method`\n\nDeklaruje schému: jej polia, validáciu a operácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov schémy, používaný v trasách (`*Users`) a v `CALL()`. |\n| `declaration` | `Function` | no |  | `function(schema)`, ktorá deklaruje polia a operácie, alebo `null` na odstránenie schémy. |\n\nReturns: `SchemaBuilderEntity` Nová schéma (nič, keď sa odstraňuje).\n\nDeklarácia sa spustí okamžite so schémou ako argumentom a ako `this`. Schéma s rovnakým názvom sa nahradí. Ak chceš schému odstrániť, odovzdaj ako deklaráciu `null`. S funkciou ako jediným argumentom dostane schéma náhodný názov (dynamická schéma).\n\nExample: Schéma s poľami a operáciou\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.define('name', 'String(50)', true);\n\tschema.define('email', 'Email', true);\n\n\tschema.setInsert(function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n\n});\n```\n\nExample: Odstránenie schémy\n```js\nNEWSCHEMA('Users', null);\n```\n\n### GETSCHEMA(name, [callback], [timeout])\n\nType: `method`\n\nVráti deklarovanú schému.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov schémy. |\n| `callback` | `Function` | no |  | `function(err, schema)`, zavolaná, keď schéma existuje. |\n| `timeout` | `Number` | no | `20000` | Ako dlho čakať, v milisekundách. |\n\nReturns: `SchemaBuilderEntity` Schéma alebo `undefined`. Nič, keď je zadaný callback.\n\nS callbackom počká, kým sa schéma deklaruje (predvolene 20 sekúnd), a zavolá `callback(err, schema)`.\n\nExample: Čítanie schémy\n```js\nvar schema = GETSCHEMA('Users');\nconsole.log(schema.fields);\n```\n\n### schema.define(name, type, [required], [error], [xss])\n\nType: `method`\n\nDeklaruje pole: jeho typ, či je povinné, a jeho chybové hlásenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Názov poľa alebo pole názvov. |\n| `type` | `Function|String|Array|Object` | yes |  | Typ poľa (pozri vyššie) alebo `null` na jeho odstránenie. |\n| `required` | `Boolean|Function|String` | no | `false` | `true`; funkcia `(value, model)`, ktorá vráti `true`, `false` alebo chybové hlásenie; alebo chybové hlásenie, ktoré pole zároveň urobí povinným. |\n| `error` | `String` | no |  | Chybové hlásenie, keď je pole neplatné. `@key` prečíta zdroj. |\n| `xss` | `Boolean|Number` | no |  | Pre reťazce: `true` vyprázdni hodnotu s XSS alebo SQL injection, `1` kontroluje len XSS, `2` len SQL injection. |\n\nReturns: `Function` `function(value)`, ktorá nastaví predvolenú hodnotu (hodnotu alebo funkciu) a vráti schému.\n\nTypy: `String`, `'String(length)'`, `'Text'`, `'SafeString'`, `'Name'`, `'Capitalize'`, `'Capitalize2'`, `'Lower'`, `'Upper'`, `'Email'`, `'Phone'`, `'Zip'`, `'URL'`, `'JSON'`, `'Base64'`, `'Color'`, `'Icon'`, `'UID'`/`UID`, `'GUID'`/`GUID`, `Number` (`'Float'`, `'Decimal'`, `'Double'`), `'Int'`/`'Integer'`, `'Byte'`/`'TinyInt'`, `'SmallInt'`, `'Number2'`, `Boolean`, `Date` (`'Time'`, `'DateTime'`), `Object`, vložený objekt `'name:String, age:Number'`, enum `['a', 'b']`, objekt kľúč-hodnota, `Array` alebo `'[Type]'` a názov inej schémy (`'Address'`, `'[Address]'`).\n\nPovinné pole nesmie byť prázdne: reťazec musí mať znaky (a platnú hodnotu pre `Email`, `URL`, `UID` a podobné), číslo musí byť väčšie ako `0`, boolean `true` a pole musí mať položky. Pole inej schémy sa validuje vždy.\n\nFunkcia, ktorú vracia, nastaví predvolenú hodnotu a vráti schému. `type` `null` pole odstráni. Pole názvov deklaruje viac polí s rovnakým typom.\n\nExample: Polia\n```js\nschema.define('id', 'UID');\nschema.define('name', 'String(50)', true);\nschema.define('email', 'Email', 'Enter a valid email address');\nschema.define('age', Number, value => value >= 18, 'You must be an adult');\nschema.define('role', ['admin', 'user'], true);\nschema.define('tags', '[String]');\nschema.define('address', 'Address');\n```\n\nExample: Predvolené hodnoty\n```js\nschema.define('count', Number)(10);\nschema.define('created', Date)(() => new Date());\n```\n\n### schema.required(name, [fn])\n\nType: `method`\n\nUrobí deklarované pole povinným, vždy alebo len pri splnení podmienky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa alebo viac názvov oddelených čiarkami. |\n| `fn` | `Function|Boolean` | no |  | `function(model, operations)`, ktorá vráti `true`, keď sa pole musí validovať; alebo `false`, aby bolo pole voliteľné. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\n`fn(model, operations)` pri každej validácii rozhodne, či sa pole validuje. `operations` je objekt s názvami operácií, ktoré trasa spúšťa, takže pri vkladaní je `operations.insert` pravdivé. `false` namiesto funkcie urobí pole znova voliteľným. Viac názvov sa dá oddeliť čiarkami. Pole musí byť deklarované vopred.\n\nExample: Povinné len pri vkladaní\n```js\nschema.define('password', 'String(30)');\nschema.required('password', (model, operations) => !!operations.insert);\n```\n\n### schema.undefine(name)\n\nType: `method` · Since: `0.0.46`\n\nOdstráni deklarované pole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nExample: Odstránenie poľa zdedenej schémy\n```js\nschema.inherit('Users');\nschema.undefine('password');\n```\n\n### schema.inherit(name)\n\nType: `method`\n\nSkopíruje polia, operácie a nastavenia inej schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov schémy, z ktorej sa dedí. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nPočká, kým sa iná schéma deklaruje. Polia a operácie, ktoré schéma už má, sa ponechajú.\n\nExample: Dedenie\n```js\nNEWSCHEMA('Admins', function(schema) {\n\tschema.inherit('Users');\n\tschema.define('level', Number);\n});\n```\n\n### schema.array()\n\nType: `method` · Since: `0.0.63`\n\nSchéma dostane namiesto jedného objektu pole položiek.\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nKaždá položka sa skonvertuje a zvaliduje. Dáta, ktoré nie sú pole, sa stanú prázdnym poľom.\n\nExample: Pole položiek\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.array();\n\tschema.define('id', 'UID', true);\n\tschema.define('count', Number, true);\n});\n```\n\n### schema.action(name, options)\n\nType: `method` · Since: `0.0.67`\n\nDeklaruje operáciu s jej vstupom, query, parametrami a oprávneniami v jednom objekte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie, voliteľne s parametrami URL (`read/{id:UID}`). Dá sa vynechať, keď `options` obsahuje `id` alebo `name`. |\n| `options` | `Object` | yes |  | Možnosti akcie (pozri tabuľku). |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\n`input`, `query`, `params` a `output` prijímajú deklaráciu na mieste (`'*name:String(50), email:Email, tags:[String], role:{admin|user}'`; `*` je povinné, `@Name` je iná schéma alebo akcia) alebo názov JSON schémy z `jsonschemas/`. Neplatné dáta zastavia akciu chybou. Názov ako `'read/{id:UID}'` deklaruje `params` z názvu.\n\nMožnosti:\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `action` | `function($, model)`: akcia. Beží so schémou ako `this` |\n| `name` | Popis |\n| `input` | Polia tela požiadavky; výsledok je v `model` |\n| `output` | Polia odpovede |\n| `query` | Polia query stringu, v `$.query` (`filter` je alias) |\n| `params` | Polia parametrov URL, v `$.params` |\n| `user` | `true`: len prihlásený používateľ, inak `401` |\n| `sa` | `true`: len používateľ so `sa` alebo `su` |\n| `permissions` | Reťazec alebo pole; používateľ potrebuje jedno z nich v `user.permissions` alebo `user.roles` (`sa`/`su` prejdú vždy) |\n| `cache` | Uloží odpoveď do cache: `{ query, params, user, language, expire }`; `true` alebo zoznam názvov polí určuje, čo tvorí kľúč cache, `expire` je predvolene `'5 minutes'` |\n| `publish` | Publikuje vstup alebo výstup do TMS |\n\nTrasa volá akciu ako akúkoľvek inú operáciu: `*Users --> create`.\n\nExample: Akcie so vstupom, query a oprávneniami\n```js\nNEWSCHEMA('Users', function(schema) {\n\n\tschema.action('list', {\n\t\tname: 'List of users',\n\t\tquery: 'page:Number, limit:Number',\n\t\tuser: true,\n\t\taction: function($) {\n\t\t\tNOSQL('users').find().take($.query.limit || 20).callback($.callback);\n\t\t}\n\t});\n\n\tschema.action('create', {\n\t\tname: 'Create a user',\n\t\tinput: '*name:String(50), *email:Email, role:{admin|user}',\n\t\tpermissions: 'admin',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\tNOSQL('users').insert(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n\n});\n```\n\nExample: Trasy\n```js\nROUTE('GET  /api/users/ *Users --> list');\nROUTE('POST /api/users/ *Users --> create');\n```\n\nExample: Cache odpovede na 10 minút\n```js\nschema.action('stats', {\n\tquery: 'year:Number',\n\tcache: { query: true, expire: '10 minutes' },\n\taction: function($) {\n\t\t// ...\n\t}\n});\n```\n\n### schema.setSave(fn, [filter])\n\nType: `method`\n\nNastaví operáciu save.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nPouži ju, keď jedna operácia vytvára aj aktualizuje. Trasa ju volá pomocou `*Schema --> save`; z kódu použi `CALL('Schema --> save')`.\n\nExample: Deklarácia a trasa\n```js\nschema.setSave(function($, model) {\n\tif (model.id)\n\t\tNOSQL('users').modify(model).where('id', model.id);\n\telse {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t}\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> save');\n```\n\n### schema.setInsert(fn, [filter])\n\nType: `method`\n\nNastaví operáciu insert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nModel sa zvaliduje predtým, ako sa operácia spustí. Trasa ju volá pomocou `*Schema --> insert`; z kódu použi `CALL('Schema --> insert')`.\n\nExample: Deklarácia a trasa\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\tNOSQL('users').insert(model);\n\t$.success(model.id);\n});\n\n// ROUTE('POST /api/users/ *Users --> insert');\n```\n\n### schema.setUpdate(fn, [filter])\n\nType: `method`\n\nNastaví operáciu update.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nValiduje sa celý model; ID zvyčajne pochádza z URL v `$.id`. Trasa ju volá pomocou `*Schema --> update`; z kódu použi `CALL('Schema --> update')`.\n\nExample: Deklarácia a trasa\n```js\nschema.setUpdate(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PUT /api/users/{id}/ *Users --> update');\n```\n\n### schema.setPatch(fn, [filter])\n\nType: `method`\n\nNastaví operáciu patch, ktorá mení len odoslané polia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nSkonvertujú a zvalidujú sa len odoslané polia a ich názvy sú v `$.keys`. Trasa ju volá pomocou `*Schema --> patch`; z kódu použi `CALL('Schema --> patch')`.\n\nExample: Deklarácia a trasa\n```js\nschema.setPatch(function($, model) {\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('PATCH /api/users/{id}/ *Users --> patch');\n```\n\n### schema.setRead(fn, [filter])\n\nType: `method`\n\nNastaví operáciu read. `schema.setGet()` je alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nTrasa ju volá pomocou `*Schema --> read` alebo `--> get`.\n\nExample: Deklarácia a trasa\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n});\n\n// ROUTE('GET /api/users/{id}/ *Users --> read');\n```\n\n### schema.setQuery(fn, [filter])\n\nType: `method`\n\nNastaví operáciu query, ktorá vypisuje položky. `schema.setList()` je alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nTrasa ju volá pomocou `*Schema --> query` alebo `--> list`. `filter` skonvertuje query string do `$.filter`.\n\nExample: Zoznam s filtrom\n```js\nschema.setQuery(function($) {\n\tvar filter = $.filter;\n\tNOSQL('users').find().take(filter.limit || 20).skip(((filter.page || 1) - 1) * (filter.limit || 20)).callback($.callback);\n}, 'page:Number, limit:Number');\n\n// ROUTE('GET /api/users/ *Users --> query');\n```\n\n### schema.setRemove(fn, [filter])\n\nType: `method`\n\nNastaví operáciu remove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Operácia, `function($, model)`. Beží so schémou ako `this`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nTrasa ju volá pomocou `*Schema --> remove`; z kódu použi `CALL('Schema --> remove')`.\n\nExample: Deklarácia a trasa\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('DELETE /api/users/{id}/ *Users --> remove');\n```\n\n### schema.addWorkflow(name, fn, [filter])\n\nType: `method`\n\nPridá operáciu s vlastným názvom. `schema.add()` je alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie. |\n| `fn` | `Function|String` | yes |  | `function($, model)` alebo `'Schema --> name'`. |\n| `filter` | `String` | no |  | Polia query stringu, napríklad `'page:Number, limit:Number'`. Operácia ich číta skonvertované v `$.filter`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nNamiesto funkcie môžeš zadať `'Schema --> name'` a znovu použiť operáciu inej schémy.\n\nExample: Vlastná operácia\n```js\nschema.addWorkflow('activate', function($) {\n\tNOSQL('users').modify({ active: true }).where('id', $.id);\n\t$.success();\n});\n\n// ROUTE('POST /api/users/{id}/activate/ *Users --> activate');\n```\n\nExample: Opätovné použitie operácie inej schémy\n```js\nschema.addWorkflow('check', 'Common --> check');\n```\n\n### schema.middleware(fn)\n\nType: `method`\n\nPridá funkciu, ktorá sa spustí pred každou operáciou schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, next)`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nZavolaj `next()`, ak chceš pokračovať. `next(true)` zastaví, takže middleware musí odpovedať sám, napríklad pomocou `$.invalid()`. Viac middleware beží v poradí, v akom boli pridané.\n\nExample: Len pre prihlásených používateľov\n```js\nschema.middleware(function($, next) {\n\tif ($.user)\n\t\tnext();\n\telse {\n\t\t$.invalid(401);\n\t\tnext(true);\n\t}\n});\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nNastaví súbor zdrojov s chybovými hláseniami schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru zdrojov v `resources/`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nPole bez vlastného hlásenia prečíta z tohto zdroja kľúč so svojím názvom. `schema.setPrefix(prefix)` pridá ku kľúčom prefix.\n\nExample: Hlásenia zo zdroja\n```js\nschema.setResource('errors');\nschema.setPrefix('user_');\nschema.define('email', 'Email', true); // key: user_email\n```\n\n### schema.setTimer(fn)\n\nType: `method` · Since: `0.0.63`\n\nNastaví funkciu, ktorá sa spúšťa každú minútu. `schema.setService()` je alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(counter)`; `counter` počíta minúty. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nExample: Čistenie každú hodinu\n```js\nschema.setTimer(function(counter) {\n\tif (counter % 60 === 0)\n\t\tNOSQL('sessions').remove().where('expire', '<', NOW);\n});\n```\n\n### schema.setDestroy(fn)\n\nType: `method` · Since: `0.0.63`\n\nNastaví funkciu, ktorá sa spustí, keď sa schéma odstráni alebo nahradí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nExample: Uvoľnenie prostriedkov\n```js\nschema.setDestroy(function() {\n\tclearInterval(timer);\n});\n```\n\n### $.callback([value])\n\nType: `method`\n\nUkončí operáciu a odpovie hodnotou alebo chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|Error` | no |  | Odpoveď alebo chyba. |\n\n`Error` alebo `ErrorBuilder` odpovie danou chybou. Funguje aj `$.callback(err, value)`, takže `$.callback` môžeš odovzdať funkciám, ktoré volajú späť s `(err, response)`. V operácii schémy odpovie `$.callback()` bez hodnoty modelom.\n\nExample: Odpoveď s dátami\n```js\nschema.setQuery(function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nUkončí operáciu a odpovie `{ \"success\": true, \"value\": ... }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Výsledok. |\n| `value` | `Object` | no |  | Hodnota odoslaná ako `value`. |\n\nReturns: `SchemaOptions` `$`.\n\nS jedným argumentom, ktorý nie je boolean, je tento argument hodnotou. `$.success(false)` odpovie `{ \"success\": false }`.\n\nExample: Odpoveď s novým ID\n```js\n$.success(model.id);\n// { \"success\": true, \"value\": \"1fd0b001ez51d\" }\n```\n\n### $.invalid(name, [message])\n\nType: `method`\n\nUkončí operáciu chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Number|Error` | yes |  | Názov poľa, hlásenie, stavový kód alebo chyba. |\n| `message` | `String` | no |  | Chybové hlásenie. `@key` prečíta zdroj. |\n\nReturns: `SchemaOptions|Function` `$`, alebo callback, keď sa volá bez argumentov.\n\n`$.invalid('email')` nahlási neplatné pole s predvoleným hlásením, `$.invalid('email', 'Wrong email')` s tvojím hlásením, `$.invalid('Something went wrong')` hlásenie bez poľa a `$.invalid(404)` stavový kód. Prijíma sa aj `Error` alebo `ErrorBuilder`. Bez argumentov vráti funkciu `(err)`, ktorá ukončí operáciu danou chybou.\n\nExample: Chyby\n```js\nschema.setRead(function($) {\n\tNOSQL('users').one().where('id', $.id).callback(function(err, user) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse if (!user)\n\t\t\t$.invalid(404);\n\t\telse\n\t\t\t$.callback(user);\n\t});\n});\n```\n\n### $.done([value])\n\nType: `method`\n\nVráti callback `(err, response)`, ktorý ukončí operáciu úspechom alebo chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Boolean|Object` | no |  | `true` na odoslanie odpovede, alebo hodnota na odoslanie. |\n\nReturns: `Function` `function(err, response)`.\n\n`$.done()` odpovie `{ \"success\": true }`, `$.done(true)` vloží odpoveď do `value` a `$.done(something)` vloží `something` do `value`.\n\nExample: Odpoveď po volaní databázy\n```js\nschema.setRemove(function($) {\n\tNOSQL('users').remove().where('id', $.id).callback($.done());\n});\n```\n\n### $.successful(fn)\n\nType: `method`\n\nVráti callback, ktorý pri chybe ukončí operáciu a inak spustí `fn`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`, spustená s `$` ako `this`. |\n\nReturns: `Function` `function(err, response)`.\n\nExample: Pokračovanie len bez chyby\n```js\nNOSQL('users').one().where('id', $.id).callback($.successful(function(user) {\n\t$.callback(user || {});\n}));\n```\n\n### $.promisify(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nSpustí funkciu s callbackom v štýle Node.js a vráti promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia, ktorej posledný argument je `callback(err, response)`. |\n| `a, b, c` | `Object` | no |  | Argumenty pre `fn`. |\n\nReturns: `Promise` Vyrieši sa s odpoveďou.\n\nArgumenty sa odovzdajú do `fn` pred callbackom. Pri chybe sa operácia s ňou ukončí a promise sa nikdy nevyrieši.\n\nExample: Čakanie na funkciu s callbackom\n```js\nschema.action('read', {\n\taction: async function($) {\n\t\tvar data = await $.promisify(require('fs').readFile, PATH.databases('data.json'));\n\t\t$.callback(data.toString('utf8').parseJSON());\n\t}\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nUkončí operáciu a presmeruje požiadavku na inú URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová URL. |\n\nReturns: `SchemaOptions` `$`.\n\nExample: Presmerovanie\n```js\n$.redirect('/login/');\n```\n\n### $.action(name, [model])\n\nType: `method`\n\nSpustí inú akciu alebo operáciu zvnútra operácie, s tým istým kontrolérom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Operácia tejto schémy, `Schema --> operation` alebo názov akcie. |\n| `model` | `Object` | no |  | Dáta pre operáciu. |\n\nReturns: `SchemaCall` Rovnaký objekt ako `CALL()`.\n\nNázov bez `-->` je operácia aktuálnej schémy. Prefix `+`, `-` alebo `#` nastaví metódu (POST, GET alebo PATCH). Je to `CALL()` naviazané na aktuálnu požiadavku, takže vracia rovnaký objekt s `.callback()` a `.promise()`.\n\nExample: Volanie inej operácie\n```js\nschema.action('create', {\n\tinput: '*name:String',\n\taction: async function($, model) {\n\t\tvar user = await $.action('-read').promise($);\n\t\t// ...\n\t}\n});\n```\n\n### $.on(name, fn)\n\nType: `method` · Since: `0.0.63`\n\nPočúva udalosť operácie: `error`, `response` alebo `end`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `error`, `response` alebo `end`. |\n| `fn` | `Function` | yes |  | Poslucháč. |\n\nReturns: `SchemaOptions` `$`.\n\n`error` dostane chyby, `response` odpoveď a `end` oboje `(err, response)`. Vyvolajú sa, keď skončí operácia schémy zavolaná s jedinou operáciou.\n\nExample: Zalogovanie konca operácie\n```js\n$.on('end', function(err, response) {\n\tconsole.log('done', err, response);\n});\n```\n\n### $.model\n\nType: `property`\n\nValidovaný model operácie.\n\nReturns: `Object`\n\nObsahuje len deklarované polia, skonvertované na ich typy. Operácie ho dostanú aj ako druhý argument. `$.value` je alias.\n\nExample: Čítanie modelu\n```js\nschema.setInsert(function($) {\n\tconsole.log($.model.name);\n\t$.success();\n});\n```\n\n### $.query\n\nType: `property`\n\nQuery string požiadavky.\n\nReturns: `Object`\n\nV akcii s možnosťou `query` sa polia skonvertujú a zvalidujú.\n\nExample: Čítanie query\n```js\n// GET /api/users/?page=2\nvar page = $.query.page;\n```\n\n### $.params\n\nType: `property`\n\nDynamické parametre URL trasy.\n\nReturns: `Object`\n\nV akcii s možnosťou `params` sa skonvertujú a zvalidujú.\n\nExample: Čítanie parametra\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nvar id = $.params.id;\n```\n\n### $.id\n\nType: `property`\n\nPrvý dynamický parameter URL trasy, zvyčajne ID.\n\nReturns: `String`\n\nExample: Čítanie podľa ID\n```js\n// ROUTE('GET /api/users/{id}/ *Users --> read');\nNOSQL('users').one().where('id', $.id).callback($.callback, 'error-users-404');\n```\n\n### $.user\n\nType: `property`\n\nPrihlásený používateľ požiadavky, alebo `null`.\n\nReturns: `Object`\n\nAkcie s `user`, `sa` alebo `permissions` ho kontrolujú pred spustením. `$.session` obsahuje reláciu.\n\nExample: Uloženie autora\n```js\nmodel.userid = $.user.id;\n```\n\n### $.keys\n\nType: `property`\n\nV požiadavke `PATCH` názvy polí, ktoré boli odoslané; inak `null`.\n\nReturns: `Array`\n\nSkonvertujú a zvalidujú sa len tieto polia.\n\nExample: Patch len odoslaných polí\n```js\nschema.setPatch(function($, model) {\n\tconsole.log($.keys); // ['name']\n\tNOSQL('users').modify(model).where('id', $.id);\n\t$.success();\n});\n```\n\n### $.filter\n\nType: `property`\n\nQuery string skonvertovaný pomocou `filter` operácie.\n\nReturns: `Object`\n\nFilter je druhý argument `schema.setQuery()` a ostatných metód set. Bez filtra je to query tak, ako prišlo.\n\nExample: Typované query\n```js\nschema.setQuery(function($) {\n\tconsole.log($.filter.page); // a number\n\t$.callback([]);\n}, 'page:Number, limit:Number');\n```\n\n### $.controller\n\nType: `property`\n\nKontrolér požiadavky, alebo nič, keď operácia beží z kódu.\n\nReturns: `Controller`\n\n`$` číta niektoré vlastnosti kontroléra aj priamo: `$.req`, `$.res`, `$.headers`, `$.ip`, `$.ua`, `$.language`, `$.files`, `$.body`, `$.url`, `$.path`, `$.mobile` a `$.sessionid`.\n\nExample: Čítanie požiadavky\n```js\nconsole.log($.ip, $.language, $.headers['user-agent']);\n```\n\n### $.responses\n\nType: `property`\n\nOdpovede predchádzajúcich operácií, keď trasa alebo `CALL()` spúšťa viac operácií.\n\nReturns: `Object`\n\n`$.response(name)` vráti jednu z nich.\n\nExample: Použitie výsledku predchádzajúcej operácie\n```js\n// ROUTE('POST /api/orders/ *Orders --> check insert');\nschema.setInsert(function($, model) {\n\tvar check = $.response('check');\n\t// ...\n});\n```\n\n### NEWACTION(name, options)\n\nType: `method` · Since: `0.0.81`\n\nDeklaruje akciu, ktorá nepatrí schéme.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov akcie, napríklad `Users/create`. Dá sa vynechať, keď `options` obsahuje `id` alebo `name`. |\n| `options` | `Object` | yes |  | Možnosti akcie. |\n\nReturns: `Object` Akcia s metódou `remove()`.\n\nPrijíma rovnaké možnosti ako `schema.action()` (`action`, `name`, `input`, `output`, `query`, `params`, `user`, `sa`, `permissions`, `cache`, `publish`) a navyše:\n\n| Možnosť | Čo robí |\n| --- | --- |\n| `route` | `'API /api/'` deklaruje API trasu pre akciu. Názov API je názov akcie malými písmenami s `_` namiesto `/`, s `+`, keď má akcia `input`, a inak s `-` |\n| `csrf`, `encrypt`, `compress` | Ako `schema.csrf()`, `schema.encrypt()` a `schema.compress()` |\n\nAkcia beží s `$` ako `this`. Deklarácia akcie s existujúcim názvom ju nahradí a `action.remove()` ju odstráni aj s jej trasou. Trasa volá akciu pomocou `-->` bez schémy.\n\nExample: Akcia a jej trasa\n```js\nNEWACTION('Users/create', {\n\tname: 'Create a user',\n\tinput: '*name:String(50), *email:Email',\n\tuser: true,\n\taction: function($, model) {\n\t\tmodel.id = UID();\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t}\n});\n\nROUTE('POST /api/users/ --> Users/create');\n```\n\nExample: Akcia s vlastnou API trasou\n```js\nNEWACTION('Users/list', {\n\tquery: 'page:Number',\n\troute: 'API /api/',\n\taction: function($) {\n\t\tNOSQL('users').find().callback($.callback);\n\t}\n});\n\n// the client calls POST /api/ with { \"schema\": \"users_list\" }\n```\n\n### CALL(name, [model], [controller])\n\nType: `method` · Since: `0.0.67`\n\nSpúšťa akcie alebo operácie schém z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov akcie alebo `Schema --> operations`, voliteľne s prefixom `+`, `-` alebo `#`. |\n| `model` | `Object` | no |  | Dáta pre operáciu. Validujú sa. |\n| `controller` | `Controller|SchemaOptions` | no |  | Požiadavka, s ktorou sa má spustiť, alebo `$`. |\n\nReturns: `SchemaCall` Objekt s metódami z tabuľky.\n\n`name` je akcia (`Users/create`), viac akcií oddelených medzerami alebo `Schema --> operations`. Prefix `+`, `-` alebo `#` nastaví metódu (POST, GET alebo PATCH); bez neho je volanie POST, keď existuje model. Volanie začne v nasledujúcom ticku, takže najprv nastav jeho možnosti:\n\n| Metóda | Čo nastavuje |\n| --- | --- |\n| `.query(obj)`, `.params(obj)` | `$.query` a `$.params` |\n| `.user(obj)`, `.language(str)` | `$.user` (alebo používateľa z `$`) a jazyk |\n| `.controller(ctrl)` | Kontrolér (alebo kontrolér z `$`) |\n| `.callback(fn)` | `function(err, response)` |\n| `.done($, fn)` | Pri chybe ukončí `$`, inak spustí `fn(response)` |\n| `.promise([$])` | Vráti promise; s `$` chyba ukončí danú operáciu |\n| `.debug()` | Vypíše vstup a výsledok do konzoly |\n\nPri viacerých operáciách je odpoveď objekt s výsledkom každej z nich.\n\nExample: Spustenie akcie\n```js\nCALL('Users/create', { name: 'Peter', email: 'peter@example.com' }).user(user).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Čakanie na operáciu schémy\n```js\nvar users = await CALL('-Users --> list').query({ page: 1 }).promise();\n```\n\n### EXEC(name, [model], [callback], [controller])\n\nType: `method`\n\nSpúšťa operácie schém z kódu. `$ACTION()` je alias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | `Schema --> operations` s prefixom metódy. |\n| `model` | `Object` | no |  | Dáta pre operáciu. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Požiadavka alebo objekt s `query`, `params`, `user`, `id`… |\n\nReturns: `Promise` Promise, keď nie je zadaný callback.\n\n`name` je `+Schema --> operations` (alebo `-`, `#` či metóda ako `POST Schema --> insert`). Namiesto kontroléra môžeš odovzdať objekt s `query`, `params`, `user`, `session`, `body`, `headers` a `id`. Bez callbacku vráti promise. Pre akcie deklarované pomocou `NEWACTION()` použi `CALL()`.\n\nExample: Vloženie z kódu\n```js\nEXEC('+Users --> insert', { name: 'Peter', email: 'peter@example.com' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: S query a používateľom\n```js\nvar list = await EXEC('-Users --> query', null, { query: { page: 1 }, user: user });\n```\n\n### MAKE(schema, model, [callback], [novalidate], [controller])\n\nType: `method` · Since: `0.0.63`\n\nSkonvertuje a zvaliduje model schémou bez spustenia akejkoľvek operácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Názov schémy. |\n| `model` | `Object` | yes |  | Dáta na validáciu. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n| `novalidate` | `Boolean` | no | `false` | `true` dáta len skonvertuje. |\n| `controller` | `Controller` | no |  | Kontrolér, ktorý namiesto promise dostane chybu. |\n\nReturns: `Promise` Validovaný model, keď nie je zadaný callback.\n\nBez callbacku vráti promise.\n\nExample: Validácia dát\n```js\n// Users: name is required\nMAKE('Users', { name: '' }, function(err, model) {\n\tconsole.log(err); // an ErrorBuilder with the invalid name\n});\n\nvar model = await MAKE('Users', { name: 'Peter' });\n```\n\n### $OPERATION(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nSpustí z kódu operáciu schémy pridanú pomocou `schema.addOperation()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Názov schémy. |\n| `name` | `String` | yes |  | Názov zadaný v `schema.addOperation()`. |\n| `options` | `Object` | no |  | Vlastné možnosti, dostupné ako `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Kontrolér alebo objekt `$`. |\n\nReturns: `Boolean` `true`, keď schéma existuje.\n\n`schema.addOperation(name, operation, [filter])` prepojí názov v schéme s globálnou operáciou deklarovanou pomocou `NEWOPERATION()`. `$OPERATION()` ju spustí: schéma zavolá `OPERATION(operation, $.model, $.callback, schemaName, $)`, takže operácia odpovedá cez schému a zdieľa jej kontrolér.\n\nModel sa nepripravuje ani nevaliduje: `$.model` je prázdny objekt a možnosti prichádzajú ako `$.options`. Middleware schémy sa aj tak spustí. Keď je `options` funkcia, je to callback. Chýbajúca schéma zavolá callback s chybou `Schema \"name\" not found.`; schéma bez danej operácie odpovie `Schema \"name\" doesn't contain \"Operation.name\" operation.`\n\nNezamieňaj si ju s `OPERATION()`, ktorá spúšťa globálnu operáciu priamo.\n\nExample: Prepojenie a spustenie operácie\n```js\nNEWOPERATION('newsletter', function($) {\n\t// $.controller is the controller passed to $OPERATION()\n\t$.success();\n});\n\nNEWSCHEMA('Users', function(schema) {\n\tschema.addOperation('subscribe', 'newsletter');\n});\n\n$OPERATION('Users', 'subscribe', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### $TASK(schema, name, [options], [callback], [controller])\n\nType: `method`\n\nSpustí z kódu úlohu schémy pridanú pomocou `schema.addTask()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Názov schémy. |\n| `name` | `String` | yes |  | Názov zadaný v `schema.addTask()`. |\n| `options` | `Object` | no |  | Vlastné možnosti, dostupné ako `$.options`. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `controller` | `Controller|Object` | no |  | Kontrolér alebo objekt `$`. |\n\nReturns: `Boolean` `true`, keď schéma existuje.\n\n`schema.addTask(name, task, [filter], [callback])` prepojí názov v schéme s krokom úlohy deklarovanej pomocou `NEWTASK()` (`task` je `'name/step'`). `$TASK()` ju spustí: schéma spustí `TASK(task, $.callback, $)` s `$.model` ako hodnotou úlohy. S `callback` z `addTask()` schéma namiesto toho zavolá `callback($, err, response)` a odpovieš sám.\n\nModel sa nepripravuje ani nevaliduje: `$.model` je prázdny objekt a možnosti prichádzajú ako `$.options`. Keď je `options` funkcia, je to callback. Chýbajúca schéma zavolá callback s chybou `Schema \"name\" not found.`\n\nExample: Prepojenie a spustenie úlohy\n```js\nNEWTASK('Import', function(push) {\n\tpush('run', function($, value) {\n\t\t$.success();\n\t});\n});\n\nNEWSCHEMA('Products', function(schema) {\n\tschema.addTask('import', 'Import/run');\n});\n\n$TASK('Products', 'import', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### FAKE(schema, [onlyrequired])\n\nType: `method`\n\nVráti objekt s náhodnými dátami, ktoré zodpovedajú schéme, na testy a ukážky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Názov schémy, deklarácia na mieste alebo objekt typov. |\n| `onlyrequired` | `Boolean` | no | `false` | Vyplní len povinné polia. |\n\nReturns: `Object` Falošný model.\n\n`schema` je názov schémy, deklarácia na mieste ako `'name:String, email:Email'` alebo objekt ako `{ id: UID, name: 'String(30)' }`. Každé pole dostane náhodnú hodnotu svojho typu: e-maily, telefóny, PSČ, URL, identifikátory (`UID`, `GUID`), čísla, dátumy, booleany a reťazce (skrátené na deklarovanú dĺžku, najviac 30 znakov). Polia dostanú dve položky, enumy a zoznamy kľúč-hodnota jednu zo svojich hodnôt a polia inej schémy vnorený falošný objekt.\n\nNiektoré názvy polí dávajú realistické hodnoty: `firstname`, `lastname`, `fullname`, `company`, `country`, `currency`, `language`, `age`, `birthdate`.\n\nS `onlyrequired` sa vyplnia len povinné polia pomenovanej schémy.\n\nExample: Zo schémy\n```js\nvar model = FAKE('Users');\n\n$INSERT('Users', model, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Na mieste\n```js\nvar user = FAKE({ id: UID, firstname: 'String(30)', email: 'Email', age: Number });\nvar item = FAKE('name:String, price:Number, tags:[String]');\n```\n\n### schema.setQueryExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `query`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `query`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `query` sa dá pridať viac rozšírení. Alias: `schema.setListExtension()`.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setQuery(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setQueryExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setReadExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `read`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `read`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `read` sa dá pridať viac rozšírení. Alias: `schema.setGetExtension()`.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRead(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setReadExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setInsertExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `insert`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `insert`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `insert` sa dá pridať viac rozšírení.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setInsert(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setInsertExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setUpdateExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `update`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `update`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `update` sa dá pridať viac rozšírení.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setUpdate(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setUpdateExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setPatchExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `patch`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `patch`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `patch` sa dá pridať viac rozšírení.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setPatch(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setPatchExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setRemoveExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `remove`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `remove`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `remove` sa dá pridať viac rozšírení.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setRemove(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setRemoveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.setSaveExtension(fn)\n\nType: `method`\n\nPridá rozšírenie k operácii `save`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `$` sú možnosti bežiacej operácie, `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcej operácii `save`, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tej istej operácii `save` sa dá pridať viac rozšírení.\n\nExample: Rozšírenie operácie z pluginu\n```js\n// schemas/users.js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('name', String, true);\n\tschema.setSave(function($, model) {\n\t\t$.extend(model, function() {\n\t\t\t$.success();\n\t\t});\n\t});\n});\n\n// plugins/audit/index.js\nGETSCHEMA('Users', function(err, schema) {\n\tschema.setSaveExtension(function($, data, next) {\n\t\t// data === the model passed to $.extend()\n\t\tnext();\n\t});\n});\n```\n\n### schema.addWorkflowExtension(name, fn)\n\nType: `method`\n\nPridá rozšírenie k workflowu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov workflowu. |\n| `fn` | `Function` | yes |  | `function($, data, next)`. `data` je hodnota odovzdaná do `$.extend()`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nRozšírenie je funkcia `function($, data, next)`, ktorú pridáš k existujúcemu workflowu, zvyčajne z iného súboru alebo pluginu. Rozšírenia sa nespúšťajú samy: operácia ich spustí, keď zavolá `$.extend(data, [callback])`, v poradí, v akom boli pridané. S callbackom musí každé rozšírenie zavolať `next()`; bez neho `next` nerobí nič. K tomu istému workflowu sa dá pridať viac rozšírení. Alias: `schema.addExtension()`.\n\nExample: Rozšírenie workflowu\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.addWorkflow('send', function($) {\n\t\t$.extend($.model);\n\t\t$.success();\n\t});\n\tschema.addWorkflowExtension('send', function($, data) {\n\t\t// runs synchronously, next() is not needed\n\t\tconsole.log('Order sent', data.id);\n\t});\n});\n```\n\n### $.extend([data], [callback])\n\nType: `method`\n\nSpustí rozšírenia aktuálnej operácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Hodnota odovzdaná každému rozšíreniu ako jeho druhý argument. |\n| `callback` | `Function` | no |  | Spustí sa po poslednom rozšírení. |\n\nReturns: `Boolean` `true`, keď rozšírenia existujú, inak `undefined`.\n\nSpustí rozšírenia pridané pomocou `schema.setSaveExtension()`, `schema.addWorkflowExtension()` a ostatných pre bežiacu operáciu. Bez `callback` sa všetky rozšírenia spustia naraz. S `callback` bežia jedno po druhom (každé zavolá `next()`) a `callback` sa spustí na konci, aj keď žiadne rozšírenia nie sú. Metóda vráti `true`, keď má operácia rozšírenia.\n\nExample: Čakanie na rozšírenia\n```js\nschema.setInsert(function($, model) {\n\tmodel.id = UID();\n\t$.extend(model, function() {\n\t\tNOSQL('users').insert(model);\n\t\t$.success(model.id);\n\t});\n});\n```\n\n### schema.csrf([enable])\n\nType: `method` · Since: `0.0.37`\n\nVyžaduje platný CSRF token pre každú trasu schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nTrasy schémy potom fungujú ako trasy s flagom `csrf`: token z `controller.csrf()` musí prísť v hlavičke `x-csrf-token` alebo v argumente `?csrf=`. Neplatný token odpovie chybou `Invalid CSRF token`.\n\nExample: Ochrana formulára\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.csrf();\n\tschema.define('email', 'Email', true);\n\tschema.setInsert(function($, model) {\n\t\t$.success();\n\t});\n});\n```\n\n### schema.encrypt([enable])\n\nType: `method`\n\nŠifruje odpovede trás schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nTextové odpovede sa šifrujú pomocou `CONF.secret_encryption` a dostanú hlavičku `X-Encryption: a`. Bez `secret_encryption` v konfigurácii sa nešifruje nič.\n\nExample: Šifrované odpovede\n```js\n// config: secret_encryption : my-secret-key\nNEWSCHEMA('Wallet', function(schema) {\n\tschema.encrypt();\n\tschema.setRead(function($) {\n\t\t$.callback({ balance: 100 });\n\t});\n});\n```\n\n### schema.compress([enable])\n\nType: `method`\n\nVynechá hodnoty `null` a `undefined` z JSON odpovedí schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nJSON odpoveď trás schémy sa serializuje bez kľúčov, ktorých hodnota je `null` alebo `undefined`, takže je menšia.\n\nExample: Menší JSON\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.compress();\n\tschema.setQuery(function($) {\n\t\t// { id: 1, note: null } is answered as { \"id\": 1 }\n\t\t$.callback([{ id: 1, note: null }]);\n\t});\n});\n```\n\n### schema.allow(field, [field2], [...])\n\nType: `method`\n\nSkopíruje polia, ktoré schéma nedefinuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String|Array` | yes |  | Názov, zoznam oddelený čiarkami alebo pole názvov. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nUvedené polia sa skopírujú zo vstupu do modelu tak, ako sú: bez konverzie a bez validácie. Funguje aj jeden reťazec s názvami oddelenými čiarkami.\n\nExample: Ľubovoľné metadáta\n```js\nNEWSCHEMA('Events', function(schema) {\n\tschema.define('name', String, true);\n\tschema.allow('meta, tags');\n});\n```\n\n### schema.verify(name, fn, [cache])\n\nType: `method`\n\nPridá asynchrónnu kontrolu jedného poľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `fn` | `Function` | yes |  | `function($)`. |\n| `cache` | `String` | no |  | Ako dlho sa výsledok drží, napríklad `'10 minutes'`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nKontrola sa spustí po validácii, len keď má pole hodnotu. `fn($)` dostane `$.value`, `$.model`, `$.name`, `$.user`, `$.query` a ďalšie hodnoty požiadavky. Zavolaj `$.next([value])` (alebo `$.success([value])`), ak chceš hodnotu prijať, voliteľne s novou hodnotou, alebo `$.invalid(error)`, ak ju chceš odmietnuť; odmietnuté pole sa nastaví na `null`. S `cache` (expirácia ako `'5 minutes'`) sa výsledok pre rovnakú hodnotu drží v cache.\n\nExample: Kontrola kódu krajiny\n```js\nNEWSCHEMA('Companies', function(schema) {\n\tschema.define('country', 'Upper(2)', true);\n\tschema.verify('country', function($) {\n\t\tNOSQL('countries').one().where('id', $.value).callback(function(err, item) {\n\t\t\tif (item)\n\t\t\t\t$.next();\n\t\t\telse\n\t\t\t\t$.invalid('error-country');\n\t\t});\n\t}, '10 minutes');\n});\n```\n\n### schema.clear()\n\nType: `method`\n\nOdstráni všetky polia schémy.\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nOdstráni definované polia, povinné polia, kontroly `schema.verify()` a polia `schema.allow()`. Operácie zostanú.\n\nExample: Opätovné definovanie polí\n```js\nGETSCHEMA('Products', function(err, schema) {\n\tschema.clear();\n\tschema.define('name', String, true);\n});\n```\n\n### schema.setPrimary(name)\n\nType: `method`\n\nPomenuje primárny kľúč schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nNázov sa uloží do `schema.primary` a `schema.inherit()` ho skopíruje. Framework ho v operáciách nepoužíva: je to informácia pre tvoj vlastný kód.\n\nExample: Primárny kľúč\n```js\nNEWSCHEMA('Users', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.setPrimary('id');\n});\n```\n\n### schema.setError(fn)\n\nType: `method`\n\nNastaví funkciu, ktorá sa spustí, keď operácia alebo validácia schémy skončí chybami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(error, model, type, [name])`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\n`fn(error, model, type, [name])` dostane `ErrorBuilder`, model, typ operácie (`'make'` pre validáciu, `'save'`, `'workflow'`, ...) a názov workflowu. Chyby môžeš prečítať alebo zmeniť predtým, ako sa odošlú v odpovedi.\n\nExample: Zalogovanie neplatného vstupu\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.setError(function(error, model, type) {\n\t\tconsole.log('Orders', type, error.items);\n\t});\n});\n```\n\n### schema.addTask(name, task, [filter], [callback])\n\nType: `method`\n\nPridá operáciu schémy, ktorá spustí úlohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie. |\n| `task` | `String` | yes |  | Úloha v tvare `'name/start'`. |\n| `filter` | `String` | no |  | Polia query stringu. |\n| `callback` | `Function` | no |  | `function($, err, response)`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nVolanie operácie (napríklad `CALL('Schema --> name')` alebo `*Schema --> name` v trase) spustí `TASK(task)` s modelom ako hodnotou. Odpoveď úlohy je odpoveďou operácie. S `callback($, err, response)` odpovieš sám.\n\nExample: Operácia schémy, ktorá spustí úlohu\n```js\nNEWTASK('Import', function(push) {\n\tpush('start', function($, value) {\n\t\t$.end(value.url);\n\t});\n});\n\nNEWSCHEMA('Feeds', function(schema) {\n\tschema.define('url', 'URL', true);\n\tschema.addTask('import', 'Import/start');\n});\n\n// ROUTE('POST /api/feeds/import/ *Feeds --> import');\n```\n\n### schema.addOperation(name, operation, [filter])\n\nType: `method`\n\nPridá operáciu schémy, ktorá spustí operáciu z `NEWOPERATION()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie v schéme. |\n| `operation` | `String` | yes |  | Názov operácie z `NEWOPERATION()`. |\n| `filter` | `String` | no |  | Polia query stringu. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nVolanie operácie schémy (napríklad `*Schema --> name` v trase) spustí `OPERATION(operation)` s modelom ako hodnotou a jej odpoveď je odpoveďou operácie schémy.\n\nExample: Opätovné použitie operácie\n```js\nNEWOPERATION('sendmail', function($) {\n\tMAIL($.value.email, 'Hello', 'mails/hello', $.value, $.done());\n});\n\nNEWSCHEMA('Newsletter', function(schema) {\n\tschema.define('email', 'Email', true);\n\tschema.addOperation('send', 'sendmail');\n});\n\n// ROUTE('POST /api/newsletter/ *Newsletter --> send');\n```\n\n### schema.cl(name, [value])\n\nType: `method`\n\nPrečíta alebo nahradí zoznam hodnôt poľa typu enum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `Array|Object` | no |  | Nový zoznam hodnôt. |\n\nReturns: `Array|Object` Aktuálny zoznam, alebo `undefined` pre iné polia.\n\nFunguje pre polia definované poľom (enum) alebo objektom (kľúč-hodnota). S `value` sa zoznam nahradí.\n\nExample: Hodnoty načítané neskôr\n```js\nNEWSCHEMA('Tickets', function(schema) {\n\tschema.define('status', ['open', 'closed']);\n});\n\nON('ready', function() {\n\tGETSCHEMA('Tickets').cl('status', ['open', 'pending', 'closed']);\n});\n```\n\n### schema.props()\n\nType: `method`\n\nOpíše polia schémy.\n\nReturns: `Object` Opis polí.\n\nVráti objekt s jedným kľúčom pre každé pole a jeho `type` (`number`, `string`, `uid`, `email`, `boolean`, `date`, ...) a `required` a `length`, keď sú nastavené. Hodí sa na opis schémy pre klienta.\n\nExample: Odoslanie polí klientovi\n```js\nfunction fields() {\n\tthis.json(GETSCHEMA('Users').props());\n}\n```\n\n### schema.make(model, [callback])\n\nType: `method`\n\nPripraví a zvaliduje model z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Vstup. |\n| `callback` | `Function` | no |  | `function(err, model)`. |\n\nReturns: `Object` Pripravený model (pred asynchrónnymi kontrolami).\n\nSkonvertuje vstup podľa polí schémy, zvaliduje ho a spustí kontroly `schema.verify()`. `callback(err, model)` dostane `ErrorBuilder` alebo pripravený model. Alias: `schema.load()`.\n\nExample: Validácia hodnoty\n```js\nGETSCHEMA('Users').make({ name: 'Peter', email: 'peter@example.com' }, function(err, model) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(model);\n});\n```\n\n### schema.validate(model)\n\nType: `method`\n\nZvaliduje model bez jeho konverzie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Model. |\n\nReturns: `ErrorBuilder` Chyby; `.is` je `true`, keď nejaké sú.\n\nSkontroluje povinné polia a validáciu každého poľa. Nespúšťa kontroly `schema.verify()`.\n\nExample: Kontrola modelu\n```js\nvar errors = GETSCHEMA('Users').validate({ name: '' });\nif (errors.is)\n\tconsole.log(errors.items);\n```\n\n### schema.default()\n\nType: `method`\n\nVytvorí model s predvolenými hodnotami polí.\n\nReturns: `Object` Nový model.\n\nKaždé pole dostane svoju predvolenú hodnotu: `0` pre čísla, `''` pre reťazce, `false` pre booleany, `NOW` pre dátumy, `[]` pre polia a predvolený model pre pole inej schémy. Alias: `schema.create()`.\n\nExample: Prázdny formulár\n```js\nfunction create() {\n\tthis.view('form', GETSCHEMA('Products').default());\n}\n```\n\n### schema.destroy()\n\nType: `method`\n\nOdstráni schému.\n\nReturns: `undefined` Nič.\n\nSchéma sa odstráni zo zoznamu schém a spustí sa jej funkcia zo `schema.setDestroy()`.\n\nExample: Odstránenie schémy\n```js\nGETSCHEMA('Temporary').destroy();\n```\n\n### schema.workflow(name, model, [options], callback, [controller])\n\nType: `method`\n\nSpustí workflow schémy z kódu s modelom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov workflowu. |\n| `model` | `Object` | yes |  | Vstup. |\n| `options` | `Object` | no |  | Hodnota dostupná ako `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Kontrolér alebo `$`, z ktorého sa vezme používateľ a požiadavka. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\nModel sa najprv pripraví a zvaliduje, ako v trase. `schema.workflow2(name, [options], callback, [controller])` ho spustí bez modelu a bez validácie. Pre väčšinu kódu sú jednoduchšie `CALL()` a `EXEC()`.\n\nExample: Spustenie workflowu\n```js\nGETSCHEMA('Orders').workflow('check', { id: '123' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### schema.query([options], callback, [controller])\n\nType: `method`\n\nSpustí operáciu `query` z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Hodnota dostupná ako `$.options`. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n| `controller` | `Controller` | no |  | Kontrolér alebo `$`. |\n\nReturns: `SchemaBuilderEntity` Schéma, na reťazenie.\n\n`schema.read()` (alias `schema.get()`) a `schema.remove()` fungujú rovnako pre operácie `read` a `remove`. Tieto bežia bez modelu.\n\nExample: Zoznam z kódu\n```js\nGETSCHEMA('Products').query(function(err, items) {\n\tconsole.log(items);\n});\n```\n","entries":[{"type":"method","name":"NEWSCHEMA()","signature":"NEWSCHEMA(name, [declaration])","since":"","deprecated":false},{"type":"method","name":"GETSCHEMA()","signature":"GETSCHEMA(name, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"schema.define()","signature":"schema.define(name, type, [required], [error], [xss])","since":"","deprecated":false},{"type":"method","name":"schema.required()","signature":"schema.required(name, [fn])","since":"","deprecated":false},{"type":"method","name":"schema.undefine()","signature":"schema.undefine(name)","since":"0.0.46","deprecated":false},{"type":"method","name":"schema.inherit()","signature":"schema.inherit(name)","since":"","deprecated":false},{"type":"method","name":"schema.array()","signature":"schema.array()","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.action()","signature":"schema.action(name, options)","since":"0.0.67","deprecated":false},{"type":"method","name":"schema.setSave()","signature":"schema.setSave(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setInsert()","signature":"schema.setInsert(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setUpdate()","signature":"schema.setUpdate(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setPatch()","signature":"schema.setPatch(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRead()","signature":"schema.setRead(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setQuery()","signature":"schema.setQuery(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.setRemove()","signature":"schema.setRemove(fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflow()","signature":"schema.addWorkflow(name, fn, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.middleware()","signature":"schema.middleware(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setTimer()","signature":"schema.setTimer(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"schema.setDestroy()","signature":"schema.setDestroy(fn)","since":"0.0.63","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(name, [message])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([value])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(fn)","since":"","deprecated":false},{"type":"method","name":"$.promisify()","signature":"$.promisify(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.action()","signature":"$.action(name, [model])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, fn)","since":"0.0.63","deprecated":false},{"type":"property","name":"$.model","signature":"$.model","since":"","deprecated":false},{"type":"property","name":"$.query","signature":"$.query","since":"","deprecated":false},{"type":"property","name":"$.params","signature":"$.params","since":"","deprecated":false},{"type":"property","name":"$.id","signature":"$.id","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.keys","signature":"$.keys","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.responses","signature":"$.responses","since":"","deprecated":false},{"type":"method","name":"NEWACTION()","signature":"NEWACTION(name, options)","since":"0.0.81","deprecated":false},{"type":"method","name":"CALL()","signature":"CALL(name, [model], [controller])","since":"0.0.67","deprecated":false},{"type":"method","name":"EXEC()","signature":"EXEC(name, [model], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"MAKE()","signature":"MAKE(schema, model, [callback], [novalidate], [controller])","since":"0.0.63","deprecated":false},{"type":"method","name":"$OPERATION()","signature":"$OPERATION(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"$TASK()","signature":"$TASK(schema, name, [options], [callback], [controller])","since":"","deprecated":false},{"type":"method","name":"FAKE()","signature":"FAKE(schema, [onlyrequired])","since":"","deprecated":false},{"type":"method","name":"schema.setQueryExtension()","signature":"schema.setQueryExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setReadExtension()","signature":"schema.setReadExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setInsertExtension()","signature":"schema.setInsertExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setUpdateExtension()","signature":"schema.setUpdateExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setPatchExtension()","signature":"schema.setPatchExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setRemoveExtension()","signature":"schema.setRemoveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.setSaveExtension()","signature":"schema.setSaveExtension(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addWorkflowExtension()","signature":"schema.addWorkflowExtension(name, fn)","since":"","deprecated":false},{"type":"method","name":"$.extend()","signature":"$.extend([data], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.csrf()","signature":"schema.csrf([enable])","since":"0.0.37","deprecated":false},{"type":"method","name":"schema.encrypt()","signature":"schema.encrypt([enable])","since":"","deprecated":false},{"type":"method","name":"schema.compress()","signature":"schema.compress([enable])","since":"","deprecated":false},{"type":"method","name":"schema.allow()","signature":"schema.allow(field, [field2], [...])","since":"","deprecated":false},{"type":"method","name":"schema.verify()","signature":"schema.verify(name, fn, [cache])","since":"","deprecated":false},{"type":"method","name":"schema.clear()","signature":"schema.clear()","since":"","deprecated":false},{"type":"method","name":"schema.setPrimary()","signature":"schema.setPrimary(name)","since":"","deprecated":false},{"type":"method","name":"schema.setError()","signature":"schema.setError(fn)","since":"","deprecated":false},{"type":"method","name":"schema.addTask()","signature":"schema.addTask(name, task, [filter], [callback])","since":"","deprecated":false},{"type":"method","name":"schema.addOperation()","signature":"schema.addOperation(name, operation, [filter])","since":"","deprecated":false},{"type":"method","name":"schema.cl()","signature":"schema.cl(name, [value])","since":"","deprecated":false},{"type":"method","name":"schema.props()","signature":"schema.props()","since":"","deprecated":false},{"type":"method","name":"schema.make()","signature":"schema.make(model, [callback])","since":"","deprecated":false},{"type":"method","name":"schema.validate()","signature":"schema.validate(model)","since":"","deprecated":false},{"type":"method","name":"schema.default()","signature":"schema.default()","since":"","deprecated":false},{"type":"method","name":"schema.destroy()","signature":"schema.destroy()","since":"","deprecated":false},{"type":"method","name":"schema.workflow()","signature":"schema.workflow(name, model, [options], callback, [controller])","since":"","deprecated":false},{"type":"method","name":"schema.query()","signature":"schema.query([options], callback, [controller])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabUBm4XU60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Views","summary":"Every command of the view engine and the controller methods that render views.","markdown":"---\ntitle: Views\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Views\n\n> Every command of the view engine and the controller methods that render views.\n\nViews are `.html` files in `views/` with commands in `@{...}` and translated text in `@(...)`. The guide [Views](../../guides/views/) explains how they work together; this page lists each command and the controller methods for views.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nPrints the value of a JavaScript expression, HTML-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | A JavaScript expression. |\n\nReturns: `String` The encoded value.\n\nAny expression works: a property of the model, a method call, arithmetic. `null` and `undefined` print an empty string. The characters `<`, `>`, `&`, `\"` and `'` are encoded. To print the value without encoding, use `@{!expression}`.\n\nText that starts with `@{{` is not a command and stays in the page as written.\n\nExample: Values of the model\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nPrints the value of an expression without HTML encoding.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | A JavaScript expression. |\n\nReturns: `String` The raw value.\n\nUse it for HTML that you trust, for example content you have already sanitized. Never use it for text typed by users.\n\nExample: Raw HTML\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nThe model passed to the view by `controller.view(name, model)`.\n\n`M` is a shorter name for the same object. The layout gets the same model as the view. A command that assigns a value, like `@{model.count = 0}`, prints nothing.\n\nExample: Controller and view\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: In the view\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nAn object shared by the view, its partial views and the layout during one request.\n\nIt is `controller.repository` in JavaScript. `R` is a shorter name. Values set in the view are visible in the layout, because the view is rendered first.\n\nExample: Set in the view, read in the layout\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nValues of the current request that every view can use.\n\n| Variable | Value |\n| --- | --- |\n| `user` | The signed-in user (`controller.user`) |\n| `session` | The session (`controller.session`) |\n| `query` | The query string as an object |\n| `body` | The request body; `@{body}` alone is the rendered view, in a layout |\n| `config`, `CONF` | The configuration |\n| `language` | The language of the request |\n| `url` | The path of the request |\n| `files` | Uploaded files |\n| `mobile` | `true` for a mobile device |\n| `controller` | The controller |\n\nThey are encoded like any expression; put `!` in front for the raw value.\n\nExample: Request values\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nPrints a value of the configuration, HTML-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | A key of the configuration. |\n\nThe value is read when the view is compiled. `@{config.key}` and `@{CONF.key}` print the same value. A quoted path without `%`, like `@{'/css/default.css'}`, prints the URL of that static file.\n\nExample: App name\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRenders a part of the view only when a condition is true.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | A JavaScript expression. |\n\nThe condition is JavaScript. `@{else if}` and `@{else}` are optional. Close the block with `@{fi}` or `@{endif}`.\n\nExample: Condition\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRenders a part of the view for each item of an array or object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | The name of the variable for the current item. |\n| `source` | `Array|Object` | yes |  | The expression to loop over. |\n\n`index` is the position of the current item, from `0`. An empty source prints nothing. When the source is an object, it becomes an array of `{ key, value }`. `@{foreach var item in source}` also works. `@{continue}` and `@{break}` skip an item or stop the loop.\n\nExample: Array\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Object\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Skip items\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nPrints the rendered view inside the layout.\n\nUse it in the layout. With a property, `@{body.name}` reads the request body instead.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nChanges the layout of the current view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the layout, or `''` for no layout. |\n\nReturns: `String` An empty string.\n\nThe default layout is `layout` (`default_layout` in the config). An empty string renders the view without a layout. Layouts are always looked up from the root of `views/`.\n\nExample: Another layout\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: No layout\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nRenders a partial view in place, without a layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the view. |\n| `model` | `Object` | no |  | The model of the partial view. |\n| `expire` | `String` | no |  | How long to cache the output, e.g. `'5 minutes'`. |\n| `key` | `String` | no |  | A key that makes the cache entry unique, e.g. the language. |\n\nReturns: `String` The rendered HTML.\n\nThe name is resolved like in `controller.view()`. The partial does not get the model of the parent automatically; pass it. With `expire` the output is cached for that time under the name and the `key`.\n\nExample: Partial per item\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Cached menu\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nCompiles an HTML string as a view and renders it in place.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The template, with the same syntax as a view. |\n| `model` | `Object` | no |  | The model. |\n| `key` | `String` | no |  | A cache key for the compiled template. |\n\nReturns: `String` The rendered HTML.\n\nUseful for templates stored in a database. The result has no layout. With `key`, the compiled template is kept in memory in release mode.\n\nExample: Template from the model\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nWrites HTML in the view and prints it somewhere else, usually in the layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the section. |\n\n`@{section name}` … `@{end}` stores its content and prints nothing; blocks with the same name are joined. `@{section('name')}` prints the stored content, or nothing. The content is kept in the repository, so print it after the view is rendered: in the layout.\n\nExample: Scripts of one page\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: In the layout\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDefines a helper inside the view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the helper. |\n| `arguments` | `String` | yes |  | Names of the arguments, as in a JavaScript function. |\n\nThe helper exists only in this view. Call it by its name; its output is not encoded again. For helpers shared by all views use `DEF.helpers`.\n\nExample: Inline helper\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDefines view helpers available in all views.\n\nAdd the functions before the views are compiled, for example in `definitions/`. In a view, call the helper by its name: `@{name(arguments)}`; `@{helpers.name(arguments)}` and `@{helper('name', arguments)}` work too. Inside the function `this` is the controller. The returned value is printed without encoding.\n\nExample: Define\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Use\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nMarks text for translation; it is replaced when the view is compiled.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | The text in the default language, or `#key`. |\n\nThe text is translated with the language of the controller (`controller.language`, which comes from `DEF.onLocale`). The translation is read from the resource file of the language under a key made from the hash of the text; when there is none, the original text stays. `@(#key)` reads `key` from the resource directly. Inside quotes, quotes in the translation are escaped. Each language gets its own compiled view.\n\nExample: Translated text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nPrints a value from a resource file, HTML-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | The resource file without extension. |\n| `key` | `String` | yes |  | The key. |\n\nReturns: `String` The value, or an empty string.\n\nWithout `name` the value comes from `default.resource`. When a key is missing in another file, the value from `default.resource` is used. `@{!resource(...)}` prints it raw.\n\nExample: Resource values\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nWrites the HTML tags for static files and for the head of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | A file name or one of the keywords. As many as you need. |\n\nReturns: `String` HTML tags.\n\nEach argument is one of:\n\n| Argument | Output |\n| --- | --- |\n| `'meta'` | Title and meta tags, see `@{meta}` |\n| `'head'` | The author meta tag and the tags added with `@{head()}` |\n| `'file.css'` | `<link rel=\"stylesheet\">` from `/css/` |\n| `'file.js'` | `<script>` from `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | The icon link |\n| an image or video | Its URL |\n| `'a.css + b.css'` | One merged file with all of them |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | The live reload script, in debug mode only |\n\nA name that starts with `/` or a full URL is used as it is. `!` in front of a file prints only its URL. The output is cached per file.\n\nExample: Head of a layout\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: Merged files\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nWrite `<link rel=\"stylesheet\">` tags for CSS files, or `<script>` tags for JavaScript files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | A file. As many as you need. |\n\nReturns: `String` HTML tags.\n\nRelative names are taken from `/css/` (`static_url_style`) and `/js/` (`static_url_script`). In `@{js()}`, start a name with `async ` to add the `async` attribute.\n\nExample: Styles and scripts\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nPrints the URL of a static file in its folder, without a tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name. |\n\nReturns: `String` The URL.\n\nEach command uses its folder from the config: `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/`, and `public` the root. A name that starts with `/` is used from the root. The URL respects the theme and `default_root`.\n\nExample: URLs\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nPrints the title and meta tags of the page, or sets them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | The title. |\n| `description` | `String` | no |  | The description. |\n| `keywords` | `String|Array` | no |  | Keywords. |\n| `image` | `String` | no |  | An image for social networks, an absolute URL or a file in `/img/`. |\n\nReturns: `String` HTML tags, or an empty string when setting.\n\nWithout arguments it prints `<title>`, the description and keywords meta tags, and `og:image` and `twitter:image` when an image is set. With arguments it sets the values and prints nothing. The title gets ` - ` and `CONF.name` at the end unless `allow_custom_titles` is `true`. To change the output, replace `DEF.onMeta`.\n\nExample: Set in the view, print in the layout\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nPrints or sets the title of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | The title. |\n\nReturns: `String` The title, or an empty string when setting.\n\n`@{title(value)}` sets the title and prints nothing; `@{title2(value)}` appends to the current title. `@{title}` prints the title alone. The value is HTML-encoded when it is set, so `@{!title}` prints it without encoding it twice. To print the whole `<title>` tag, use `@{meta}`.\n\nExample: Title\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nSets the description, keywords or author of the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | The value. |\n\nReturns: `String` The value, or an empty string when setting.\n\nWith an argument they set the value and print nothing. `@{description}`, `@{keywords}` and `@{author}` print the value. `@{meta}` prints the description and keywords; `@{import('head')}` prints the author (or `CONF.author`). Keywords can be an array.\n\nExample: Meta values\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nAdds CSS, JavaScript or HTML to the head of the page, or prints it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | A file name, a URL or HTML. |\n\nReturns: `String` HTML, or an empty string when adding.\n\nWith arguments it adds tags and prints nothing: `.css` files become `<link>`, `.js` files `<script>`, and a value that starts with `<` is added as HTML. Each value is added once. `@{head}` (or `@{import('head')}`) prints the author meta tag and everything added.\n\nExample: Add from a view\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Print in the layout\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nAdds content to a named place, or prints it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the place. |\n| `value` | `String` | no |  | A file path or HTML. |\n\nReturns: `String` The content, or an empty string when adding.\n\nWith values it appends them and prints nothing: `.js` and `.mjs` files become `<script>`, `.css` files `<link>`, anything else is added as it is. With the name only it prints the content. Values are not resolved to the static folders, so write full paths.\n\nExample: Place for scripts\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSerializes a value to JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | The value to serialize. |\n| `id` | `String` | no |  | The id of a `<script>` element. |\n| `beautify` | `Boolean` | no | `false` | Indents the JSON. |\n\nReturns: `String` JSON, or a `<script>` element.\n\nWith `id` the JSON is wrapped in `<script type=\"application/json\" id=\"...\">`, so client-side code can read it. The output is not HTML-encoded.\n\nExample: Data for the browser\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nWrites `<option>` elements for a `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | The options. |\n| `selected` | `Any` | no |  | The value of the selected option. |\n| `name` | `String` | no | `name` | The property with the text. |\n| `value` | `String` | no | `value` | The property with the value. |\n| `disabled` | `String` | no | `disabled` | The property that disables an option. |\n\nReturns: `String` HTML.\n\nFor an array of objects, `name` is the property of the text (default `name`) and `value` the property of the value (default: the same as `name` when you give a name, otherwise `value`). The property `disabled` disables an option. For an array of strings or numbers, each item is both text and value. For an object, keys are values and values are texts. The option equal to `selected` gets `selected=\"selected\"`. Texts and values are encoded.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Strings\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nPrints an HTML attribute when a condition is true.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | When truthy, the attribute is printed. |\n\nReturns: `String` The attribute or an empty string.\n\nThey print ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` or ` readonly=\"readonly\"`, with a space in front, or nothing.\n\nExample: Attributes\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nWrites an `<input>` for a field of the model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `attributes` | `Object` | no |  | Extra attributes, e.g. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` An `<input>` element.\n\nThe model of the view is added automatically: the value of the input is `model[name]`, encoded. The attributes are added to the element; `required`, `disabled`, `readonly` and `autofocus` are written as boolean attributes, and `autocomplete: true` writes `autocomplete=\"on\"` (any other truthy value writes `off`). `value` in the attributes is used when the model has no such field.\n\nExample: Form fields\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nWrites an `<input>` of any type for a field of the model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The type of the input. |\n| `name` | `String` | yes |  | The name of the field. |\n| `attributes` | `Object` | no |  | Extra attributes. |\n\nReturns: `String` An `<input>` element.\n\nWorks like `@{text()}` with the type you choose, for example `email`, `number` or `date`.\n\nExample: Email\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nWrites a checkbox or a radio button for a field of the model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `value` | `String` | yes |  | Radio only: the value of this button. |\n| `label` | `String|Object` | no |  | A label, or extra attributes (`label` is one of them). |\n\nReturns: `String` An `<input>`, wrapped in `<label>` when there is a label.\n\nA checkbox is checked when `model[name]` is `true`, `1`, `'true'` or `'on'`; its value is `1`. A radio button is checked when `model[name]` equals `value`. A string as the last argument is a label: the input is wrapped in `<label>` with the text in a `<span>`. `@{radio()}` needs this last argument, a label or an object.\n\nExample: Checkbox and radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nWrites a `<textarea>` with the value of a field of the model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the field. |\n| `attributes` | `Object` | no |  | Extra attributes, e.g. `{ rows: 5 }`. |\n\nReturns: `String` A `<textarea>` element.\n\nThe content is `model[name]`, or `value` from the attributes. The content is not encoded, so encode values typed by users first.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nWrites an `<img>` for a file in `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The image file. |\n| `width` | `Number|Object` | no |  | The width, or an object with all attributes. |\n| `height` | `Number` | no |  | The height. |\n| `alt` | `String` | no |  | The alternative text. |\n| `class` | `String` | no |  | CSS classes. |\n\nReturns: `String` An `<img>` element.\n\nInstead of the arguments you can pass an object: `{ width, height, alt, class, style }`. `alt` is encoded.\n\nExample: Image\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nPrints a CSRF token for the current request.\n\nReturns: `String` The token.\n\nA route with the `csrf` flag checks the token in the `X-CSRF-Token` header or in the `csrf` query parameter. It needs `secret_csrf` in the config. The token is made by `DEF.onCSRFcreate(req)` and checked by `DEF.onCSRFcheck(req)`.\n\nExample: Form and AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nPrints the current query string, optionally with one key changed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | The parameter to set. |\n| `value` | `Any` | no |  | Its new value. |\n\nReturns: `String` A query string.\n\nThe result starts with `?`, or is empty. Use it for paging and filters that keep the other parameters.\n\nExample: Paging\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nPrints the path of the current request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Adds the protocol and the host. |\n\nReturns: `String` The URL.\n\n`@{url(true)}` prints the full address with the protocol and the host.\n\nExample: Canonical link\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nPasses a rendered block of the view to `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A name that tells your function what to do. |\n\nThe function gets the name, the HTML of the block and the model, and returns the HTML to print. By default it returns the HTML unchanged; replace it to run another template language or a Markdown parser. The block is not minified.\n\nExample: A hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: In a view\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nTurns off the minification of a view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` or `all`. |\n\nBy default Total.js minifies the HTML of a view and its inline CSS and JavaScript. Put this command anywhere in the view to keep one part as written: `html`, `css` (or `style`), `js` (or `script`, `javascript`) or `all`. HTML comments are removed in any case, except conditional comments.\n\nExample: Keep the HTML as written\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenders a view with its layout and sends it as the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | The name of the view without `.html`. |\n| `model` | `Object` | no |  | The model of the view. |\n| `headers` | `Object` | no |  | Extra HTTP headers. |\n| `partial` | `Boolean` | no | `false` | `true` returns the HTML instead of sending it. |\n\nReturns: `Controller|String` The controller, or the HTML when `partial` is `true`.\n\nWithout `name` the view is named after the last part of the URL (`index` for `/`). The name is looked up in `views/<controller>/` first, then in `views/`; prefixes `~`, `=theme/`, `@`, `#plugin/` and `.` change that (see the guide). With `partial` set to `true`, the method returns the HTML instead of sending it; the layout is still applied unless you set `controller.layout('')`. When the view does not exist, the response is an error 500.\n\nExample: Render a view\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Get the HTML\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nCompiles an HTML string as a view, renders it and sends it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The template. |\n| `model` | `Object` | no |  | The model. |\n| `headers` | `Object` | no |  | Extra HTTP headers. |\n| `partial` | `Boolean` | no | `false` | `true` returns the HTML instead of sending it. |\n| `key` | `String` | no |  | A cache key for the compiled template. |\n\nReturns: `Controller|String` The controller, or the HTML when `partial` is `true`.\n\nThe string uses the same syntax as a view file. With `key` the compiled template is kept in memory in release mode.\n\nExample: Template from a database\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nSets the layout for the next view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the layout, or `''`. |\n\nReturns: `Controller` The controller.\n\nThe default is `default_layout` from the config (`layout`). An empty string renders without a layout. The view can change it again with `@{layout()}`.\n\nExample: Admin layout\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nSets the title and meta tags that `@{meta}` prints.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | The title. |\n| `description` | `String` | no |  | The description. |\n| `keywords` | `String|Array` | no |  | Keywords. |\n| `image` | `String` | no |  | An image for social networks. |\n\nReturns: `Controller` The controller.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` and `controller.author()` set one value each.\n\nExample: Meta tags\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nAdds content to a section of the view, or reads it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the section. |\n| `value` | `String` | no |  | HTML to add. |\n| `replace` | `Boolean` | no | `false` | Replaces the content instead of appending. |\n\nReturns: `Controller|String` The controller, or the content when reading.\n\nWithout `value` it returns the content. Otherwise it appends the value, or replaces the content when `replace` is `true`. Print the section with `@{section('name')}`.\n\nExample: Section from a controller\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nAn object shared by the view, its partial views and the layout.\n\nIn the view it is `repository` or `R`.\n\nExample: Pass a value to the layout\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRenders a view outside a request and returns the HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the view. |\n| `model` | `Object` | no |  | The model. |\n| `layout` | `String` | no | `''` | A layout. |\n| `repository` | `Object` | no |  | The repository. |\n| `language` | `String` | no |  | The language for `@(...)`. |\n\nReturns: `String` The HTML.\n\nThere is no layout unless you name one. Use it for emails, files or responses built by hand. A name like `=theme/view` reads the view from a theme.\n\nExample: Render to a string\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nCompiles an HTML string as a view, outside a request, and returns the HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | The template. |\n| `model` | `Object` | no |  | The model. |\n| `layout` | `String` | no | `''` | A layout. |\n| `repository` | `Object` | no |  | The repository. |\n| `language` | `String` | no |  | The language for `@(...)`. |\n\nReturns: `String` The HTML.\n\nIt is `VIEW()` for a template in a string, for example from a database. The string uses the same syntax as a view file. There is no layout unless you name one, and `layout` and `repository` can switch places. The template is compiled on every call.\n\nExample: Template from a string\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBm4XU60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Views","summary":"Alle Befehle der View-Engine und die Controller-Methoden, die Views rendern.","markdown":"---\ntitle: Views\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Views\n\n> Alle Befehle der View-Engine und die Controller-Methoden, die Views rendern.\n\nViews sind `.html`-Dateien in `views/` mit Befehlen in `@{...}` und übersetztem Text in `@(...)`. Die Anleitung [Views](../../guides/views/) erklärt, wie sie zusammenspielen; diese Seite listet jeden Befehl und die Controller-Methoden für Views auf.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nGibt den Wert eines JavaScript-Ausdrucks HTML-kodiert aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Ein JavaScript-Ausdruck. |\n\nReturns: `String` Der kodierte Wert.\n\nJeder Ausdruck funktioniert: eine Eigenschaft des Models, ein Methodenaufruf, Arithmetik. `null` und `undefined` geben einen leeren String aus. Die Zeichen `<`, `>`, `&`, `\"` und `'` werden kodiert. Um den Wert ohne Kodierung auszugeben, verwende `@{!expression}`.\n\nText, der mit `@{{` beginnt, ist kein Befehl und bleibt unverändert in der Seite.\n\nExample: Werte des Models\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nGibt den Wert eines Ausdrucks ohne HTML-Kodierung aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Ein JavaScript-Ausdruck. |\n\nReturns: `String` Der unveränderte Wert.\n\nVerwende es für HTML, dem du vertraust, zum Beispiel Inhalte, die du bereits bereinigt hast. Verwende es nie für Text, den Benutzer eingegeben haben.\n\nExample: Rohes HTML\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nDas Model, das `controller.view(name, model)` an die View übergibt.\n\n`M` ist ein kürzerer Name für dasselbe Objekt. Das Layout erhält dasselbe Model wie die View. Ein Befehl, der einen Wert zuweist, wie `@{model.count = 0}`, gibt nichts aus.\n\nExample: Controller und View\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: In der View\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nEin Objekt, das sich die View, ihre Partial Views und das Layout während eines Requests teilen.\n\nIn JavaScript ist es `controller.repository`. `R` ist ein kürzerer Name. In der View gesetzte Werte sind im Layout sichtbar, weil die View zuerst gerendert wird.\n\nExample: In der View setzen, im Layout lesen\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nWerte des aktuellen Requests, die jede View verwenden kann.\n\n| Variable | Wert |\n| --- | --- |\n| `user` | Der angemeldete Benutzer (`controller.user`) |\n| `session` | Die Session (`controller.session`) |\n| `query` | Der Query-String als Objekt |\n| `body` | Der Body des Requests; `@{body}` allein ist im Layout die gerenderte View |\n| `config`, `CONF` | Die Konfiguration |\n| `language` | Die Sprache des Requests |\n| `url` | Der Pfad des Requests |\n| `files` | Hochgeladene Dateien |\n| `mobile` | `true` für ein mobiles Gerät |\n| `controller` | Der Controller |\n\nSie werden wie jeder Ausdruck kodiert; setze `!` davor, um den unveränderten Wert zu erhalten.\n\nExample: Werte des Requests\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nGibt einen Wert der Konfiguration HTML-kodiert aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Ein Schlüssel der Konfiguration. |\n\nDer Wert wird gelesen, wenn die View kompiliert wird. `@{config.key}` und `@{CONF.key}` geben denselben Wert aus. Ein Pfad in Anführungszeichen ohne `%`, wie `@{'/css/default.css'}`, gibt die URL dieser statischen Datei aus.\n\nExample: Name der App\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRendert einen Teil der View nur, wenn eine Bedingung wahr ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Ein JavaScript-Ausdruck. |\n\nDie Bedingung ist JavaScript. `@{else if}` und `@{else}` sind optional. Schließe den Block mit `@{fi}` oder `@{endif}`.\n\nExample: Bedingung\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRendert einen Teil der View für jedes Element eines Arrays oder Objekts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | Der Name der Variablen für das aktuelle Element. |\n| `source` | `Array|Object` | yes |  | Der Ausdruck, über den iteriert wird. |\n\n`index` ist die Position des aktuellen Elements, ab `0`. Eine leere Quelle gibt nichts aus. Ist die Quelle ein Objekt, wird sie zu einem Array aus `{ key, value }`. `@{foreach var item in source}` funktioniert ebenfalls. `@{continue}` und `@{break}` überspringen ein Element oder beenden die Schleife.\n\nExample: Array\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Objekt\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Elemente überspringen\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nGibt die gerenderte View im Layout aus.\n\nVerwende es im Layout. Mit einer Eigenschaft liest `@{body.name}` stattdessen den Body des Requests.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nÄndert das Layout der aktuellen View.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Layouts oder `''` für kein Layout. |\n\nReturns: `String` Ein leerer String.\n\nDas Standard-Layout ist `layout` (`default_layout` in der Konfiguration). Ein leerer String rendert die View ohne Layout. Layouts werden immer ab dem Stammverzeichnis von `views/` gesucht.\n\nExample: Ein anderes Layout\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: Kein Layout\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nRendert eine Partial View an Ort und Stelle, ohne Layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | no |  | Das Model der Partial View. |\n| `expire` | `String` | no |  | Wie lange die Ausgabe gecacht wird, z. B. `'5 minutes'`. |\n| `key` | `String` | no |  | Ein Schlüssel, der den Cache-Eintrag eindeutig macht, z. B. die Sprache. |\n\nReturns: `String` Das gerenderte HTML.\n\nDer Name wird wie in `controller.view()` aufgelöst. Die Partial View erhält das Model der übergeordneten View nicht automatisch; übergib es. Mit `expire` wird die Ausgabe für diese Zeit unter dem Namen und dem `key` gecacht.\n\nExample: Partial View pro Element\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Gecachtes Menü\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nKompiliert einen HTML-String als View und rendert ihn an Ort und Stelle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das Template, mit derselben Syntax wie eine View. |\n| `model` | `Object` | no |  | Das Model. |\n| `key` | `String` | no |  | Ein Cache-Schlüssel für das kompilierte Template. |\n\nReturns: `String` Das gerenderte HTML.\n\nNützlich für Templates, die in einer Datenbank gespeichert sind. Das Ergebnis hat kein Layout. Mit `key` bleibt das kompilierte Template im Release-Modus im Speicher.\n\nExample: Template aus dem Model\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nSchreibt HTML in der View und gibt es an anderer Stelle aus, meist im Layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Section. |\n\n`@{section name}` … `@{end}` speichert seinen Inhalt und gibt nichts aus; Blöcke mit demselben Namen werden zusammengefügt. `@{section('name')}` gibt den gespeicherten Inhalt aus, oder nichts. Der Inhalt liegt im Repository, gib ihn also aus, nachdem die View gerendert wurde: im Layout.\n\nExample: Skripte einer Seite\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: Im Layout\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDefiniert einen Helper innerhalb der View.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Helpers. |\n| `arguments` | `String` | yes |  | Namen der Argumente, wie in einer JavaScript-Funktion. |\n\nDer Helper existiert nur in dieser View. Rufe ihn über seinen Namen auf; seine Ausgabe wird nicht erneut kodiert. Für Helper, die alle Views teilen, verwende `DEF.helpers`.\n\nExample: Inline-Helper\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDefiniert View-Helper, die in allen Views verfügbar sind.\n\nFüge die Funktionen hinzu, bevor die Views kompiliert werden, zum Beispiel in `definitions/`. Rufe den Helper in einer View über seinen Namen auf: `@{name(arguments)}`; `@{helpers.name(arguments)}` und `@{helper('name', arguments)}` funktionieren ebenfalls. In der Funktion ist `this` der Controller. Der Rückgabewert wird ohne Kodierung ausgegeben.\n\nExample: Definieren\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Verwenden\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nMarkiert Text zur Übersetzung; er wird beim Kompilieren der View ersetzt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Der Text in der Standardsprache oder `#key`. |\n\nDer Text wird in die Sprache des Controllers übersetzt (`controller.language`, die aus `DEF.onLocale` stammt). Die Übersetzung wird aus der Ressourcendatei der Sprache gelesen, unter einem Schlüssel aus dem Hash des Textes; gibt es keine, bleibt der Originaltext. `@(#key)` liest `key` direkt aus der Ressource. Innerhalb von Anführungszeichen werden Anführungszeichen in der Übersetzung escaped. Jede Sprache erhält ihre eigene kompilierte View.\n\nExample: Übersetzter Text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nGibt einen Wert aus einer Ressourcendatei HTML-kodiert aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Die Ressourcendatei ohne Endung. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `String` Der Wert oder ein leerer String.\n\nOhne `name` stammt der Wert aus `default.resource`. Fehlt ein Schlüssel in einer anderen Datei, wird der Wert aus `default.resource` verwendet. `@{!resource(...)}` gibt ihn unverändert aus.\n\nExample: Werte aus Ressourcen\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nSchreibt die HTML-Tags für statische Dateien und für den Head der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Ein Dateiname oder eines der Schlüsselwörter. So viele du brauchst. |\n\nReturns: `String` HTML-Tags.\n\nJedes Argument ist eines der folgenden:\n\n| Argument | Ausgabe |\n| --- | --- |\n| `'meta'` | Titel und Meta-Tags, siehe `@{meta}` |\n| `'head'` | Das Author-Meta-Tag und die mit `@{head()}` hinzugefügten Tags |\n| `'file.css'` | `<link rel=\"stylesheet\">` aus `/css/` |\n| `'file.js'` | `<script>` aus `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | Der Icon-Link |\n| ein Bild oder Video | Seine URL |\n| `'a.css + b.css'` | Eine zusammengeführte Datei aus allen |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | Das Live-Reload-Skript, nur im Debug-Modus |\n\nEin Name, der mit `/` beginnt, oder eine vollständige URL wird unverändert verwendet. `!` vor einer Datei gibt nur ihre URL aus. Die Ausgabe wird pro Datei gecacht.\n\nExample: Head eines Layouts\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: Zusammengeführte Dateien\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nSchreiben `<link rel=\"stylesheet\">`-Tags für CSS-Dateien oder `<script>`-Tags für JavaScript-Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Eine Datei. So viele du brauchst. |\n\nReturns: `String` HTML-Tags.\n\nRelative Namen werden aus `/css/` (`static_url_style`) und `/js/` (`static_url_script`) genommen. Beginne in `@{js()}` einen Namen mit `async `, um das Attribut `async` hinzuzufügen.\n\nExample: Styles und Skripte\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nGibt die URL einer statischen Datei in ihrem Ordner aus, ohne Tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname. |\n\nReturns: `String` Die URL.\n\nJeder Befehl verwendet seinen Ordner aus der Konfiguration: `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/`, und `public` das Stammverzeichnis. Ein Name, der mit `/` beginnt, wird ab dem Stammverzeichnis verwendet. Die URL berücksichtigt das Theme und `default_root`.\n\nExample: URLs\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nGibt den Titel und die Meta-Tags der Seite aus oder setzt sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | Der Titel. |\n| `description` | `String` | no |  | Die Beschreibung. |\n| `keywords` | `String|Array` | no |  | Keywords. |\n| `image` | `String` | no |  | Ein Bild für soziale Netzwerke, eine absolute URL oder eine Datei in `/img/`. |\n\nReturns: `String` HTML-Tags oder ein leerer String beim Setzen.\n\nOhne Argumente gibt es `<title>`, die Meta-Tags für Beschreibung und Keywords sowie `og:image` und `twitter:image` aus, wenn ein Bild gesetzt ist. Mit Argumenten setzt es die Werte und gibt nichts aus. Der Titel erhält am Ende ` - ` und `CONF.name`, außer `allow_custom_titles` ist `true`. Um die Ausgabe zu ändern, ersetze `DEF.onMeta`.\n\nExample: In der View setzen, im Layout ausgeben\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nGibt den Titel der Seite aus oder setzt ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Der Titel. |\n\nReturns: `String` Der Titel oder ein leerer String beim Setzen.\n\n`@{title(value)}` setzt den Titel und gibt nichts aus; `@{title2(value)}` hängt an den aktuellen Titel an. `@{title}` gibt nur den Titel aus. Der Wert wird beim Setzen HTML-kodiert, daher gibt `@{!title}` ihn aus, ohne ihn doppelt zu kodieren. Um das ganze `<title>`-Tag auszugeben, verwende `@{meta}`.\n\nExample: Titel\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nSetzt die Beschreibung, die Keywords oder den Autor der Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | Der Wert. |\n\nReturns: `String` Der Wert oder ein leerer String beim Setzen.\n\nMit einem Argument setzen sie den Wert und geben nichts aus. `@{description}`, `@{keywords}` und `@{author}` geben den Wert aus. `@{meta}` gibt die Beschreibung und die Keywords aus; `@{import('head')}` gibt den Autor aus (oder `CONF.author`). Keywords können ein Array sein.\n\nExample: Meta-Werte\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nFügt CSS, JavaScript oder HTML zum Head der Seite hinzu oder gibt es aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Ein Dateiname, eine URL oder HTML. |\n\nReturns: `String` HTML oder ein leerer String beim Hinzufügen.\n\nMit Argumenten fügt es Tags hinzu und gibt nichts aus: `.css`-Dateien werden zu `<link>`, `.js`-Dateien zu `<script>`, und ein Wert, der mit `<` beginnt, wird als HTML hinzugefügt. Jeder Wert wird nur einmal hinzugefügt. `@{head}` (oder `@{import('head')}`) gibt das Author-Meta-Tag und alles Hinzugefügte aus.\n\nExample: Aus einer View hinzufügen\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Im Layout ausgeben\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nFügt Inhalt zu einem benannten Platz hinzu oder gibt ihn aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Platzes. |\n| `value` | `String` | no |  | Ein Dateipfad oder HTML. |\n\nReturns: `String` Der Inhalt oder ein leerer String beim Hinzufügen.\n\nMit Werten hängt es diese an und gibt nichts aus: `.js`- und `.mjs`-Dateien werden zu `<script>`, `.css`-Dateien zu `<link>`, alles andere wird unverändert hinzugefügt. Nur mit dem Namen gibt es den Inhalt aus. Werte werden nicht auf die statischen Ordner aufgelöst, schreibe also vollständige Pfade.\n\nExample: Platz für Skripte\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSerialisiert einen Wert zu JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | Der zu serialisierende Wert. |\n| `id` | `String` | no |  | Die id eines `<script>`-Elements. |\n| `beautify` | `Boolean` | no | `false` | Rückt das JSON ein. |\n\nReturns: `String` JSON oder ein `<script>`-Element.\n\nMit `id` wird das JSON in `<script type=\"application/json\" id=\"...\">` eingeschlossen, damit clientseitiger Code es lesen kann. Die Ausgabe wird nicht HTML-kodiert.\n\nExample: Daten für den Browser\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nSchreibt `<option>`-Elemente für ein `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | Die Optionen. |\n| `selected` | `Any` | no |  | Der Wert der ausgewählten Option. |\n| `name` | `String` | no | `name` | Die Eigenschaft mit dem Text. |\n| `value` | `String` | no | `value` | Die Eigenschaft mit dem Wert. |\n| `disabled` | `String` | no | `disabled` | Die Eigenschaft, die eine Option deaktiviert. |\n\nReturns: `String` HTML.\n\nBei einem Array aus Objekten ist `name` die Eigenschaft des Textes (Standard `name`) und `value` die Eigenschaft des Wertes (Standard: dieselbe wie `name`, wenn du einen Namen angibst, sonst `value`). Die Eigenschaft `disabled` deaktiviert eine Option. Bei einem Array aus Strings oder Zahlen ist jedes Element sowohl Text als auch Wert. Bei einem Objekt sind die Schlüssel Werte und die Werte Texte. Die Option, die `selected` entspricht, erhält `selected=\"selected\"`. Texte und Werte werden kodiert.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Strings\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nGibt ein HTML-Attribut aus, wenn eine Bedingung wahr ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Wenn truthy, wird das Attribut ausgegeben. |\n\nReturns: `String` Das Attribut oder ein leerer String.\n\nSie geben ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` oder ` readonly=\"readonly\"` aus, mit einem Leerzeichen davor, oder nichts.\n\nExample: Attribute\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nSchreibt ein `<input>` für ein Feld des Models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `attributes` | `Object` | no |  | Zusätzliche Attribute, z. B. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` Ein `<input>`-Element.\n\nDas Model der View wird automatisch hinzugefügt: Der Wert des Inputs ist `model[name]`, kodiert. Die Attribute werden dem Element hinzugefügt; `required`, `disabled`, `readonly` und `autofocus` werden als boolesche Attribute geschrieben, und `autocomplete: true` schreibt `autocomplete=\"on\"` (jeder andere truthy-Wert schreibt `off`). `value` in den Attributen wird verwendet, wenn das Model kein solches Feld hat.\n\nExample: Formularfelder\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nSchreibt ein `<input>` beliebigen Typs für ein Feld des Models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Typ des Inputs. |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `attributes` | `Object` | no |  | Zusätzliche Attribute. |\n\nReturns: `String` Ein `<input>`-Element.\n\nFunktioniert wie `@{text()}` mit dem Typ deiner Wahl, zum Beispiel `email`, `number` oder `date`.\n\nExample: E-Mail\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nSchreibt eine Checkbox oder einen Radio-Button für ein Feld des Models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `value` | `String` | yes |  | Nur Radio: der Wert dieses Buttons. |\n| `label` | `String|Object` | no |  | Ein Label oder zusätzliche Attribute (`label` ist eines davon). |\n\nReturns: `String` Ein `<input>`, in `<label>` eingeschlossen, wenn es ein Label gibt.\n\nEine Checkbox ist angehakt, wenn `model[name]` gleich `true`, `1`, `'true'` oder `'on'` ist; ihr Wert ist `1`. Ein Radio-Button ist ausgewählt, wenn `model[name]` gleich `value` ist. Ein String als letztes Argument ist ein Label: Das Input wird in `<label>` eingeschlossen, mit dem Text in einem `<span>`. `@{radio()}` braucht dieses letzte Argument, ein Label oder ein Objekt.\n\nExample: Checkbox und Radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nSchreibt eine `<textarea>` mit dem Wert eines Feldes des Models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Feldes. |\n| `attributes` | `Object` | no |  | Zusätzliche Attribute, z. B. `{ rows: 5 }`. |\n\nReturns: `String` Ein `<textarea>`-Element.\n\nDer Inhalt ist `model[name]` oder `value` aus den Attributen. Der Inhalt wird nicht kodiert, kodiere also von Benutzern eingegebene Werte vorher.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nSchreibt ein `<img>` für eine Datei in `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Bilddatei. |\n| `width` | `Number|Object` | no |  | Die Breite oder ein Objekt mit allen Attributen. |\n| `height` | `Number` | no |  | Die Höhe. |\n| `alt` | `String` | no |  | Der Alternativtext. |\n| `class` | `String` | no |  | CSS-Klassen. |\n\nReturns: `String` Ein `<img>`-Element.\n\nStatt der Argumente kannst du ein Objekt übergeben: `{ width, height, alt, class, style }`. `alt` wird kodiert.\n\nExample: Bild\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nGibt ein CSRF-Token für den aktuellen Request aus.\n\nReturns: `String` Das Token.\n\nEine Route mit dem Flag `csrf` prüft das Token im Header `X-CSRF-Token` oder im Query-Parameter `csrf`. Dafür braucht es `secret_csrf` in der Konfiguration. Das Token wird von `DEF.onCSRFcreate(req)` erzeugt und von `DEF.onCSRFcheck(req)` geprüft.\n\nExample: Formular und AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nGibt den aktuellen Query-String aus, optional mit einem geänderten Schlüssel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Der zu setzende Parameter. |\n| `value` | `Any` | no |  | Sein neuer Wert. |\n\nReturns: `String` Ein Query-String.\n\nDas Ergebnis beginnt mit `?` oder ist leer. Verwende es für Paginierung und Filter, die die anderen Parameter beibehalten.\n\nExample: Paginierung\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nGibt den Pfad des aktuellen Requests aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Fügt das Protokoll und den Host hinzu. |\n\nReturns: `String` Die URL.\n\n`@{url(true)}` gibt die vollständige Adresse mit Protokoll und Host aus.\n\nExample: Canonical-Link\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nÜbergibt einen gerenderten Block der View an `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Name, der deiner Funktion sagt, was zu tun ist. |\n\nDie Funktion erhält den Namen, das HTML des Blocks und das Model und gibt das auszugebende HTML zurück. Standardmäßig gibt sie das HTML unverändert zurück; ersetze sie, um eine andere Template-Sprache oder einen Markdown-Parser auszuführen. Der Block wird nicht minifiziert.\n\nExample: Ein Hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: In einer View\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nSchaltet die Minifizierung einer View ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` oder `all`. |\n\nStandardmäßig minifiziert Total.js das HTML einer View sowie ihr Inline-CSS und -JavaScript. Setze diesen Befehl irgendwo in die View, um einen Teil unverändert zu lassen: `html`, `css` (oder `style`), `js` (oder `script`, `javascript`) oder `all`. HTML-Kommentare werden in jedem Fall entfernt, außer bedingten Kommentaren.\n\nExample: HTML unverändert lassen\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRendert eine View mit ihrem Layout und sendet sie als Response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | Der Name der View ohne `.html`. |\n| `model` | `Object` | no |  | Das Model der View. |\n| `headers` | `Object` | no |  | Zusätzliche HTTP-Header. |\n| `partial` | `Boolean` | no | `false` | `true` gibt das HTML zurück, statt es zu senden. |\n\nReturns: `Controller|String` Der Controller oder das HTML, wenn `partial` gleich `true` ist.\n\nOhne `name` wird die View nach dem letzten Teil der URL benannt (`index` für `/`). Der Name wird zuerst in `views/<controller>/` gesucht, dann in `views/`; die Präfixe `~`, `=theme/`, `@`, `#plugin/` und `.` ändern das (siehe Anleitung). Mit `partial` auf `true` gibt die Methode das HTML zurück, statt es zu senden; das Layout wird trotzdem angewendet, außer du setzt `controller.layout('')`. Existiert die View nicht, ist die Response ein Fehler 500.\n\nExample: Eine View rendern\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Das HTML erhalten\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nKompiliert einen HTML-String als View, rendert ihn und sendet ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das Template. |\n| `model` | `Object` | no |  | Das Model. |\n| `headers` | `Object` | no |  | Zusätzliche HTTP-Header. |\n| `partial` | `Boolean` | no | `false` | `true` gibt das HTML zurück, statt es zu senden. |\n| `key` | `String` | no |  | Ein Cache-Schlüssel für das kompilierte Template. |\n\nReturns: `Controller|String` Der Controller oder das HTML, wenn `partial` gleich `true` ist.\n\nDer String verwendet dieselbe Syntax wie eine View-Datei. Mit `key` bleibt das kompilierte Template im Release-Modus im Speicher.\n\nExample: Template aus einer Datenbank\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nSetzt das Layout für die nächste View.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Layouts oder `''`. |\n\nReturns: `Controller` Der Controller.\n\nStandard ist `default_layout` aus der Konfiguration (`layout`). Ein leerer String rendert ohne Layout. Die View kann es mit `@{layout()}` erneut ändern.\n\nExample: Admin-Layout\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nSetzt den Titel und die Meta-Tags, die `@{meta}` ausgibt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Der Titel. |\n| `description` | `String` | no |  | Die Beschreibung. |\n| `keywords` | `String|Array` | no |  | Keywords. |\n| `image` | `String` | no |  | Ein Bild für soziale Netzwerke. |\n\nReturns: `Controller` Der Controller.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` und `controller.author()` setzen jeweils einen Wert.\n\nExample: Meta-Tags\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nFügt Inhalt zu einer Section der View hinzu oder liest ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Section. |\n| `value` | `String` | no |  | Hinzuzufügendes HTML. |\n| `replace` | `Boolean` | no | `false` | Ersetzt den Inhalt, statt anzuhängen. |\n\nReturns: `Controller|String` Der Controller oder der Inhalt beim Lesen.\n\nOhne `value` gibt es den Inhalt zurück. Sonst hängt es den Wert an oder ersetzt den Inhalt, wenn `replace` gleich `true` ist. Gib die Section mit `@{section('name')}` aus.\n\nExample: Section aus einem Controller\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nEin Objekt, das sich die View, ihre Partial Views und das Layout teilen.\n\nIn der View ist es `repository` oder `R`.\n\nExample: Einen Wert an das Layout übergeben\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRendert eine View außerhalb eines Requests und gibt das HTML zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | no |  | Das Model. |\n| `layout` | `String` | no | `''` | Ein Layout. |\n| `repository` | `Object` | no |  | Das Repository. |\n| `language` | `String` | no |  | Die Sprache für `@(...)`. |\n\nReturns: `String` Das HTML.\n\nEs gibt kein Layout, außer du gibst eines an. Verwende es für E-Mails, Dateien oder von Hand gebaute Responses. Ein Name wie `=theme/view` liest die View aus einem Theme.\n\nExample: In einen String rendern\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nKompiliert einen HTML-String als View, außerhalb eines Requests, und gibt das HTML zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Das Template. |\n| `model` | `Object` | no |  | Das Model. |\n| `layout` | `String` | no | `''` | Ein Layout. |\n| `repository` | `Object` | no |  | Das Repository. |\n| `language` | `String` | no |  | Die Sprache für `@(...)`. |\n\nReturns: `String` Das HTML.\n\nEs ist `VIEW()` für ein Template in einem String, zum Beispiel aus einer Datenbank. Der String verwendet dieselbe Syntax wie eine View-Datei. Es gibt kein Layout, außer du gibst eines an, und `layout` und `repository` können die Plätze tauschen. Das Template wird bei jedem Aufruf kompiliert.\n\nExample: Template aus einem String\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBm4XU60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Vistas","summary":"Todos los comandos del motor de vistas y los métodos del controlador que renderizan vistas.","markdown":"---\ntitle: Vistas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Vistas\n\n> Todos los comandos del motor de vistas y los métodos del controlador que renderizan vistas.\n\nLas vistas son archivos `.html` en `views/` con comandos en `@{...}` y texto traducido en `@(...)`. La guía [Vistas](../../guides/views/) explica cómo funcionan juntos; esta página lista cada comando y los métodos del controlador para vistas.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nImprime el valor de una expresión JavaScript, codificado en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Una expresión JavaScript. |\n\nReturns: `String` El valor codificado.\n\nSirve cualquier expresión: una propiedad del modelo, una llamada a un método, aritmética. `null` y `undefined` imprimen una cadena vacía. Los caracteres `<`, `>`, `&`, `\"` y `'` se codifican. Para imprimir el valor sin codificar, usa `@{!expression}`.\n\nEl texto que empieza por `@{{` no es un comando y se queda en la página tal cual.\n\nExample: Valores del modelo\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nImprime el valor de una expresión sin codificación HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Una expresión JavaScript. |\n\nReturns: `String` El valor sin procesar.\n\nÚsalo para HTML en el que confías, por ejemplo contenido que ya has sanitizado. Nunca lo uses para texto escrito por usuarios.\n\nExample: HTML sin procesar\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nEl modelo que `controller.view(name, model)` pasa a la vista.\n\n`M` es un nombre más corto para el mismo objeto. La plantilla (layout) recibe el mismo modelo que la vista. Un comando que asigna un valor, como `@{model.count = 0}`, no imprime nada.\n\nExample: Controlador y vista\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: En la vista\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nUn objeto compartido por la vista, sus vistas parciales y la plantilla (layout) durante una petición.\n\nEn JavaScript es `controller.repository`. `R` es un nombre más corto. Los valores asignados en la vista son visibles en la plantilla, porque la vista se renderiza primero.\n\nExample: Asignar en la vista, leer en la plantilla\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nValores de la petición actual que cualquier vista puede usar.\n\n| Variable | Valor |\n| --- | --- |\n| `user` | El usuario con sesión iniciada (`controller.user`) |\n| `session` | La sesión (`controller.session`) |\n| `query` | El query string como objeto |\n| `body` | El cuerpo de la petición; `@{body}` solo es la vista renderizada, en una plantilla |\n| `config`, `CONF` | La configuración |\n| `language` | El idioma de la petición |\n| `url` | La ruta (path) de la petición |\n| `files` | Archivos subidos |\n| `mobile` | `true` para un dispositivo móvil |\n| `controller` | El controlador |\n\nSe codifican como cualquier expresión; pon `!` delante para obtener el valor sin procesar.\n\nExample: Valores de la petición\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nImprime un valor de la configuración, codificado en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Una clave de la configuración. |\n\nEl valor se lee cuando se compila la vista. `@{config.key}` y `@{CONF.key}` imprimen el mismo valor. Una ruta entre comillas sin `%`, como `@{'/css/default.css'}`, imprime la URL de ese archivo estático.\n\nExample: Nombre de la aplicación\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRenderiza una parte de la vista solo cuando una condición es verdadera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Una expresión JavaScript. |\n\nLa condición es JavaScript. `@{else if}` y `@{else}` son opcionales. Cierra el bloque con `@{fi}` o `@{endif}`.\n\nExample: Condición\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRenderiza una parte de la vista para cada elemento de un array u objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | El nombre de la variable para el elemento actual. |\n| `source` | `Array|Object` | yes |  | La expresión que se recorre. |\n\n`index` es la posición del elemento actual, desde `0`. Un origen vacío no imprime nada. Cuando el origen es un objeto, se convierte en un array de `{ key, value }`. `@{foreach var item in source}` también funciona. `@{continue}` y `@{break}` saltan un elemento o detienen el bucle.\n\nExample: Array\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Objeto\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Saltar elementos\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nImprime la vista renderizada dentro de la plantilla (layout).\n\nÚsalo en la plantilla. Con una propiedad, `@{body.name}` lee en cambio el cuerpo de la petición.\n\nExample: Plantilla\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nCambia la plantilla (layout) de la vista actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la plantilla, o `''` para no usar plantilla. |\n\nReturns: `String` Una cadena vacía.\n\nLa plantilla por defecto es `layout` (`default_layout` en la configuración). Una cadena vacía renderiza la vista sin plantilla. Las plantillas siempre se buscan desde la raíz de `views/`.\n\nExample: Otra plantilla\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: Sin plantilla\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nRenderiza una vista parcial en su sitio, sin plantilla (layout).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la vista. |\n| `model` | `Object` | no |  | El modelo de la vista parcial. |\n| `expire` | `String` | no |  | Cuánto tiempo guardar la salida en caché, p. ej. `'5 minutes'`. |\n| `key` | `String` | no |  | Una clave que hace única la entrada de caché, p. ej. el idioma. |\n\nReturns: `String` El HTML renderizado.\n\nEl nombre se resuelve como en `controller.view()`. La vista parcial no recibe automáticamente el modelo de la vista padre; pásalo tú. Con `expire`, la salida se guarda en caché durante ese tiempo bajo el nombre y la `key`.\n\nExample: Vista parcial por elemento\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Menú en caché\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nCompila una cadena HTML como vista y la renderiza en su sitio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | La plantilla, con la misma sintaxis que una vista. |\n| `model` | `Object` | no |  | El modelo. |\n| `key` | `String` | no |  | Una clave de caché para la plantilla compilada. |\n\nReturns: `String` El HTML renderizado.\n\nÚtil para plantillas guardadas en una base de datos. El resultado no tiene plantilla (layout). Con `key`, la plantilla compilada se mantiene en memoria en modo release.\n\nExample: Plantilla desde el modelo\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nEscribe HTML en la vista y lo imprime en otro lugar, normalmente en la plantilla (layout).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la sección. |\n\n`@{section name}` … `@{end}` guarda su contenido y no imprime nada; los bloques con el mismo nombre se unen. `@{section('name')}` imprime el contenido guardado, o nada. El contenido se guarda en el repository, así que imprímelo después de renderizar la vista: en la plantilla.\n\nExample: Scripts de una página\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: En la plantilla\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDefine un helper dentro de la vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del helper. |\n| `arguments` | `String` | yes |  | Nombres de los argumentos, como en una función JavaScript. |\n\nEl helper existe solo en esta vista. Llámalo por su nombre; su salida no se vuelve a codificar. Para helpers compartidos por todas las vistas usa `DEF.helpers`.\n\nExample: Helper en línea\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDefine helpers de vista disponibles en todas las vistas.\n\nAñade las funciones antes de que se compilen las vistas, por ejemplo en `definitions/`. En una vista, llama al helper por su nombre: `@{name(arguments)}`; `@{helpers.name(arguments)}` y `@{helper('name', arguments)}` también funcionan. Dentro de la función, `this` es el controlador. El valor devuelto se imprime sin codificar.\n\nExample: Definir\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Usar\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nMarca texto para traducir; se reemplaza cuando se compila la vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | El texto en el idioma por defecto, o `#key`. |\n\nEl texto se traduce con el idioma del controlador (`controller.language`, que viene de `DEF.onLocale`). La traducción se lee del archivo de recursos del idioma bajo una clave generada a partir del hash del texto; si no hay ninguna, se queda el texto original. `@(#key)` lee `key` directamente del recurso. Dentro de comillas, las comillas de la traducción se escapan. Cada idioma obtiene su propia vista compilada.\n\nExample: Texto traducido\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nImprime un valor de un archivo de recursos, codificado en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | El archivo de recursos sin extensión. |\n| `key` | `String` | yes |  | La clave. |\n\nReturns: `String` El valor, o una cadena vacía.\n\nSin `name`, el valor viene de `default.resource`. Cuando falta una clave en otro archivo, se usa el valor de `default.resource`. `@{!resource(...)}` lo imprime sin procesar.\n\nExample: Valores de recursos\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nEscribe las etiquetas HTML para archivos estáticos y para el head de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un nombre de archivo o una de las palabras clave. Tantos como necesites. |\n\nReturns: `String` Etiquetas HTML.\n\nCada argumento es uno de estos:\n\n| Argumento | Salida |\n| --- | --- |\n| `'meta'` | Título y etiquetas meta, consulta `@{meta}` |\n| `'head'` | La etiqueta meta del autor y las etiquetas añadidas con `@{head()}` |\n| `'file.css'` | `<link rel=\"stylesheet\">` desde `/css/` |\n| `'file.js'` | `<script>` desde `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | El enlace del icono |\n| una imagen o un vídeo | Su URL |\n| `'a.css + b.css'` | Un único archivo combinado con todos ellos |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | El script de live reload, solo en modo debug |\n\nUn nombre que empieza por `/` o una URL completa se usa tal cual. `!` delante de un archivo imprime solo su URL. La salida se guarda en caché por archivo.\n\nExample: Head de una plantilla\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: Archivos combinados\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nEscriben etiquetas `<link rel=\"stylesheet\">` para archivos CSS, o etiquetas `<script>` para archivos JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un archivo. Tantos como necesites. |\n\nReturns: `String` Etiquetas HTML.\n\nLos nombres relativos se toman de `/css/` (`static_url_style`) y `/js/` (`static_url_script`). En `@{js()}`, empieza un nombre con `async ` para añadir el atributo `async`.\n\nExample: Estilos y scripts\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nImprime la URL de un archivo estático en su carpeta, sin etiqueta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo. |\n\nReturns: `String` La URL.\n\nCada comando usa su carpeta de la configuración: `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/`, y `public` la raíz. Un nombre que empieza por `/` se usa desde la raíz. La URL respeta el tema y `default_root`.\n\nExample: URLs\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nImprime el título y las etiquetas meta de la página, o los asigna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | El título. |\n| `description` | `String` | no |  | La descripción. |\n| `keywords` | `String|Array` | no |  | Palabras clave. |\n| `image` | `String` | no |  | Una imagen para redes sociales, una URL absoluta o un archivo en `/img/`. |\n\nReturns: `String` Etiquetas HTML, o una cadena vacía al asignar.\n\nSin argumentos imprime `<title>`, las etiquetas meta de descripción y palabras clave, y `og:image` y `twitter:image` cuando hay una imagen asignada. Con argumentos asigna los valores y no imprime nada. El título recibe ` - ` y `CONF.name` al final, salvo que `allow_custom_titles` sea `true`. Para cambiar la salida, reemplaza `DEF.onMeta`.\n\nExample: Asignar en la vista, imprimir en la plantilla\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nImprime o asigna el título de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | El título. |\n\nReturns: `String` El título, o una cadena vacía al asignar.\n\n`@{title(value)}` asigna el título y no imprime nada; `@{title2(value)}` lo añade al final del título actual. `@{title}` imprime solo el título. El valor se codifica en HTML cuando se asigna, así que `@{!title}` lo imprime sin codificarlo dos veces. Para imprimir la etiqueta `<title>` completa, usa `@{meta}`.\n\nExample: Título\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nAsignan la descripción, las palabras clave o el autor de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | El valor. |\n\nReturns: `String` El valor, o una cadena vacía al asignar.\n\nCon un argumento asignan el valor y no imprimen nada. `@{description}`, `@{keywords}` y `@{author}` imprimen el valor. `@{meta}` imprime la descripción y las palabras clave; `@{import('head')}` imprime el autor (o `CONF.author`). Las palabras clave pueden ser un array.\n\nExample: Valores meta\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nAñade CSS, JavaScript o HTML al head de la página, o lo imprime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Un nombre de archivo, una URL o HTML. |\n\nReturns: `String` HTML, o una cadena vacía al añadir.\n\nCon argumentos añade etiquetas y no imprime nada: los archivos `.css` se convierten en `<link>`, los archivos `.js` en `<script>`, y un valor que empieza por `<` se añade como HTML. Cada valor se añade una sola vez. `@{head}` (o `@{import('head')}`) imprime la etiqueta meta del autor y todo lo añadido.\n\nExample: Añadir desde una vista\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Imprimir en la plantilla\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nAñade contenido a un lugar con nombre, o lo imprime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del lugar. |\n| `value` | `String` | no |  | Una ruta de archivo o HTML. |\n\nReturns: `String` El contenido, o una cadena vacía al añadir.\n\nCon valores los añade al final y no imprime nada: los archivos `.js` y `.mjs` se convierten en `<script>`, los archivos `.css` en `<link>`, y cualquier otra cosa se añade tal cual. Solo con el nombre imprime el contenido. Los valores no se resuelven a las carpetas estáticas, así que escribe rutas completas.\n\nExample: Lugar para scripts\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSerializa un valor a JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | El valor que se serializa. |\n| `id` | `String` | no |  | El id de un elemento `<script>`. |\n| `beautify` | `Boolean` | no | `false` | Indenta el JSON. |\n\nReturns: `String` JSON, o un elemento `<script>`.\n\nCon `id`, el JSON se envuelve en `<script type=\"application/json\" id=\"...\">`, para que el código del lado del cliente pueda leerlo. La salida no se codifica en HTML.\n\nExample: Datos para el navegador\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nEscribe elementos `<option>` para un `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | Las opciones. |\n| `selected` | `Any` | no |  | El valor de la opción seleccionada. |\n| `name` | `String` | no | `name` | La propiedad con el texto. |\n| `value` | `String` | no | `value` | La propiedad con el valor. |\n| `disabled` | `String` | no | `disabled` | La propiedad que deshabilita una opción. |\n\nReturns: `String` HTML.\n\nPara un array de objetos, `name` es la propiedad del texto (por defecto `name`) y `value` la propiedad del valor (por defecto: la misma que `name` cuando das un nombre, si no `value`). La propiedad `disabled` deshabilita una opción. Para un array de cadenas o números, cada elemento es a la vez texto y valor. Para un objeto, las claves son los valores y los valores son los textos. La opción igual a `selected` recibe `selected=\"selected\"`. Los textos y los valores se codifican.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Cadenas\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nImprimen un atributo HTML cuando una condición es verdadera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Cuando es truthy, se imprime el atributo. |\n\nReturns: `String` El atributo o una cadena vacía.\n\nImprimen ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` o ` readonly=\"readonly\"`, con un espacio delante, o nada.\n\nExample: Atributos\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nEscribe un `<input>` para un campo del modelo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `attributes` | `Object` | no |  | Atributos adicionales, p. ej. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` Un elemento `<input>`.\n\nEl modelo de la vista se añade automáticamente: el valor del input es `model[name]`, codificado. Los atributos se añaden al elemento; `required`, `disabled`, `readonly` y `autofocus` se escriben como atributos booleanos, y `autocomplete: true` escribe `autocomplete=\"on\"` (cualquier otro valor truthy escribe `off`). `value` en los atributos se usa cuando el modelo no tiene ese campo.\n\nExample: Campos de formulario\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nEscribe un `<input>` de cualquier tipo para un campo del modelo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El tipo del input. |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `attributes` | `Object` | no |  | Atributos adicionales. |\n\nReturns: `String` Un elemento `<input>`.\n\nFunciona como `@{text()}` con el tipo que elijas, por ejemplo `email`, `number` o `date`.\n\nExample: Email\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nEscriben una casilla de verificación o un botón de opción para un campo del modelo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `value` | `String` | yes |  | Solo para radio: el valor de este botón. |\n| `label` | `String|Object` | no |  | Una etiqueta, o atributos adicionales (`label` es uno de ellos). |\n\nReturns: `String` Un `<input>`, envuelto en `<label>` cuando hay etiqueta.\n\nUna casilla de verificación está marcada cuando `model[name]` es `true`, `1`, `'true'` o `'on'`; su valor es `1`. Un botón de opción está marcado cuando `model[name]` es igual a `value`. Una cadena como último argumento es una etiqueta: el input se envuelve en `<label>` con el texto en un `<span>`. `@{radio()}` necesita este último argumento, una etiqueta o un objeto.\n\nExample: Checkbox y radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nEscribe un `<textarea>` con el valor de un campo del modelo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo. |\n| `attributes` | `Object` | no |  | Atributos adicionales, p. ej. `{ rows: 5 }`. |\n\nReturns: `String` Un elemento `<textarea>`.\n\nEl contenido es `model[name]`, o `value` de los atributos. El contenido no se codifica, así que codifica antes los valores escritos por usuarios.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nEscribe un `<img>` para un archivo en `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El archivo de imagen. |\n| `width` | `Number|Object` | no |  | El ancho, o un objeto con todos los atributos. |\n| `height` | `Number` | no |  | El alto. |\n| `alt` | `String` | no |  | El texto alternativo. |\n| `class` | `String` | no |  | Clases CSS. |\n\nReturns: `String` Un elemento `<img>`.\n\nEn lugar de los argumentos puedes pasar un objeto: `{ width, height, alt, class, style }`. `alt` se codifica.\n\nExample: Imagen\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nImprime un token CSRF para la petición actual.\n\nReturns: `String` El token.\n\nUna ruta con el flag `csrf` comprueba el token en la cabecera `X-CSRF-Token` o en el parámetro de query `csrf`. Necesita `secret_csrf` en la configuración. El token lo genera `DEF.onCSRFcreate(req)` y lo comprueba `DEF.onCSRFcheck(req)`.\n\nExample: Formulario y AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nImprime el query string actual, opcionalmente con una clave cambiada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | El parámetro que se asigna. |\n| `value` | `Any` | no |  | Su nuevo valor. |\n\nReturns: `String` Un query string.\n\nEl resultado empieza por `?`, o está vacío. Úsalo para paginación y filtros que conservan los demás parámetros.\n\nExample: Paginación\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nImprime la ruta (path) de la petición actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Añade el protocolo y el host. |\n\nReturns: `String` La URL.\n\n`@{url(true)}` imprime la dirección completa con el protocolo y el host.\n\nExample: Enlace canónico\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nPasa un bloque renderizado de la vista a `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre que le dice a tu función qué hacer. |\n\nLa función recibe el nombre, el HTML del bloque y el modelo, y devuelve el HTML que se imprime. Por defecto devuelve el HTML sin cambios; reemplázala para ejecutar otro lenguaje de plantillas o un parser de Markdown. El bloque no se minifica.\n\nExample: Un hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: En una vista\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nDesactiva la minificación de una vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` o `all`. |\n\nPor defecto Total.js minifica el HTML de una vista y su CSS y JavaScript en línea. Pon este comando en cualquier parte de la vista para mantener una parte tal como está escrita: `html`, `css` (o `style`), `js` (o `script`, `javascript`) o `all`. Los comentarios HTML se eliminan en cualquier caso, salvo los comentarios condicionales.\n\nExample: Mantener el HTML tal como está escrito\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenderiza una vista con su plantilla (layout) y la envía como respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | El nombre de la vista sin `.html`. |\n| `model` | `Object` | no |  | El modelo de la vista. |\n| `headers` | `Object` | no |  | Cabeceras HTTP adicionales. |\n| `partial` | `Boolean` | no | `false` | `true` devuelve el HTML en lugar de enviarlo. |\n\nReturns: `Controller|String` El controlador, o el HTML cuando `partial` es `true`.\n\nSin `name`, la vista toma el nombre de la última parte de la URL (`index` para `/`). El nombre se busca primero en `views/<controller>/` y luego en `views/`; los prefijos `~`, `=theme/`, `@`, `#plugin/` y `.` cambian eso (consulta la guía). Con `partial` en `true`, el método devuelve el HTML en lugar de enviarlo; la plantilla se sigue aplicando salvo que asignes `controller.layout('')`. Cuando la vista no existe, la respuesta es un error 500.\n\nExample: Renderizar una vista\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Obtener el HTML\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nCompila una cadena HTML como vista, la renderiza y la envía.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | La plantilla. |\n| `model` | `Object` | no |  | El modelo. |\n| `headers` | `Object` | no |  | Cabeceras HTTP adicionales. |\n| `partial` | `Boolean` | no | `false` | `true` devuelve el HTML en lugar de enviarlo. |\n| `key` | `String` | no |  | Una clave de caché para la plantilla compilada. |\n\nReturns: `Controller|String` El controlador, o el HTML cuando `partial` es `true`.\n\nLa cadena usa la misma sintaxis que un archivo de vista. Con `key`, la plantilla compilada se mantiene en memoria en modo release.\n\nExample: Plantilla desde una base de datos\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nAsigna la plantilla (layout) para la siguiente vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la plantilla, o `''`. |\n\nReturns: `Controller` El controlador.\n\nEl valor por defecto es `default_layout` de la configuración (`layout`). Una cadena vacía renderiza sin plantilla. La vista puede cambiarla de nuevo con `@{layout()}`.\n\nExample: Plantilla de administración\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nAsigna el título y las etiquetas meta que imprime `@{meta}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | El título. |\n| `description` | `String` | no |  | La descripción. |\n| `keywords` | `String|Array` | no |  | Palabras clave. |\n| `image` | `String` | no |  | Una imagen para redes sociales. |\n\nReturns: `Controller` El controlador.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` y `controller.author()` asignan un valor cada uno.\n\nExample: Etiquetas meta\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nAñade contenido a una sección de la vista, o lo lee.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la sección. |\n| `value` | `String` | no |  | HTML que se añade. |\n| `replace` | `Boolean` | no | `false` | Reemplaza el contenido en lugar de añadirlo al final. |\n\nReturns: `Controller|String` El controlador, o el contenido al leer.\n\nSin `value` devuelve el contenido. Si no, añade el valor al final, o reemplaza el contenido cuando `replace` es `true`. Imprime la sección con `@{section('name')}`.\n\nExample: Sección desde un controlador\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn objeto compartido por la vista, sus vistas parciales y la plantilla (layout).\n\nEn la vista es `repository` o `R`.\n\nExample: Pasar un valor a la plantilla\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRenderiza una vista fuera de una petición y devuelve el HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la vista. |\n| `model` | `Object` | no |  | El modelo. |\n| `layout` | `String` | no | `''` | Una plantilla. |\n| `repository` | `Object` | no |  | El repository. |\n| `language` | `String` | no |  | El idioma para `@(...)`. |\n\nReturns: `String` El HTML.\n\nNo hay plantilla (layout) salvo que nombres una. Úsalo para emails, archivos o respuestas construidas a mano. Un nombre como `=theme/view` lee la vista de un tema.\n\nExample: Renderizar a una cadena\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nCompila una cadena HTML como vista, fuera de una petición, y devuelve el HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | La plantilla. |\n| `model` | `Object` | no |  | El modelo. |\n| `layout` | `String` | no | `''` | Una plantilla (layout). |\n| `repository` | `Object` | no |  | El repository. |\n| `language` | `String` | no |  | El idioma para `@(...)`. |\n\nReturns: `String` El HTML.\n\nEs `VIEW()` para una plantilla en una cadena, por ejemplo de una base de datos. La cadena usa la misma sintaxis que un archivo de vista. No hay plantilla (layout) salvo que nombres una, y `layout` y `repository` pueden intercambiar posiciones. La plantilla se compila en cada llamada.\n\nExample: Plantilla desde una cadena\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBm4XU60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Vues","summary":"Toutes les commandes du moteur de vues et les méthodes du contrôleur qui affichent les vues.","markdown":"---\ntitle: Vues\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Vues\n\n> Toutes les commandes du moteur de vues et les méthodes du contrôleur qui affichent les vues.\n\nLes vues sont des fichiers `.html` dans `views/`, avec des commandes dans `@{...}` et du texte traduit dans `@(...)`. Le guide [Vues](../../guides/views/) explique comment ils fonctionnent ensemble ; cette page liste chaque commande ainsi que les méthodes du contrôleur pour les vues.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nAffiche la valeur d'une expression JavaScript, encodée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Une expression JavaScript. |\n\nReturns: `String` La valeur encodée.\n\nN'importe quelle expression fonctionne : une propriété du modèle, un appel de méthode, un calcul. `null` et `undefined` affichent une chaîne vide. Les caractères `<`, `>`, `&`, `\"` et `'` sont encodés. Pour afficher la valeur sans encodage, utilise `@{!expression}`.\n\nUn texte qui commence par `@{{` n'est pas une commande et reste tel quel dans la page.\n\nExample: Valeurs du modèle\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nAffiche la valeur d'une expression sans encodage HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Une expression JavaScript. |\n\nReturns: `String` La valeur brute.\n\nUtilise-la pour du HTML de confiance, par exemple du contenu que tu as déjà nettoyé. Ne l'utilise jamais pour du texte saisi par les utilisateurs.\n\nExample: HTML brut\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nLe modèle passé à la vue par `controller.view(name, model)`.\n\n`M` est un nom plus court pour le même objet. Le layout reçoit le même modèle que la vue. Une commande qui affecte une valeur, comme `@{model.count = 0}`, n'affiche rien.\n\nExample: Contrôleur et vue\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: Dans la vue\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nUn objet partagé par la vue, ses vues partielles et le layout pendant une requête.\n\nEn JavaScript, il s'agit de `controller.repository`. `R` est un nom plus court. Les valeurs définies dans la vue sont visibles dans le layout, car la vue est rendue en premier.\n\nExample: Défini dans la vue, lu dans le layout\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nValeurs de la requête courante que toute vue peut utiliser.\n\n| Variable | Valeur |\n| --- | --- |\n| `user` | L'utilisateur connecté (`controller.user`) |\n| `session` | La session (`controller.session`) |\n| `query` | La query string sous forme d'objet |\n| `body` | Le corps de la requête ; `@{body}` seul correspond à la vue rendue, dans un layout |\n| `config`, `CONF` | La configuration |\n| `language` | La langue de la requête |\n| `url` | Le chemin de la requête |\n| `files` | Les fichiers envoyés |\n| `mobile` | `true` pour un appareil mobile |\n| `controller` | Le contrôleur |\n\nElles sont encodées comme n'importe quelle expression ; place `!` devant pour obtenir la valeur brute.\n\nExample: Valeurs de la requête\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nAffiche une valeur de la configuration, encodée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Une clé de la configuration. |\n\nLa valeur est lue lors de la compilation de la vue. `@{config.key}` et `@{CONF.key}` affichent la même valeur. Un chemin entre guillemets sans `%`, comme `@{'/css/default.css'}`, affiche l'URL de ce fichier statique.\n\nExample: Nom de l'application\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRend une partie de la vue uniquement lorsqu'une condition est vraie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Une expression JavaScript. |\n\nLa condition est du JavaScript. `@{else if}` et `@{else}` sont facultatifs. Ferme le bloc avec `@{fi}` ou `@{endif}`.\n\nExample: Condition\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRend une partie de la vue pour chaque élément d'un tableau ou d'un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | Le nom de la variable de l'élément courant. |\n| `source` | `Array|Object` | yes |  | L'expression à parcourir. |\n\n`index` est la position de l'élément courant, à partir de `0`. Une source vide n'affiche rien. Lorsque la source est un objet, elle devient un tableau de `{ key, value }`. `@{foreach var item in source}` fonctionne aussi. `@{continue}` et `@{break}` sautent un élément ou arrêtent la boucle.\n\nExample: Tableau\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Objet\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Sauter des éléments\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nAffiche la vue rendue à l'intérieur du layout.\n\nUtilise-la dans le layout. Avec une propriété, `@{body.name}` lit plutôt le corps de la requête.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nChange le layout de la vue courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du layout, ou `''` pour aucun layout. |\n\nReturns: `String` Une chaîne vide.\n\nLe layout par défaut est `layout` (`default_layout` dans la configuration). Une chaîne vide rend la vue sans layout. Les layouts sont toujours recherchés à partir de la racine de `views/`.\n\nExample: Un autre layout\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: Sans layout\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nRend une vue partielle sur place, sans layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la vue. |\n| `model` | `Object` | no |  | Le modèle de la vue partielle. |\n| `expire` | `String` | no |  | Durée de mise en cache du résultat, par ex. `'5 minutes'`. |\n| `key` | `String` | no |  | Une clé qui rend l'entrée du cache unique, par ex. la langue. |\n\nReturns: `String` Le HTML rendu.\n\nLe nom est résolu comme dans `controller.view()`. La vue partielle ne reçoit pas automatiquement le modèle de la vue parente ; passe-le. Avec `expire`, le résultat est mis en cache pendant cette durée sous le nom et la `key`.\n\nExample: Vue partielle par élément\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Menu en cache\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nCompile une chaîne HTML comme une vue et la rend sur place.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le template, avec la même syntaxe qu'une vue. |\n| `model` | `Object` | no |  | Le modèle. |\n| `key` | `String` | no |  | Une clé de cache pour le template compilé. |\n\nReturns: `String` Le HTML rendu.\n\nUtile pour les templates stockés dans une base de données. Le résultat n'a pas de layout. Avec `key`, le template compilé est conservé en mémoire en mode release.\n\nExample: Template issu du modèle\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nÉcrit du HTML dans la vue et l'affiche ailleurs, généralement dans le layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la section. |\n\n`@{section name}` … `@{end}` stocke son contenu et n'affiche rien ; les blocs portant le même nom sont réunis. `@{section('name')}` affiche le contenu stocké, ou rien. Le contenu est conservé dans le repository : affiche-le donc après le rendu de la vue, dans le layout.\n\nExample: Scripts d'une page\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: Dans le layout\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDéfinit un helper à l'intérieur de la vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du helper. |\n| `arguments` | `String` | yes |  | Noms des arguments, comme dans une fonction JavaScript. |\n\nLe helper n'existe que dans cette vue. Appelle-le par son nom ; son résultat n'est pas encodé une seconde fois. Pour des helpers partagés par toutes les vues, utilise `DEF.helpers`.\n\nExample: Helper en ligne\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDéfinit des helpers de vue disponibles dans toutes les vues.\n\nAjoute les fonctions avant la compilation des vues, par exemple dans `definitions/`. Dans une vue, appelle le helper par son nom : `@{name(arguments)}` ; `@{helpers.name(arguments)}` et `@{helper('name', arguments)}` fonctionnent aussi. Dans la fonction, `this` est le contrôleur. La valeur retournée est affichée sans encodage.\n\nExample: Définir\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Utiliser\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nMarque un texte à traduire ; il est remplacé lors de la compilation de la vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Le texte dans la langue par défaut, ou `#key`. |\n\nLe texte est traduit dans la langue du contrôleur (`controller.language`, qui provient de `DEF.onLocale`). La traduction est lue dans le fichier de ressources de la langue, sous une clé construite à partir du hash du texte ; s'il n'y en a pas, le texte original est conservé. `@(#key)` lit directement `key` dans la ressource. Entre guillemets, les guillemets de la traduction sont échappés. Chaque langue a sa propre vue compilée.\n\nExample: Texte traduit\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nAffiche une valeur d'un fichier de ressources, encodée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Le fichier de ressources sans extension. |\n| `key` | `String` | yes |  | La clé. |\n\nReturns: `String` La valeur, ou une chaîne vide.\n\nSans `name`, la valeur provient de `default.resource`. Lorsqu'une clé manque dans un autre fichier, la valeur de `default.resource` est utilisée. `@{!resource(...)}` l'affiche brute.\n\nExample: Valeurs de ressources\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nÉcrit les balises HTML des fichiers statiques et de l'en-tête de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un nom de fichier ou l'un des mots-clés. Autant que nécessaire. |\n\nReturns: `String` Des balises HTML.\n\nChaque argument est l'un des suivants :\n\n| Argument | Résultat |\n| --- | --- |\n| `'meta'` | Le titre et les balises meta, voir `@{meta}` |\n| `'head'` | La balise meta author et les balises ajoutées avec `@{head()}` |\n| `'file.css'` | `<link rel=\"stylesheet\">` depuis `/css/` |\n| `'file.js'` | `<script>` depuis `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | Le lien de l'icône |\n| une image ou une vidéo | Son URL |\n| `'a.css + b.css'` | Un seul fichier fusionné les contenant tous |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | Le script de rechargement à chaud, en mode debug uniquement |\n\nUn nom qui commence par `/` ou une URL complète est utilisé tel quel. `!` devant un fichier n'affiche que son URL. Le résultat est mis en cache par fichier.\n\nExample: En-tête d'un layout\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: Fichiers fusionnés\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nÉcrivent des balises `<link rel=\"stylesheet\">` pour les fichiers CSS, ou des balises `<script>` pour les fichiers JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un fichier. Autant que nécessaire. |\n\nReturns: `String` Des balises HTML.\n\nLes noms relatifs sont pris dans `/css/` (`static_url_style`) et `/js/` (`static_url_script`). Dans `@{js()}`, commence un nom par `async ` pour ajouter l'attribut `async`.\n\nExample: Styles et scripts\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nAffiche l'URL d'un fichier statique dans son dossier, sans balise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier. |\n\nReturns: `String` L'URL.\n\nChaque commande utilise son dossier défini dans la configuration : `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/`, et `public` la racine. Un nom qui commence par `/` est pris depuis la racine. L'URL respecte le thème et `default_root`.\n\nExample: URL\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nAffiche le titre et les balises meta de la page, ou les définit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | Le titre. |\n| `description` | `String` | no |  | La description. |\n| `keywords` | `String|Array` | no |  | Les mots-clés. |\n| `image` | `String` | no |  | Une image pour les réseaux sociaux, une URL absolue ou un fichier dans `/img/`. |\n\nReturns: `String` Des balises HTML, ou une chaîne vide lors de la définition.\n\nSans argument, elle affiche `<title>`, les balises meta description et keywords, ainsi que `og:image` et `twitter:image` lorsqu'une image est définie. Avec des arguments, elle définit les valeurs et n'affiche rien. Le titre reçoit ` - ` et `CONF.name` à la fin, sauf si `allow_custom_titles` vaut `true`. Pour modifier le résultat, remplace `DEF.onMeta`.\n\nExample: Définir dans la vue, afficher dans le layout\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nAffiche ou définit le titre de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Le titre. |\n\nReturns: `String` Le titre, ou une chaîne vide lors de la définition.\n\n`@{title(value)}` définit le titre et n'affiche rien ; `@{title2(value)}` ajoute à la suite du titre courant. `@{title}` affiche le titre seul. La valeur est encodée en HTML lorsqu'elle est définie : `@{!title}` l'affiche donc sans l'encoder deux fois. Pour afficher la balise `<title>` complète, utilise `@{meta}`.\n\nExample: Titre\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nDéfinissent la description, les mots-clés ou l'auteur de la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | La valeur. |\n\nReturns: `String` La valeur, ou une chaîne vide lors de la définition.\n\nAvec un argument, elles définissent la valeur et n'affichent rien. `@{description}`, `@{keywords}` et `@{author}` affichent la valeur. `@{meta}` affiche la description et les mots-clés ; `@{import('head')}` affiche l'auteur (ou `CONF.author`). Les mots-clés peuvent être un tableau.\n\nExample: Valeurs meta\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nAjoute du CSS, du JavaScript ou du HTML à l'en-tête de la page, ou l'affiche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Un nom de fichier, une URL ou du HTML. |\n\nReturns: `String` Du HTML, ou une chaîne vide lors de l'ajout.\n\nAvec des arguments, elle ajoute des balises et n'affiche rien : les fichiers `.css` deviennent `<link>`, les fichiers `.js` `<script>`, et une valeur qui commence par `<` est ajoutée comme HTML. Chaque valeur n'est ajoutée qu'une fois. `@{head}` (ou `@{import('head')}`) affiche la balise meta author et tout ce qui a été ajouté.\n\nExample: Ajouter depuis une vue\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Afficher dans le layout\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nAjoute du contenu à un emplacement nommé, ou l'affiche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'emplacement. |\n| `value` | `String` | no |  | Un chemin de fichier ou du HTML. |\n\nReturns: `String` Le contenu, ou une chaîne vide lors de l'ajout.\n\nAvec des valeurs, elle les ajoute à la suite et n'affiche rien : les fichiers `.js` et `.mjs` deviennent `<script>`, les fichiers `.css` `<link>`, tout le reste est ajouté tel quel. Avec le nom seul, elle affiche le contenu. Les valeurs ne sont pas résolues vers les dossiers statiques : écris donc des chemins complets.\n\nExample: Emplacement pour les scripts\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSérialise une valeur en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | La valeur à sérialiser. |\n| `id` | `String` | no |  | L'id d'un élément `<script>`. |\n| `beautify` | `Boolean` | no | `false` | Indente le JSON. |\n\nReturns: `String` Du JSON, ou un élément `<script>`.\n\nAvec `id`, le JSON est enveloppé dans `<script type=\"application/json\" id=\"...\">`, afin que le code côté client puisse le lire. Le résultat n'est pas encodé en HTML.\n\nExample: Données pour le navigateur\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nÉcrit des éléments `<option>` pour un `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | Les options. |\n| `selected` | `Any` | no |  | La valeur de l'option sélectionnée. |\n| `name` | `String` | no | `name` | La propriété contenant le texte. |\n| `value` | `String` | no | `value` | La propriété contenant la valeur. |\n| `disabled` | `String` | no | `disabled` | La propriété qui désactive une option. |\n\nReturns: `String` Du HTML.\n\nPour un tableau d'objets, `name` est la propriété du texte (par défaut `name`) et `value` la propriété de la valeur (par défaut : la même que `name` lorsque tu indiques un nom, sinon `value`). La propriété `disabled` désactive une option. Pour un tableau de chaînes ou de nombres, chaque élément est à la fois le texte et la valeur. Pour un objet, les clés sont les valeurs et les valeurs sont les textes. L'option égale à `selected` reçoit `selected=\"selected\"`. Les textes et les valeurs sont encodés.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Chaînes\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nAffichent un attribut HTML lorsqu'une condition est vraie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Lorsqu'elle est vraie, l'attribut est affiché. |\n\nReturns: `String` L'attribut ou une chaîne vide.\n\nElles affichent ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` ou ` readonly=\"readonly\"`, précédé d'un espace, ou rien.\n\nExample: Attributs\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nÉcrivent un `<input>` pour un champ du modèle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `attributes` | `Object` | no |  | Attributs supplémentaires, par ex. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` Un élément `<input>`.\n\nLe modèle de la vue est ajouté automatiquement : la valeur de l'input est `model[name]`, encodée. Les attributs sont ajoutés à l'élément ; `required`, `disabled`, `readonly` et `autofocus` sont écrits comme attributs booléens, et `autocomplete: true` écrit `autocomplete=\"on\"` (toute autre valeur vraie écrit `off`). `value` dans les attributs est utilisé lorsque le modèle n'a pas ce champ.\n\nExample: Champs de formulaire\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nÉcrit un `<input>` de n'importe quel type pour un champ du modèle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le type de l'input. |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `attributes` | `Object` | no |  | Attributs supplémentaires. |\n\nReturns: `String` Un élément `<input>`.\n\nFonctionne comme `@{text()}` avec le type de ton choix, par exemple `email`, `number` ou `date`.\n\nExample: E-mail\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nÉcrivent une case à cocher ou un bouton radio pour un champ du modèle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `value` | `String` | yes |  | Radio uniquement : la valeur de ce bouton. |\n| `label` | `String|Object` | no |  | Un libellé, ou des attributs supplémentaires (`label` en fait partie). |\n\nReturns: `String` Un `<input>`, enveloppé dans `<label>` lorsqu'il y a un libellé.\n\nUne case à cocher est cochée lorsque `model[name]` vaut `true`, `1`, `'true'` ou `'on'` ; sa valeur est `1`. Un bouton radio est coché lorsque `model[name]` est égal à `value`. Une chaîne comme dernier argument est un libellé : l'input est enveloppé dans `<label>` avec le texte dans un `<span>`. `@{radio()}` a besoin de ce dernier argument, un libellé ou un objet.\n\nExample: Case à cocher et radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nÉcrit un `<textarea>` avec la valeur d'un champ du modèle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ. |\n| `attributes` | `Object` | no |  | Attributs supplémentaires, par ex. `{ rows: 5 }`. |\n\nReturns: `String` Un élément `<textarea>`.\n\nLe contenu est `model[name]`, ou `value` issu des attributs. Le contenu n'est pas encodé : encode donc d'abord les valeurs saisies par les utilisateurs.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nÉcrit un `<img>` pour un fichier dans `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le fichier image. |\n| `width` | `Number|Object` | no |  | La largeur, ou un objet avec tous les attributs. |\n| `height` | `Number` | no |  | La hauteur. |\n| `alt` | `String` | no |  | Le texte alternatif. |\n| `class` | `String` | no |  | Les classes CSS. |\n\nReturns: `String` Un élément `<img>`.\n\nÀ la place des arguments, tu peux passer un objet : `{ width, height, alt, class, style }`. `alt` est encodé.\n\nExample: Image\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nAffiche un jeton CSRF pour la requête courante.\n\nReturns: `String` Le jeton.\n\nUne route avec le flag `csrf` vérifie le jeton dans l'en-tête `X-CSRF-Token` ou dans le paramètre de requête `csrf`. Elle nécessite `secret_csrf` dans la configuration. Le jeton est créé par `DEF.onCSRFcreate(req)` et vérifié par `DEF.onCSRFcheck(req)`.\n\nExample: Formulaire et AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nAffiche la query string courante, éventuellement avec une clé modifiée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Le paramètre à définir. |\n| `value` | `Any` | no |  | Sa nouvelle valeur. |\n\nReturns: `String` Une query string.\n\nLe résultat commence par `?`, ou est vide. Utilise-la pour la pagination et les filtres qui conservent les autres paramètres.\n\nExample: Pagination\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nAffiche le chemin de la requête courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Ajoute le protocole et l'hôte. |\n\nReturns: `String` L'URL.\n\n`@{url(true)}` affiche l'adresse complète avec le protocole et l'hôte.\n\nExample: Lien canonique\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nPasse un bloc rendu de la vue à `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom qui indique à ta fonction ce qu'elle doit faire. |\n\nLa fonction reçoit le nom, le HTML du bloc et le modèle, et retourne le HTML à afficher. Par défaut, elle retourne le HTML inchangé ; remplace-la pour exécuter un autre langage de template ou un parseur Markdown. Le bloc n'est pas minifié.\n\nExample: Un hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: Dans une vue\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nDésactive la minification d'une vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` ou `all`. |\n\nPar défaut, Total.js minifie le HTML d'une vue ainsi que son CSS et son JavaScript en ligne. Place cette commande n'importe où dans la vue pour conserver une partie telle qu'écrite : `html`, `css` (ou `style`), `js` (ou `script`, `javascript`) ou `all`. Les commentaires HTML sont supprimés dans tous les cas, sauf les commentaires conditionnels.\n\nExample: Conserver le HTML tel qu'écrit\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRend une vue avec son layout et l'envoie comme réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | Le nom de la vue sans `.html`. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n| `headers` | `Object` | no |  | En-têtes HTTP supplémentaires. |\n| `partial` | `Boolean` | no | `false` | `true` retourne le HTML au lieu de l'envoyer. |\n\nReturns: `Controller|String` Le contrôleur, ou le HTML lorsque `partial` vaut `true`.\n\nSans `name`, la vue porte le nom de la dernière partie de l'URL (`index` pour `/`). Le nom est d'abord recherché dans `views/<controller>/`, puis dans `views/` ; les préfixes `~`, `=theme/`, `@`, `#plugin/` et `.` modifient ce comportement (voir le guide). Avec `partial` à `true`, la méthode retourne le HTML au lieu de l'envoyer ; le layout est tout de même appliqué, sauf si tu définis `controller.layout('')`. Lorsque la vue n'existe pas, la réponse est une erreur 500.\n\nExample: Rendre une vue\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Obtenir le HTML\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nCompile une chaîne HTML comme une vue, la rend et l'envoie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le template. |\n| `model` | `Object` | no |  | Le modèle. |\n| `headers` | `Object` | no |  | En-têtes HTTP supplémentaires. |\n| `partial` | `Boolean` | no | `false` | `true` retourne le HTML au lieu de l'envoyer. |\n| `key` | `String` | no |  | Une clé de cache pour le template compilé. |\n\nReturns: `Controller|String` Le contrôleur, ou le HTML lorsque `partial` vaut `true`.\n\nLa chaîne utilise la même syntaxe qu'un fichier de vue. Avec `key`, le template compilé est conservé en mémoire en mode release.\n\nExample: Template issu d'une base de données\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nDéfinit le layout de la prochaine vue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du layout, ou `''`. |\n\nReturns: `Controller` Le contrôleur.\n\nLa valeur par défaut est `default_layout` de la configuration (`layout`). Une chaîne vide rend sans layout. La vue peut encore le modifier avec `@{layout()}`.\n\nExample: Layout d'administration\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nDéfinit le titre et les balises meta qu'affiche `@{meta}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Le titre. |\n| `description` | `String` | no |  | La description. |\n| `keywords` | `String|Array` | no |  | Les mots-clés. |\n| `image` | `String` | no |  | Une image pour les réseaux sociaux. |\n\nReturns: `Controller` Le contrôleur.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` et `controller.author()` définissent chacune une valeur.\n\nExample: Balises meta\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nAjoute du contenu à une section de la vue, ou le lit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la section. |\n| `value` | `String` | no |  | Le HTML à ajouter. |\n| `replace` | `Boolean` | no | `false` | Remplace le contenu au lieu de l'ajouter à la suite. |\n\nReturns: `Controller|String` Le contrôleur, ou le contenu lors de la lecture.\n\nSans `value`, elle retourne le contenu. Sinon, elle ajoute la valeur à la suite, ou remplace le contenu lorsque `replace` vaut `true`. Affiche la section avec `@{section('name')}`.\n\nExample: Section depuis un contrôleur\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn objet partagé par la vue, ses vues partielles et le layout.\n\nDans la vue, il s'agit de `repository` ou `R`.\n\nExample: Passer une valeur au layout\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRend une vue en dehors d'une requête et retourne le HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la vue. |\n| `model` | `Object` | no |  | Le modèle. |\n| `layout` | `String` | no | `''` | Un layout. |\n| `repository` | `Object` | no |  | Le repository. |\n| `language` | `String` | no |  | La langue pour `@(...)`. |\n\nReturns: `String` Le HTML.\n\nIl n'y a pas de layout, sauf si tu en nommes un. Utilise-la pour des e-mails, des fichiers ou des réponses construites à la main. Un nom comme `=theme/view` lit la vue depuis un thème.\n\nExample: Rendre dans une chaîne\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nCompile une chaîne HTML comme une vue, en dehors d'une requête, et retourne le HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Le template. |\n| `model` | `Object` | no |  | Le modèle. |\n| `layout` | `String` | no | `''` | Un layout. |\n| `repository` | `Object` | no |  | Le repository. |\n| `language` | `String` | no |  | La langue pour `@(...)`. |\n\nReturns: `String` Le HTML.\n\nC'est `VIEW()` pour un template contenu dans une chaîne, par exemple issu d'une base de données. La chaîne utilise la même syntaxe qu'un fichier de vue. Il n'y a pas de layout, sauf si tu en nommes un, et `layout` et `repository` peuvent être intervertis. Le template est compilé à chaque appel.\n\nExample: Template issu d'une chaîne\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBm4XU60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Viste","summary":"Tutti i comandi del motore delle viste e i metodi del controller che renderizzano le viste.","markdown":"---\ntitle: Viste\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Viste\n\n> Tutti i comandi del motore delle viste e i metodi del controller che renderizzano le viste.\n\nLe viste sono file `.html` in `views/` con i comandi in `@{...}` e il testo tradotto in `@(...)`. La guida [Viste](../../guides/views/) spiega come funzionano insieme; questa pagina elenca ogni comando e i metodi del controller per le viste.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nStampa il valore di un'espressione JavaScript, con codifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Un'espressione JavaScript. |\n\nReturns: `String` Il valore codificato.\n\nFunziona qualsiasi espressione: una proprietà del modello, una chiamata a un metodo, un'operazione aritmetica. `null` e `undefined` stampano una stringa vuota. I caratteri `<`, `>`, `&`, `\"` e `'` vengono codificati. Per stampare il valore senza codifica, usa `@{!expression}`.\n\nIl testo che inizia con `@{{` non è un comando e resta nella pagina così com'è.\n\nExample: Valori del modello\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nStampa il valore di un'espressione senza codifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | Un'espressione JavaScript. |\n\nReturns: `String` Il valore grezzo.\n\nUsalo per HTML di cui ti fidi, per esempio contenuto che hai già sanificato. Non usarlo mai per testo digitato dagli utenti.\n\nExample: HTML grezzo\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nIl modello passato alla vista da `controller.view(name, model)`.\n\n`M` è un nome più breve per lo stesso oggetto. Il layout riceve lo stesso modello della vista. Un comando che assegna un valore, come `@{model.count = 0}`, non stampa nulla.\n\nExample: Controller e vista\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: Nella vista\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nUn oggetto condiviso dalla vista, dalle sue viste parziali e dal layout durante una richiesta.\n\nIn JavaScript è `controller.repository`. `R` è un nome più breve. I valori impostati nella vista sono visibili nel layout, perché la vista viene renderizzata per prima.\n\nExample: Impostato nella vista, letto nel layout\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nValori della richiesta corrente che ogni vista può usare.\n\n| Variabile | Valore |\n| --- | --- |\n| `user` | L'utente autenticato (`controller.user`) |\n| `session` | La sessione (`controller.session`) |\n| `query` | La query string come oggetto |\n| `body` | Il corpo della richiesta; `@{body}` da solo è la vista renderizzata, in un layout |\n| `config`, `CONF` | La configurazione |\n| `language` | La lingua della richiesta |\n| `url` | Il percorso della richiesta |\n| `files` | I file caricati |\n| `mobile` | `true` per un dispositivo mobile |\n| `controller` | Il controller |\n\nVengono codificati come qualsiasi espressione; metti `!` davanti per il valore grezzo.\n\nExample: Valori della richiesta\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nStampa un valore della configurazione, con codifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Una chiave della configurazione. |\n\nIl valore viene letto quando la vista viene compilata. `@{config.key}` e `@{CONF.key}` stampano lo stesso valore. Un percorso tra virgolette senza `%`, come `@{'/css/default.css'}`, stampa l'URL di quel file statico.\n\nExample: Nome dell'app\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRenderizza una parte della vista solo quando una condizione è vera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Un'espressione JavaScript. |\n\nLa condizione è JavaScript. `@{else if}` e `@{else}` sono facoltativi. Chiudi il blocco con `@{fi}` o `@{endif}`.\n\nExample: Condizione\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRenderizza una parte della vista per ogni elemento di un array o di un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | Il nome della variabile per l'elemento corrente. |\n| `source` | `Array|Object` | yes |  | L'espressione su cui iterare. |\n\n`index` è la posizione dell'elemento corrente, a partire da `0`. Una sorgente vuota non stampa nulla. Quando la sorgente è un oggetto, diventa un array di `{ key, value }`. Funziona anche `@{foreach var item in source}`. `@{continue}` e `@{break}` saltano un elemento o fermano il ciclo.\n\nExample: Array\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Oggetto\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Saltare elementi\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nStampa la vista renderizzata all'interno del layout.\n\nUsalo nel layout. Con una proprietà, `@{body.name}` legge invece il corpo della richiesta.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nCambia il layout della vista corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del layout, o `''` per nessun layout. |\n\nReturns: `String` Una stringa vuota.\n\nIl layout predefinito è `layout` (`default_layout` nella configurazione). Una stringa vuota renderizza la vista senza layout. I layout vengono sempre cercati dalla radice di `views/`.\n\nExample: Un altro layout\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: Nessun layout\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nRenderizza sul posto una vista parziale, senza layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista. |\n| `model` | `Object` | no |  | Il modello della vista parziale. |\n| `expire` | `String` | no |  | Per quanto tempo mettere in cache l'output, ad es. `'5 minutes'`. |\n| `key` | `String` | no |  | Una chiave che rende unica la voce della cache, ad es. la lingua. |\n\nReturns: `String` L'HTML renderizzato.\n\nIl nome viene risolto come in `controller.view()`. La vista parziale non riceve automaticamente il modello della vista padre; passaglielo. Con `expire` l'output viene messo in cache per quel tempo sotto il nome e la `key`.\n\nExample: Vista parziale per elemento\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Menu in cache\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nCompila una stringa HTML come vista e la renderizza sul posto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il template, con la stessa sintassi di una vista. |\n| `model` | `Object` | no |  | Il modello. |\n| `key` | `String` | no |  | Una chiave di cache per il template compilato. |\n\nReturns: `String` L'HTML renderizzato.\n\nUtile per i template salvati in un database. Il risultato non ha layout. Con `key`, il template compilato viene tenuto in memoria in modalità release.\n\nExample: Template dal modello\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nScrive HTML nella vista e lo stampa altrove, di solito nel layout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della sezione. |\n\n`@{section name}` … `@{end}` memorizza il suo contenuto e non stampa nulla; i blocchi con lo stesso nome vengono uniti. `@{section('name')}` stampa il contenuto memorizzato, oppure nulla. Il contenuto è tenuto nel repository, quindi stampalo dopo che la vista è stata renderizzata: nel layout.\n\nExample: Script di una pagina\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: Nel layout\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDefinisce un helper all'interno della vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'helper. |\n| `arguments` | `String` | yes |  | I nomi degli argomenti, come in una funzione JavaScript. |\n\nL'helper esiste solo in questa vista. Chiamalo con il suo nome; il suo output non viene codificato di nuovo. Per gli helper condivisi da tutte le viste usa `DEF.helpers`.\n\nExample: Helper inline\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDefinisce gli helper delle viste disponibili in tutte le viste.\n\nAggiungi le funzioni prima che le viste vengano compilate, per esempio in `definitions/`. In una vista, chiama l'helper con il suo nome: `@{name(arguments)}`; funzionano anche `@{helpers.name(arguments)}` e `@{helper('name', arguments)}`. All'interno della funzione `this` è il controller. Il valore restituito viene stampato senza codifica.\n\nExample: Definire\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Usare\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nContrassegna il testo da tradurre; viene sostituito quando la vista viene compilata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Il testo nella lingua predefinita, o `#key`. |\n\nIl testo viene tradotto con la lingua del controller (`controller.language`, che proviene da `DEF.onLocale`). La traduzione viene letta dal file di risorse della lingua sotto una chiave ricavata dall'hash del testo; se non c'è, resta il testo originale. `@(#key)` legge `key` direttamente dalla risorsa. Tra virgolette, le virgolette nella traduzione vengono sottoposte a escape. Ogni lingua ha la propria vista compilata.\n\nExample: Testo tradotto\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nStampa un valore da un file di risorse, con codifica HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Il file di risorse senza estensione. |\n| `key` | `String` | yes |  | La chiave. |\n\nReturns: `String` Il valore, o una stringa vuota.\n\nSenza `name` il valore proviene da `default.resource`. Quando una chiave manca in un altro file, viene usato il valore di `default.resource`. `@{!resource(...)}` lo stampa grezzo.\n\nExample: Valori delle risorse\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nScrive i tag HTML per i file statici e per l'head della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un nome di file o una delle parole chiave. Quanti ne servono. |\n\nReturns: `String` Tag HTML.\n\nOgni argomento è uno dei seguenti:\n\n| Argomento | Output |\n| --- | --- |\n| `'meta'` | Titolo e meta tag, vedi `@{meta}` |\n| `'head'` | Il meta tag dell'autore e i tag aggiunti con `@{head()}` |\n| `'file.css'` | `<link rel=\"stylesheet\">` da `/css/` |\n| `'file.js'` | `<script>` da `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | Il link dell'icona |\n| un'immagine o un video | Il suo URL |\n| `'a.css + b.css'` | Un unico file che li unisce tutti |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | Lo script di live reload, solo in modalità debug |\n\nUn nome che inizia con `/` o un URL completo viene usato così com'è. `!` davanti a un file stampa solo il suo URL. L'output viene messo in cache per ogni file.\n\nExample: Head di un layout\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: File uniti\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nScrivono tag `<link rel=\"stylesheet\">` per i file CSS, o tag `<script>` per i file JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Un file. Quanti ne servono. |\n\nReturns: `String` Tag HTML.\n\nI nomi relativi vengono presi da `/css/` (`static_url_style`) e `/js/` (`static_url_script`). In `@{js()}`, fai iniziare un nome con `async ` per aggiungere l'attributo `async`.\n\nExample: Stili e script\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nStampa l'URL di un file statico nella sua cartella, senza tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file. |\n\nReturns: `String` L'URL.\n\nOgni comando usa la sua cartella dalla configurazione: `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/`, e `public` la radice. Un nome che inizia con `/` viene preso dalla radice. L'URL rispetta il tema e `default_root`.\n\nExample: URL\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nStampa il titolo e i meta tag della pagina, oppure li imposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | Il titolo. |\n| `description` | `String` | no |  | La descrizione. |\n| `keywords` | `String|Array` | no |  | Parole chiave. |\n| `image` | `String` | no |  | Un'immagine per i social network, un URL assoluto o un file in `/img/`. |\n\nReturns: `String` Tag HTML, o una stringa vuota quando imposta i valori.\n\nSenza argomenti stampa `<title>`, i meta tag description e keywords, e `og:image` e `twitter:image` quando è impostata un'immagine. Con argomenti imposta i valori e non stampa nulla. Il titolo riceve ` - ` e `CONF.name` alla fine, a meno che `allow_custom_titles` sia `true`. Per cambiare l'output, sostituisci `DEF.onMeta`.\n\nExample: Impostare nella vista, stampare nel layout\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nStampa o imposta il titolo della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Il titolo. |\n\nReturns: `String` Il titolo, o una stringa vuota quando lo imposta.\n\n`@{title(value)}` imposta il titolo e non stampa nulla; `@{title2(value)}` aggiunge in coda al titolo corrente. `@{title}` stampa solo il titolo. Il valore viene codificato in HTML quando viene impostato, quindi `@{!title}` lo stampa senza codificarlo due volte. Per stampare l'intero tag `<title>`, usa `@{meta}`.\n\nExample: Titolo\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nImpostano la descrizione, le parole chiave o l'autore della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | Il valore. |\n\nReturns: `String` Il valore, o una stringa vuota quando lo impostano.\n\nCon un argomento impostano il valore e non stampano nulla. `@{description}`, `@{keywords}` e `@{author}` stampano il valore. `@{meta}` stampa la descrizione e le parole chiave; `@{import('head')}` stampa l'autore (o `CONF.author`). Le parole chiave possono essere un array.\n\nExample: Valori meta\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nAggiunge CSS, JavaScript o HTML all'head della pagina, oppure lo stampa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Un nome di file, un URL o HTML. |\n\nReturns: `String` HTML, o una stringa vuota quando aggiunge.\n\nCon argomenti aggiunge i tag e non stampa nulla: i file `.css` diventano `<link>`, i file `.js` `<script>`, e un valore che inizia con `<` viene aggiunto come HTML. Ogni valore viene aggiunto una sola volta. `@{head}` (o `@{import('head')}`) stampa il meta tag dell'autore e tutto ciò che è stato aggiunto.\n\nExample: Aggiungere da una vista\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Stampare nel layout\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nAggiunge contenuto a un punto con nome, oppure lo stampa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del punto. |\n| `value` | `String` | no |  | Un percorso di file o HTML. |\n\nReturns: `String` Il contenuto, o una stringa vuota quando aggiunge.\n\nCon dei valori li aggiunge in coda e non stampa nulla: i file `.js` e `.mjs` diventano `<script>`, i file `.css` `<link>`, tutto il resto viene aggiunto così com'è. Con il solo nome stampa il contenuto. I valori non vengono risolti nelle cartelle statiche, quindi scrivi i percorsi completi.\n\nExample: Punto per gli script\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSerializza un valore in JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | Il valore da serializzare. |\n| `id` | `String` | no |  | L'id di un elemento `<script>`. |\n| `beautify` | `Boolean` | no | `false` | Indenta il JSON. |\n\nReturns: `String` JSON, o un elemento `<script>`.\n\nCon `id` il JSON viene racchiuso in `<script type=\"application/json\" id=\"...\">`, così il codice lato client può leggerlo. L'output non viene codificato in HTML.\n\nExample: Dati per il browser\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nScrive elementi `<option>` per un `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | Le opzioni. |\n| `selected` | `Any` | no |  | Il valore dell'opzione selezionata. |\n| `name` | `String` | no | `name` | La proprietà con il testo. |\n| `value` | `String` | no | `value` | La proprietà con il valore. |\n| `disabled` | `String` | no | `disabled` | La proprietà che disabilita un'opzione. |\n\nReturns: `String` HTML.\n\nPer un array di oggetti, `name` è la proprietà del testo (predefinita `name`) e `value` la proprietà del valore (predefinita: la stessa di `name` quando indichi un nome, altrimenti `value`). La proprietà `disabled` disabilita un'opzione. Per un array di stringhe o numeri, ogni elemento è sia testo sia valore. Per un oggetto, le chiavi sono i valori e i valori sono i testi. L'opzione uguale a `selected` riceve `selected=\"selected\"`. Testi e valori vengono codificati.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Stringhe\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nStampano un attributo HTML quando una condizione è vera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Quando è truthy, l'attributo viene stampato. |\n\nReturns: `String` L'attributo o una stringa vuota.\n\nStampano ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` o ` readonly=\"readonly\"`, con uno spazio davanti, oppure nulla.\n\nExample: Attributi\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nScrive un `<input>` per un campo del modello.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `attributes` | `Object` | no |  | Attributi aggiuntivi, ad es. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` Un elemento `<input>`.\n\nIl modello della vista viene aggiunto automaticamente: il valore dell'input è `model[name]`, codificato. Gli attributi vengono aggiunti all'elemento; `required`, `disabled`, `readonly` e `autofocus` vengono scritti come attributi booleani, e `autocomplete: true` scrive `autocomplete=\"on\"` (qualsiasi altro valore truthy scrive `off`). `value` negli attributi viene usato quando il modello non ha quel campo.\n\nExample: Campi del form\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nScrive un `<input>` di qualsiasi tipo per un campo del modello.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il tipo dell'input. |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `attributes` | `Object` | no |  | Attributi aggiuntivi. |\n\nReturns: `String` Un elemento `<input>`.\n\nFunziona come `@{text()}` con il tipo che scegli, per esempio `email`, `number` o `date`.\n\nExample: Email\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nScrivono una checkbox o un radio button per un campo del modello.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `value` | `String` | yes |  | Solo radio: il valore di questo pulsante. |\n| `label` | `String|Object` | no |  | Un'etichetta, o attributi aggiuntivi (`label` è uno di questi). |\n\nReturns: `String` Un `<input>`, racchiuso in `<label>` quando c'è un'etichetta.\n\nUna checkbox è selezionata quando `model[name]` è `true`, `1`, `'true'` o `'on'`; il suo valore è `1`. Un radio button è selezionato quando `model[name]` è uguale a `value`. Una stringa come ultimo argomento è un'etichetta: l'input viene racchiuso in `<label>` con il testo in uno `<span>`. `@{radio()}` richiede quest'ultimo argomento, un'etichetta o un oggetto.\n\nExample: Checkbox e radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nScrive una `<textarea>` con il valore di un campo del modello.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo. |\n| `attributes` | `Object` | no |  | Attributi aggiuntivi, ad es. `{ rows: 5 }`. |\n\nReturns: `String` Un elemento `<textarea>`.\n\nIl contenuto è `model[name]`, oppure `value` dagli attributi. Il contenuto non viene codificato, quindi codifica prima i valori digitati dagli utenti.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nScrive un `<img>` per un file in `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il file dell'immagine. |\n| `width` | `Number|Object` | no |  | La larghezza, o un oggetto con tutti gli attributi. |\n| `height` | `Number` | no |  | L'altezza. |\n| `alt` | `String` | no |  | Il testo alternativo. |\n| `class` | `String` | no |  | Classi CSS. |\n\nReturns: `String` Un elemento `<img>`.\n\nAl posto degli argomenti puoi passare un oggetto: `{ width, height, alt, class, style }`. `alt` viene codificato.\n\nExample: Immagine\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nStampa un token CSRF per la richiesta corrente.\n\nReturns: `String` Il token.\n\nUna route con il flag `csrf` controlla il token nell'intestazione `X-CSRF-Token` o nel parametro di query `csrf`. Richiede `secret_csrf` nella configurazione. Il token viene creato da `DEF.onCSRFcreate(req)` e controllato da `DEF.onCSRFcheck(req)`.\n\nExample: Form e AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nStampa la query string corrente, facoltativamente con una chiave modificata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Il parametro da impostare. |\n| `value` | `Any` | no |  | Il suo nuovo valore. |\n\nReturns: `String` Una query string.\n\nIl risultato inizia con `?`, oppure è vuoto. Usalo per la paginazione e per i filtri che mantengono gli altri parametri.\n\nExample: Paginazione\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nStampa il percorso della richiesta corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Aggiunge il protocollo e l'host. |\n\nReturns: `String` L'URL.\n\n`@{url(true)}` stampa l'indirizzo completo con il protocollo e l'host.\n\nExample: Link canonico\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nPassa un blocco renderizzato della vista a `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome che dice alla tua funzione cosa fare. |\n\nLa funzione riceve il nome, l'HTML del blocco e il modello, e restituisce l'HTML da stampare. Per impostazione predefinita restituisce l'HTML invariato; sostituiscila per usare un altro linguaggio di template o un parser Markdown. Il blocco non viene minificato.\n\nExample: Un hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: In una vista\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nDisattiva la minificazione di una vista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` o `all`. |\n\nPer impostazione predefinita Total.js minifica l'HTML di una vista e il suo CSS e JavaScript inline. Metti questo comando in un punto qualsiasi della vista per mantenere una parte così come è scritta: `html`, `css` (o `style`), `js` (o `script`, `javascript`) oppure `all`. I commenti HTML vengono rimossi in ogni caso, tranne i commenti condizionali.\n\nExample: Mantenere l'HTML così com'è scritto\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nRenderizza una vista con il suo layout e la invia come risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | Il nome della vista senza `.html`. |\n| `model` | `Object` | no |  | Il modello della vista. |\n| `headers` | `Object` | no |  | Intestazioni HTTP aggiuntive. |\n| `partial` | `Boolean` | no | `false` | `true` restituisce l'HTML invece di inviarlo. |\n\nReturns: `Controller|String` Il controller, o l'HTML quando `partial` è `true`.\n\nSenza `name` la vista prende il nome dall'ultima parte dell'URL (`index` per `/`). Il nome viene cercato prima in `views/<controller>/`, poi in `views/`; i prefissi `~`, `=theme/`, `@`, `#plugin/` e `.` cambiano questo comportamento (vedi la guida). Con `partial` impostato a `true`, il metodo restituisce l'HTML invece di inviarlo; il layout viene comunque applicato, a meno che tu non imposti `controller.layout('')`. Quando la vista non esiste, la risposta è un errore 500.\n\nExample: Renderizzare una vista\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Ottenere l'HTML\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nCompila una stringa HTML come vista, la renderizza e la invia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il template. |\n| `model` | `Object` | no |  | Il modello. |\n| `headers` | `Object` | no |  | Intestazioni HTTP aggiuntive. |\n| `partial` | `Boolean` | no | `false` | `true` restituisce l'HTML invece di inviarlo. |\n| `key` | `String` | no |  | Una chiave di cache per il template compilato. |\n\nReturns: `Controller|String` Il controller, o l'HTML quando `partial` è `true`.\n\nLa stringa usa la stessa sintassi di un file di vista. Con `key` il template compilato viene tenuto in memoria in modalità release.\n\nExample: Template da un database\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nImposta il layout per la vista successiva.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del layout, o `''`. |\n\nReturns: `Controller` Il controller.\n\nIl valore predefinito è `default_layout` dalla configurazione (`layout`). Una stringa vuota renderizza senza layout. La vista può cambiarlo di nuovo con `@{layout()}`.\n\nExample: Layout di amministrazione\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nImposta il titolo e i meta tag che `@{meta}` stampa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Il titolo. |\n| `description` | `String` | no |  | La descrizione. |\n| `keywords` | `String|Array` | no |  | Parole chiave. |\n| `image` | `String` | no |  | Un'immagine per i social network. |\n\nReturns: `Controller` Il controller.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` e `controller.author()` impostano un valore ciascuno.\n\nExample: Meta tag\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nAggiunge contenuto a una sezione della vista, oppure lo legge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della sezione. |\n| `value` | `String` | no |  | L'HTML da aggiungere. |\n| `replace` | `Boolean` | no | `false` | Sostituisce il contenuto invece di aggiungerlo in coda. |\n\nReturns: `Controller|String` Il controller, o il contenuto quando legge.\n\nSenza `value` restituisce il contenuto. Altrimenti aggiunge in coda il valore, o sostituisce il contenuto quando `replace` è `true`. Stampa la sezione con `@{section('name')}`.\n\nExample: Sezione da un controller\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nUn oggetto condiviso dalla vista, dalle sue viste parziali e dal layout.\n\nNella vista è `repository` o `R`.\n\nExample: Passare un valore al layout\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRenderizza una vista al di fuori di una richiesta e restituisce l'HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista. |\n| `model` | `Object` | no |  | Il modello. |\n| `layout` | `String` | no | `''` | Un layout. |\n| `repository` | `Object` | no |  | Il repository. |\n| `language` | `String` | no |  | La lingua per `@(...)`. |\n\nReturns: `String` L'HTML.\n\nNon c'è layout a meno che tu non ne indichi uno. Usalo per email, file o risposte costruite a mano. Un nome come `=theme/view` legge la vista da un tema.\n\nExample: Renderizzare in una stringa\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nCompila una stringa HTML come vista, al di fuori di una richiesta, e restituisce l'HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Il template. |\n| `model` | `Object` | no |  | Il modello. |\n| `layout` | `String` | no | `''` | Un layout. |\n| `repository` | `Object` | no |  | Il repository. |\n| `language` | `String` | no |  | La lingua per `@(...)`. |\n\nReturns: `String` L'HTML.\n\nÈ `VIEW()` per un template in una stringa, per esempio da un database. La stringa usa la stessa sintassi di un file di vista. Non c'è layout a meno che tu non ne indichi uno, e `layout` e `repository` possono scambiarsi di posto. Il template viene compilato a ogni chiamata.\n\nExample: Template da una stringa\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabUBm4XU60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/views/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Pohľady","summary":"Všetky príkazy view enginu a metódy kontroléra, ktoré renderujú pohľady.","markdown":"---\ntitle: \"Pohľady\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/views/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Pohľady\n\n> Všetky príkazy view enginu a metódy kontroléra, ktoré renderujú pohľady.\n\nPohľady sú súbory `.html` v `views/` s príkazmi v `@{...}` a preloženým textom v `@(...)`. Príručka [Pohľady](../../guides/views/) vysvetľuje, ako spolu fungujú; táto stránka uvádza každý príkaz a metódy kontroléra pre pohľady.\n\n## API\n\n### @{expression}\n\nType: `command`\n\nVypíše hodnotu JavaScript výrazu, zakódovanú pre HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | JavaScript výraz. |\n\nReturns: `String` Zakódovaná hodnota.\n\nFunguje akýkoľvek výraz: vlastnosť modelu, volanie metódy, aritmetika. `null` a `undefined` vypíšu prázdny reťazec. Znaky `<`, `>`, `&`, `\"` a `'` sa zakódujú. Ak chceš hodnotu vypísať bez kódovania, použi `@{!expression}`.\n\nText, ktorý začína `@{{`, nie je príkaz a zostane na stránke tak, ako je napísaný.\n\nExample: Hodnoty modelu\n```html\n<h1>@{model.name}</h1>\n<p>@{model.price.format(2)} EUR</p>\n<p>@{model.items.length} items</p>\n```\n\n### @{!expression}\n\nType: `command`\n\nVypíše hodnotu výrazu bez HTML kódovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expression` | `Any` | yes |  | JavaScript výraz. |\n\nReturns: `String` Nespracovaná hodnota.\n\nPouži ho pre HTML, ktorému dôveruješ, napríklad obsah, ktorý si už vyčistil. Nikdy ho nepoužívaj pre text, ktorý zadali používatelia.\n\nExample: Nespracované HTML\n```html\n<article>@{!model.html}</article>\n```\n\n### @{model.property}\n\nType: `command`\n\nModel, ktorý pohľadu odovzdá `controller.view(name, model)`.\n\n`M` je kratší názov toho istého objektu. Layout dostane rovnaký model ako pohľad. Príkaz, ktorý priraďuje hodnotu, napríklad `@{model.count = 0}`, nevypíše nič.\n\nExample: Kontrolér a pohľad\n```js\nfunction detail(id) {\n\tthis.view('detail', { id: id, name: 'Apple' });\n}\n```\n\nExample: V pohľade\n```html\n<h1>@{model.name}</h1>\n<small>@{M.id}</small>\n```\n\n### @{repository.property}\n\nType: `command`\n\nObjekt, ktorý počas jednej požiadavky zdieľa pohľad, jeho čiastkové pohľady a layout.\n\nV JavaScripte je to `controller.repository`. `R` je kratší názov. Hodnoty nastavené v pohľade sú viditeľné v layoute, pretože pohľad sa renderuje ako prvý.\n\nExample: Nastavenie v pohľade, čítanie v layoute\n```html\n@{repository.page = 'products'}\n\n<!-- layout.html -->\n<body class=\"@{repository.page}\">\n```\n\n### @{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}\n\nType: `command`\n\nHodnoty aktuálnej požiadavky, ktoré môže použiť každý pohľad.\n\n| Premenná | Hodnota |\n| --- | --- |\n| `user` | Prihlásený používateľ (`controller.user`) |\n| `session` | Session (`controller.session`) |\n| `query` | Query string ako objekt |\n| `body` | Telo požiadavky; samotné `@{body}` je v layoute vyrenderovaný pohľad |\n| `config`, `CONF` | Konfigurácia |\n| `language` | Jazyk požiadavky |\n| `url` | Cesta požiadavky |\n| `files` | Nahrané súbory |\n| `mobile` | `true` pre mobilné zariadenie |\n| `controller` | Kontrolér |\n\nKódujú sa ako akýkoľvek výraz; pre nespracovanú hodnotu daj pred ne `!`.\n\nExample: Hodnoty požiadavky\n```html\n@{if user}\n\t<p>Hello @{user.name}</p>\n@{fi}\n<input type=\"search\" name=\"q\" value=\"@{query.q}\" />\n```\n\n### @{'%key'}\n\nType: `command`\n\nVypíše hodnotu z konfigurácie, zakódovanú pre HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč konfigurácie. |\n\nHodnota sa načíta pri kompilácii pohľadu. `@{config.key}` a `@{CONF.key}` vypíšu tú istú hodnotu. Cesta v úvodzovkách bez `%`, napríklad `@{'/css/default.css'}`, vypíše URL daného statického súboru.\n\nExample: Názov aplikácie\n```html\n<footer>@{'%name'}</footer>\n<footer>@{CONF.name}</footer>\n```\n\n### @{if condition} ... @{else if condition} ... @{else} ... @{fi}\n\nType: `command`\n\nRenderuje časť pohľadu, iba keď je podmienka splnená.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | JavaScript výraz. |\n\nPodmienka je JavaScript. `@{else if}` a `@{else}` sú voliteľné. Blok uzavri pomocou `@{fi}` alebo `@{endif}`.\n\nExample: Podmienka\n```html\n@{if model.items.length}\n\t<p>@{model.items.length} products</p>\n@{else if model.loading}\n\t<p>Loading…</p>\n@{else}\n\t<p>No products.</p>\n@{fi}\n```\n\n### @{foreach item in source} ... @{end}\n\nType: `command`\n\nRenderuje časť pohľadu pre každú položku poľa alebo objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `String` | yes |  | Názov premennej pre aktuálnu položku. |\n| `source` | `Array|Object` | yes |  | Výraz, cez ktorý sa iteruje. |\n\n`index` je pozícia aktuálnej položky od `0`. Prázdny zdroj nevypíše nič. Keď je zdrojom objekt, zmení sa na pole `{ key, value }`. Funguje aj `@{foreach var item in source}`. `@{continue}` a `@{break}` preskočia položku alebo ukončia cyklus.\n\nExample: Pole\n```html\n<ul>\n\t@{foreach item in model.items}\n\t\t<li>@{index + 1}. @{item.name}</li>\n\t@{end}\n</ul>\n```\n\nExample: Objekt\n```html\n@{foreach item in model.prices}\n\t<li>@{item.key}: @{item.value}</li>\n@{end}\n```\n\nExample: Preskočenie položiek\n```html\n@{foreach item in model.items}\n\t@{if item.hidden}\n\t\t@{continue}\n\t@{fi}\n\t<li>@{item.name}</li>\n@{end}\n```\n\n### @{body}\n\nType: `command`\n\nVypíše vyrenderovaný pohľad vnútri layoutu.\n\nPouži ho v layoute. S vlastnosťou, `@{body.name}`, číta namiesto toho telo požiadavky.\n\nExample: Layout\n```html\n<!DOCTYPE html>\n<html>\n<head>\n\t@{import('meta', 'head', 'default.css')}\n</head>\n<body>\n\t@{body}\n</body>\n</html>\n```\n\n### @{layout(name)}\n\nType: `command`\n\nZmení layout aktuálneho pohľadu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov layoutu alebo `''` pre žiadny layout. |\n\nReturns: `String` Prázdny reťazec.\n\nPredvolený layout je `layout` (`default_layout` v konfigurácii). Prázdny reťazec vyrenderuje pohľad bez layoutu. Layouty sa vždy hľadajú od koreňa `views/`.\n\nExample: Iný layout\n```html\n@{layout('admin')}\n\n<h1>Dashboard</h1>\n```\n\nExample: Bez layoutu\n```html\n@{layout('')}\n```\n\n### @{view(name, [model], [expire], [key])}\n\nType: `command`\n\nVyrenderuje na danom mieste čiastkový pohľad, bez layoutu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pohľadu. |\n| `model` | `Object` | no |  | Model čiastkového pohľadu. |\n| `expire` | `String` | no |  | Ako dlho držať výstup v cache, napr. `'5 minutes'`. |\n| `key` | `String` | no |  | Kľúč, ktorý robí záznam v cache jedinečným, napr. jazyk. |\n\nReturns: `String` Vyrenderované HTML.\n\nNázov sa určí rovnako ako v `controller.view()`. Čiastkový pohľad nedostane model rodiča automaticky; odovzdaj mu ho. S `expire` sa výstup uloží do cache na daný čas pod názvom a kľúčom `key`.\n\nExample: Čiastkový pohľad pre každú položku\n```html\n@{foreach item in model.items}\n\t@{view('partials/product', item)}\n@{end}\n```\n\nExample: Menu v cache\n```html\n@{view('menu', model.menu, '10 minutes', language)}\n```\n\n### @{view_compile(body, [model], [key])}\n\nType: `command`\n\nSkompiluje HTML reťazec ako pohľad a vyrenderuje ho na danom mieste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Šablóna s rovnakou syntaxou ako pohľad. |\n| `model` | `Object` | no |  | Model. |\n| `key` | `String` | no |  | Kľúč cache pre skompilovanú šablónu. |\n\nReturns: `String` Vyrenderované HTML.\n\nHodí sa pre šablóny uložené v databáze. Výsledok nemá layout. S `key` sa skompilovaná šablóna v režime release drží v pamäti.\n\nExample: Šablóna z modelu\n```html\n@{view_compile(model.template, model.data)}\n```\n\n### @{section name} ... @{end}  /  @{section('name')}\n\nType: `command`\n\nZapíše HTML v pohľade a vypíše ho inde, zvyčajne v layoute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov sekcie. |\n\n`@{section name}` … `@{end}` uloží svoj obsah a nevypíše nič; bloky s rovnakým názvom sa spoja. `@{section('name')}` vypíše uložený obsah alebo nič. Obsah sa drží v repository, takže ho vypíš až po vyrenderovaní pohľadu: v layoute.\n\nExample: Skripty jednej stránky\n```html\n@{section scripts}\n\t<script src=\"/js/chart.js\"></script>\n@{end}\n\n<h1>Statistics</h1>\n```\n\nExample: V layoute\n```html\n@{body}\n\t@{section('scripts')}\n</body>\n```\n\n### @{helper name(arguments)} ... @{end}\n\nType: `command`\n\nDefinuje helper vnútri pohľadu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov helpera. |\n| `arguments` | `String` | yes |  | Názvy argumentov, ako v JavaScript funkcii. |\n\nHelper existuje iba v tomto pohľade. Volaj ho jeho názvom; jeho výstup sa znova nekóduje. Pre helpery zdieľané všetkými pohľadmi použi `DEF.helpers`.\n\nExample: Helper v pohľade\n```html\n@{helper badge(text, color)}\n\t<span class=\"badge badge-@{color}\">@{text}</span>\n@{end}\n\n@{badge('New', 'green')}\n@{badge('Sale', 'red')}\n```\n\n### DEF.helpers.name = function(...args) {}\n\nType: `property`\n\nDefinuje helpery pohľadov dostupné vo všetkých pohľadoch.\n\nFunkcie pridaj pred kompiláciou pohľadov, napríklad v `definitions/`. V pohľade volaj helper jeho názvom: `@{name(arguments)}`; fungujú aj `@{helpers.name(arguments)}` a `@{helper('name', arguments)}`. Vnútri funkcie je `this` kontrolér. Vrátená hodnota sa vypíše bez kódovania.\n\nExample: Definícia\n```js\n// definitions/helpers.js\nDEF.helpers.price = function(value, currency) {\n\treturn value.format(2) + ' ' + (currency || 'EUR');\n};\n\nDEF.helpers.active = function(path) {\n\treturn this.url === path ? ' class=\"active\"' : '';\n};\n```\n\nExample: Použitie\n```html\n<span>@{price(item.price, 'USD')}</span>\n<a href=\"/products/\"@{active('/products/')}>Products</a>\n```\n\n### @(Text)\n\nType: `command`\n\nOznačí text na preklad; nahradí sa pri kompilácii pohľadu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Text v predvolenom jazyku alebo `#key`. |\n\nText sa preloží do jazyka kontroléra (`controller.language`, ktorý pochádza z `DEF.onLocale`). Preklad sa načíta zo súboru zdrojov daného jazyka pod kľúčom vytvoreným z hashu textu; keď preklad neexistuje, zostane pôvodný text. `@(#key)` načíta `key` priamo zo zdroja. Vnútri úvodzoviek sa úvodzovky v preklade escapujú. Každý jazyk dostane vlastný skompilovaný pohľad.\n\nExample: Preložený text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#footer_note)</p>\n```\n\n### @{resource([name], key)}\n\nType: `command`\n\nVypíše hodnotu zo súboru zdrojov, zakódovanú pre HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Súbor zdrojov bez prípony. |\n| `key` | `String` | yes |  | Kľúč. |\n\nReturns: `String` Hodnota alebo prázdny reťazec.\n\nBez `name` sa hodnota berie z `default.resource`. Keď v inom súbore kľúč chýba, použije sa hodnota z `default.resource`. `@{!resource(...)}` ju vypíše nespracovanú.\n\nExample: Hodnoty zdrojov\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource('en', 'welcome')}</p>\n```\n\n### @{import(file1, [file2], ...)}\n\nType: `command`\n\nZapíše HTML tagy pre statické súbory a pre hlavičku stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Názov súboru alebo jedno z kľúčových slov. Toľko, koľko potrebuješ. |\n\nReturns: `String` HTML tagy.\n\nKaždý argument je jedno z nasledujúcich:\n\n| Argument | Výstup |\n| --- | --- |\n| `'meta'` | Titulok a meta tagy, pozri `@{meta}` |\n| `'head'` | Meta tag autora a tagy pridané cez `@{head()}` |\n| `'file.css'` | `<link rel=\"stylesheet\">` z `/css/` |\n| `'file.js'` | `<script>` z `/js/` |\n| `'favicon.ico'`, `'favicon.png'` | Odkaz na ikonu |\n| obrázok alebo video | Jeho URL |\n| `'a.css + b.css'` | Jeden zlúčený súbor so všetkými |\n| `'manifest'` | `<link rel=\"manifest\">` |\n| `'livereload'` | Skript pre live reload, iba v režime debug |\n\nNázov, ktorý začína `/`, alebo úplná URL sa použije tak, ako je. `!` pred súborom vypíše iba jeho URL. Výstup sa ukladá do cache pre každý súbor.\n\nExample: Hlavička layoutu\n```html\n<head>\n\t<meta charset=\"utf-8\" />\n\t@{import('meta', 'head', 'default.css', 'default.js', 'favicon.ico')}\n</head>\n```\n\nExample: Zlúčené súbory\n```html\n@{import('ui.css + default.css', 'ui.js + default.js')}\n```\n\n### @{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}\n\nType: `command`\n\nZapíšu tagy `<link rel=\"stylesheet\">` pre CSS súbory alebo tagy `<script>` pre JavaScript súbory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `file` | `String` | yes |  | Súbor. Toľko, koľko potrebuješ. |\n\nReturns: `String` HTML tagy.\n\nRelatívne názvy sa berú z `/css/` (`static_url_style`) a `/js/` (`static_url_script`). V `@{js()}` začni názov textom `async `, ak chceš pridať atribút `async`.\n\nExample: Štýly a skripty\n```html\n@{css('default.css', 'print.css')}\n@{js('default.js', 'async stats.js')}\n```\n\n### @{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}\n\nType: `command`\n\nVypíše URL statického súboru v jeho priečinku, bez tagu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru. |\n\nReturns: `String` URL.\n\nKaždý príkaz používa svoj priečinok z konfigurácie: `/js/`, `/css/`, `/img/`, `/videos/`, `/fonts/`, `/download/` a `public` koreň. Názov, ktorý začína `/`, sa berie od koreňa. URL rešpektuje tému a `default_root`.\n\nExample: URL adresy\n```html\n<img src=\"@{public_image('logo.png')}\" alt=\"Logo\" />\n<script src=\"@{public_js('app.js')}\"></script>\n```\n\n### @{meta}  /  @{meta(title, [description], [keywords], [image])}\n\nType: `command`\n\nVypíše titulok a meta tagy stránky, alebo ich nastaví.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | no |  | Titulok. |\n| `description` | `String` | no |  | Popis. |\n| `keywords` | `String|Array` | no |  | Kľúčové slová. |\n| `image` | `String` | no |  | Obrázok pre sociálne siete, absolútna URL alebo súbor v `/img/`. |\n\nReturns: `String` HTML tagy, alebo prázdny reťazec pri nastavovaní.\n\nBez argumentov vypíše `<title>`, meta tagy description a keywords a tiež `og:image` a `twitter:image`, keď je nastavený obrázok. S argumentmi nastaví hodnoty a nevypíše nič. Titulok dostane na koniec ` - ` a `CONF.name`, pokiaľ `allow_custom_titles` nie je `true`. Ak chceš zmeniť výstup, nahraď `DEF.onMeta`.\n\nExample: Nastavenie v pohľade, výpis v layoute\n```html\n@{meta(model.name, model.summary, model.tags, model.picture)}\n\n<!-- layout.html -->\n<head>\n\t@{meta}\n</head>\n```\n\n### @{title}  /  @{title(value)}  /  @{title2(value)}\n\nType: `command`\n\nVypíše alebo nastaví titulok stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Titulok. |\n\nReturns: `String` Titulok, alebo prázdny reťazec pri nastavovaní.\n\n`@{title(value)}` nastaví titulok a nevypíše nič; `@{title2(value)}` pripojí text k aktuálnemu titulku. `@{title}` vypíše samotný titulok. Hodnota sa pri nastavení zakóduje pre HTML, takže `@{!title}` ju vypíše bez dvojitého kódovania. Ak chceš vypísať celý tag `<title>`, použi `@{meta}`.\n\nExample: Titulok\n```html\n@{title(model.name)}\n\n<h1>@{!title}</h1>\n```\n\n### @{description(value)} @{keywords(value)} @{author(value)}\n\nType: `command`\n\nNastaví popis, kľúčové slová alebo autora stránky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array` | no |  | Hodnota. |\n\nReturns: `String` Hodnota, alebo prázdny reťazec pri nastavovaní.\n\nS argumentom nastavia hodnotu a nevypíšu nič. `@{description}`, `@{keywords}` a `@{author}` vypíšu hodnotu. `@{meta}` vypíše popis a kľúčové slová; `@{import('head')}` vypíše autora (alebo `CONF.author`). Kľúčové slová môžu byť pole.\n\nExample: Meta hodnoty\n```html\n@{description('Fresh apples from our farm')}\n@{keywords(['apples', 'fruit'])}\n@{author('Peter')}\n```\n\n### @{head}  /  @{head(value1, [value2], ...)}\n\nType: `command`\n\nPridá CSS, JavaScript alebo HTML do hlavičky stránky, alebo ich vypíše.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Názov súboru, URL alebo HTML. |\n\nReturns: `String` HTML, alebo prázdny reťazec pri pridávaní.\n\nS argumentmi pridá tagy a nevypíše nič: súbory `.css` sa zmenia na `<link>`, súbory `.js` na `<script>` a hodnota, ktorá začína `<`, sa pridá ako HTML. Každá hodnota sa pridá iba raz. `@{head}` (alebo `@{import('head')}`) vypíše meta tag autora a všetko pridané.\n\nExample: Pridanie z pohľadu\n```html\n@{head('chart.css', 'chart.js', '<meta name=\"robots\" content=\"noindex\" />')}\n```\n\nExample: Výpis v layoute\n```html\n<head>\n\t@{import('meta', 'head')}\n</head>\n```\n\n### @{place(name)}  /  @{place(name, value1, [value2], ...)}\n\nType: `command`\n\nPridá obsah na pomenované miesto, alebo ho vypíše.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov miesta. |\n| `value` | `String` | no |  | Cesta k súboru alebo HTML. |\n\nReturns: `String` Obsah, alebo prázdny reťazec pri pridávaní.\n\nS hodnotami ich pripojí a nevypíše nič: súbory `.js` a `.mjs` sa zmenia na `<script>`, súbory `.css` na `<link>`, čokoľvek iné sa pridá tak, ako je. Iba s názvom vypíše obsah. Hodnoty sa neprekladajú na statické priečinky, takže píš úplné cesty.\n\nExample: Miesto pre skripty\n```html\n@{place('scripts', '/js/chart.js')}\n\n<!-- layout.html -->\n@{place('scripts')}\n```\n\n### @{json(value, [id], [beautify])}\n\nType: `command`\n\nSerializuje hodnotu do JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Any` | yes |  | Hodnota na serializáciu. |\n| `id` | `String` | no |  | Id elementu `<script>`. |\n| `beautify` | `Boolean` | no | `false` | Odsadí JSON. |\n\nReturns: `String` JSON alebo element `<script>`.\n\nS `id` sa JSON zabalí do `<script type=\"application/json\" id=\"...\">`, aby ho mohol čítať kód na strane klienta. Výstup sa pre HTML nekóduje.\n\nExample: Dáta pre prehliadač\n```html\n@{json(model.items, 'items')}\n<script>\n\tvar items = JSON.parse(document.getElementById('items').innerHTML);\n</script>\n```\n\n### @{options(items, [selected], [name], [value], [disabled])}\n\nType: `command`\n\nZapíše elementy `<option>` pre `<select>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object` | yes |  | Možnosti. |\n| `selected` | `Any` | no |  | Hodnota vybranej možnosti. |\n| `name` | `String` | no | `name` | Vlastnosť s textom. |\n| `value` | `String` | no | `value` | Vlastnosť s hodnotou. |\n| `disabled` | `String` | no | `disabled` | Vlastnosť, ktorá zakáže možnosť. |\n\nReturns: `String` HTML.\n\nPre pole objektov je `name` vlastnosť s textom (predvolene `name`) a `value` vlastnosť s hodnotou (predvolene: rovnaká ako `name`, keď zadáš názov, inak `value`). Vlastnosť `disabled` možnosť zakáže. Pre pole reťazcov alebo čísel je každá položka zároveň textom aj hodnotou. Pre objekt sú kľúče hodnotami a hodnoty textami. Možnosť rovná `selected` dostane `selected=\"selected\"`. Texty a hodnoty sa kódujú.\n\nExample: Select\n```html\n<select name=\"country\">\n\t@{options(model.countries, model.country, 'name', 'id')}\n</select>\n```\n\nExample: Reťazce\n```html\n<select name=\"size\">\n\t@{options(['S', 'M', 'L'], 'M')}\n</select>\n```\n\n### @{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}\n\nType: `command`\n\nVypíše HTML atribút, keď je podmienka splnená.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Any` | yes |  | Keď je pravdivá, atribút sa vypíše. |\n\nReturns: `String` Atribút alebo prázdny reťazec.\n\nVypíšu ` checked=\"checked\"`, ` selected=\"selected\"`, ` disabled=\"disabled\"` alebo ` readonly=\"readonly\"` s medzerou na začiatku, alebo nič.\n\nExample: Atribúty\n```html\n<input type=\"checkbox\" name=\"newsletter\"@{checked(model.newsletter)} />\n<button@{disabled(!model.items.length)}>Order</button>\n```\n\n### @{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}\n\nType: `command`\n\nZapíše `<input>` pre pole modelu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `attributes` | `Object` | no |  | Ďalšie atribúty, napr. `{ placeholder: 'Name', required: true }`. |\n\nReturns: `String` Element `<input>`.\n\nModel pohľadu sa pridá automaticky: hodnota inputu je `model[name]`, zakódovaná. Atribúty sa pridajú k elementu; `required`, `disabled`, `readonly` a `autofocus` sa zapíšu ako boolovské atribúty a `autocomplete: true` zapíše `autocomplete=\"on\"` (akákoľvek iná pravdivá hodnota zapíše `off`). `value` v atribútoch sa použije, keď model také pole nemá.\n\nExample: Polia formulára\n```html\n<form method=\"POST\">\n\t@{text('name', { placeholder: 'Your name', required: true })}\n\t@{password('password')}\n\t@{hidden('id')}\n</form>\n```\n\n### @{input(type, name, [attributes])}\n\nType: `command` · Since: `0.0.53`\n\nZapíše `<input>` ľubovoľného typu pre pole modelu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Typ inputu. |\n| `name` | `String` | yes |  | Názov poľa. |\n| `attributes` | `Object` | no |  | Ďalšie atribúty. |\n\nReturns: `String` Element `<input>`.\n\nFunguje ako `@{text()}` s typom, ktorý si zvolíš, napríklad `email`, `number` alebo `date`.\n\nExample: E-mail\n```html\n@{input('email', 'email', { placeholder: 'you@example.com' })}\n```\n\n### @{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}\n\nType: `command`\n\nZapíše checkbox alebo prepínač (radio) pre pole modelu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `String` | yes |  | Iba pre radio: hodnota tohto prepínača. |\n| `label` | `String|Object` | no |  | Popisok alebo ďalšie atribúty (`label` je jedným z nich). |\n\nReturns: `String` `<input>`, zabalený do `<label>`, keď existuje popisok.\n\nCheckbox je zaškrtnutý, keď je `model[name]` `true`, `1`, `'true'` alebo `'on'`; jeho hodnota je `1`. Prepínač je zaškrtnutý, keď sa `model[name]` rovná `value`. Reťazec ako posledný argument je popisok: input sa zabalí do `<label>` s textom v `<span>`. `@{radio()}` tento posledný argument potrebuje, popisok alebo objekt.\n\nExample: Checkbox a radio\n```html\n@{checkbox('newsletter', 'Send me news')}\n@{radio('size', 'S', 'Small')}\n@{radio('size', 'L', 'Large')}\n```\n\n### @{textarea(name, [attributes])}\n\nType: `command`\n\nZapíše `<textarea>` s hodnotou poľa modelu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `attributes` | `Object` | no |  | Ďalšie atribúty, napr. `{ rows: 5 }`. |\n\nReturns: `String` Element `<textarea>`.\n\nObsah je `model[name]` alebo `value` z atribútov. Obsah sa nekóduje, preto hodnoty zadané používateľmi najprv zakóduj.\n\nExample: Textarea\n```html\n@{textarea('note', { rows: 5, placeholder: 'Note' })}\n```\n\n### @{image(name, [width], [height], [alt], [class])}\n\nType: `command`\n\nZapíše `<img>` pre súbor v `/img/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Súbor obrázka. |\n| `width` | `Number|Object` | no |  | Šírka, alebo objekt so všetkými atribútmi. |\n| `height` | `Number` | no |  | Výška. |\n| `alt` | `String` | no |  | Alternatívny text. |\n| `class` | `String` | no |  | CSS triedy. |\n\nReturns: `String` Element `<img>`.\n\nNamiesto argumentov môžeš odovzdať objekt: `{ width, height, alt, class, style }`. `alt` sa kóduje.\n\nExample: Obrázok\n```html\n@{image('logo.png', 120, 40, 'Logo')}\n@{image('photo.jpg', { alt: model.name, class: 'photo' })}\n```\n\n### @{csrf}\n\nType: `command` · Since: `0.0.37`\n\nVypíše CSRF token pre aktuálnu požiadavku.\n\nReturns: `String` Token.\n\nRouta s flagom `csrf` overí token v hlavičke `X-CSRF-Token` alebo v query parametri `csrf`. Potrebuje `secret_csrf` v konfigurácii. Token vytvára `DEF.onCSRFcreate(req)` a overuje `DEF.onCSRFcheck(req)`.\n\nExample: Formulár a AJAX\n```html\n<form method=\"POST\" action=\"/contact/?csrf=@{csrf}\">\n\t...\n</form>\n\n<meta name=\"csrf-token\" content=\"@{csrf}\" />\n```\n\n### @{href()}  /  @{href(key, value)}\n\nType: `command`\n\nVypíše aktuálny query string, voliteľne so zmeneným jedným kľúčom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Parameter, ktorý sa nastaví. |\n| `value` | `Any` | no |  | Jeho nová hodnota. |\n\nReturns: `String` Query string.\n\nVýsledok začína `?` alebo je prázdny. Použi ho pre stránkovanie a filtre, ktoré zachovávajú ostatné parametre.\n\nExample: Stránkovanie\n```html\n<a href=\"@{href('page', model.page + 1)}\">Next</a>\n```\n\n### @{url}  /  @{url(true)}\n\nType: `command`\n\nVypíše cestu aktuálnej požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `host` | `Boolean` | no | `false` | Pridá protokol a hostiteľa. |\n\nReturns: `String` URL.\n\n`@{url(true)}` vypíše úplnú adresu s protokolom a hostiteľom.\n\nExample: Kanonický odkaz\n```html\n<link rel=\"canonical\" href=\"@{url(true)}\" />\n```\n\n### @{compile name} ... @{end}\n\nType: `command`\n\nOdovzdá vyrenderovaný blok pohľadu do `DEF.onCompileView()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov, ktorý tvojej funkcii povie, čo má urobiť. |\n\nFunkcia dostane názov, HTML bloku a model a vráti HTML na výpis. Predvolene vráti HTML nezmenené; nahraď ju, ak chceš spustiť iný šablónovací jazyk alebo Markdown parser. Blok sa neminifikuje.\n\nExample: Hook\n```js\nDEF.onCompileView = function(name, html, model) {\n\treturn name === 'markdown' ? html.markdown() : html;\n};\n```\n\nExample: V pohľade\n```html\n@{compile markdown}\n# Title\nSome **text**.\n@{end}\n```\n\n### @{nocompress html|css|js|all}\n\nType: `command`\n\nVypne minifikáciu pohľadu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `html`, `css`, `js` alebo `all`. |\n\nTotal.js predvolene minifikuje HTML pohľadu a jeho inline CSS a JavaScript. Daj tento príkaz kamkoľvek do pohľadu, ak chceš jednu časť ponechať tak, ako je napísaná: `html`, `css` (alebo `style`), `js` (alebo `script`, `javascript`) alebo `all`. HTML komentáre sa odstránia v každom prípade, okrem podmienených komentárov.\n\nExample: Ponechanie HTML tak, ako je napísané\n```html\n@{nocompress html}\n<pre>\n\tIndented   text\n</pre>\n```\n\n### controller.view([name], [model], [headers], [partial])\n\nType: `method`\n\nVyrenderuje pohľad s jeho layoutom a pošle ho ako odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `from the URL` | Názov pohľadu bez `.html`. |\n| `model` | `Object` | no |  | Model pohľadu. |\n| `headers` | `Object` | no |  | Ďalšie HTTP hlavičky. |\n| `partial` | `Boolean` | no | `false` | `true` vráti HTML namiesto jeho odoslania. |\n\nReturns: `Controller|String` Kontrolér, alebo HTML, keď je `partial` `true`.\n\nBez `name` sa pohľad pomenuje podľa poslednej časti URL (`index` pre `/`). Názov sa hľadá najprv vo `views/<controller>/`, potom vo `views/`; prefixy `~`, `=theme/`, `@`, `#plugin/` a `.` to menia (pozri príručku). Keď je `partial` nastavené na `true`, metóda HTML vráti namiesto odoslania; layout sa aj tak použije, pokiaľ nenastavíš `controller.layout('')`. Keď pohľad neexistuje, odpoveďou je chyba 500.\n\nExample: Vyrenderovanie pohľadu\n```js\nexports.install = function() {\n\tROUTE('GET /products/', products);\n};\n\nfunction products() {\n\tthis.view('products', { items: [] });\n}\n```\n\nExample: Získanie HTML\n```js\nfunction preview() {\n\tthis.layout('');\n\tvar html = this.view('card', model, true);\n\tthis.json({ html: html });\n}\n```\n\n### controller.view_compile(body, [model], [headers], [partial], [key])\n\nType: `method`\n\nSkompiluje HTML reťazec ako pohľad, vyrenderuje ho a pošle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Šablóna. |\n| `model` | `Object` | no |  | Model. |\n| `headers` | `Object` | no |  | Ďalšie HTTP hlavičky. |\n| `partial` | `Boolean` | no | `false` | `true` vráti HTML namiesto jeho odoslania. |\n| `key` | `String` | no |  | Kľúč cache pre skompilovanú šablónu. |\n\nReturns: `Controller|String` Kontrolér, alebo HTML, keď je `partial` `true`.\n\nReťazec používa rovnakú syntax ako súbor pohľadu. S `key` sa skompilovaná šablóna v režime release drží v pamäti.\n\nExample: Šablóna z databázy\n```js\nfunction page() {\n\tthis.layout('');\n\tthis.view_compile('<h1>@{model.title}</h1>', { title: 'Hello' });\n}\n```\n\n### controller.layout(name)\n\nType: `method`\n\nNastaví layout pre nasledujúci pohľad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov layoutu alebo `''`. |\n\nReturns: `Controller` Kontrolér.\n\nPredvolená hodnota je `default_layout` z konfigurácie (`layout`). Prázdny reťazec renderuje bez layoutu. Pohľad ho môže znova zmeniť pomocou `@{layout()}`.\n\nExample: Layout administrácie\n```js\nfunction dashboard() {\n\tthis.layout('admin');\n\tthis.view('dashboard');\n}\n```\n\n### controller.meta(title, [description], [keywords], [image])\n\nType: `method`\n\nNastaví titulok a meta tagy, ktoré vypíše `@{meta}`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `title` | `String` | yes |  | Titulok. |\n| `description` | `String` | no |  | Popis. |\n| `keywords` | `String|Array` | no |  | Kľúčové slová. |\n| `image` | `String` | no |  | Obrázok pre sociálne siete. |\n\nReturns: `Controller` Kontrolér.\n\n`controller.title()`, `controller.description()`, `controller.keywords()` a `controller.author()` nastavia každá po jednej hodnote.\n\nExample: Meta tagy\n```js\nfunction detail() {\n\tthis.meta('Apple', 'Fresh apples', ['apple', 'fruit'], 'apple.jpg');\n\tthis.view('detail');\n}\n```\n\n### controller.section(name, [value], [replace])\n\nType: `method`\n\nPridá obsah do sekcie pohľadu, alebo ho načíta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov sekcie. |\n| `value` | `String` | no |  | HTML na pridanie. |\n| `replace` | `Boolean` | no | `false` | Nahradí obsah namiesto pripojenia. |\n\nReturns: `Controller|String` Kontrolér, alebo obsah pri čítaní.\n\nBez `value` vráti obsah. Inak hodnotu pripojí, alebo obsah nahradí, keď je `replace` `true`. Sekciu vypíš pomocou `@{section('name')}`.\n\nExample: Sekcia z kontroléra\n```js\nfunction stats() {\n\tthis.section('scripts', '<script src=\"/js/chart.js\"></script>');\n\tthis.view('stats');\n}\n```\n\n### controller.repository\n\nType: `property`\n\nObjekt, ktorý zdieľa pohľad, jeho čiastkové pohľady a layout.\n\nV pohľade je to `repository` alebo `R`.\n\nExample: Odovzdanie hodnoty do layoutu\n```js\nfunction products() {\n\tthis.repository.page = 'products';\n\tthis.view('products');\n}\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nVyrenderuje pohľad mimo požiadavky a vráti HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pohľadu. |\n| `model` | `Object` | no |  | Model. |\n| `layout` | `String` | no | `''` | Layout. |\n| `repository` | `Object` | no |  | Repository. |\n| `language` | `String` | no |  | Jazyk pre `@(...)`. |\n\nReturns: `String` HTML.\n\nLayout sa nepoužije, pokiaľ ho nepomenuješ. Použi to pre e-maily, súbory alebo odpovede zostavené ručne. Názov ako `=theme/view` načíta pohľad z témy.\n\nExample: Vyrenderovanie do reťazca\n```js\nvar html = VIEW('emails/order', order, null, null, 'en');\n```\n\n### VIEWCOMPILE(body, [model], [layout], [repository], [language])\n\nType: `method`\n\nSkompiluje HTML reťazec ako pohľad mimo požiadavky a vráti HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `String` | yes |  | Šablóna. |\n| `model` | `Object` | no |  | Model. |\n| `layout` | `String` | no | `''` | Layout. |\n| `repository` | `Object` | no |  | Repository. |\n| `language` | `String` | no |  | Jazyk pre `@(...)`. |\n\nReturns: `String` HTML.\n\nJe to `VIEW()` pre šablónu v reťazci, napríklad z databázy. Reťazec používa rovnakú syntax ako súbor pohľadu. Layout sa nepoužije, pokiaľ ho nepomenuješ, a `layout` a `repository` si môžu vymeniť miesta. Šablóna sa kompiluje pri každom volaní.\n\nExample: Šablóna z reťazca\n```js\nvar html = VIEWCOMPILE('<h1>@{model.title}</h1>', { title: 'Hello' });\n```\n","entries":[{"type":"command","name":"@{expression}","signature":"@{expression}","since":"","deprecated":false},{"type":"command","name":"@{!expression}","signature":"@{!expression}","since":"","deprecated":false},{"type":"command","name":"@{model}","signature":"@{model.property}","since":"","deprecated":false},{"type":"command","name":"@{repository}","signature":"@{repository.property}","since":"","deprecated":false},{"type":"command","name":"Built-in variables","signature":"@{user} @{session} @{query} @{body.field} @{config.key} @{language} @{url} @{controller}","since":"","deprecated":false},{"type":"command","name":"@{'%key'}","signature":"@{'%key'}","since":"","deprecated":false},{"type":"command","name":"@{if}","signature":"@{if condition} ... @{else if condition} ... @{else} ... @{fi}","since":"","deprecated":false},{"type":"command","name":"@{foreach}","signature":"@{foreach item in source} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{body}","signature":"@{body}","since":"","deprecated":false},{"type":"command","name":"@{layout()}","signature":"@{layout(name)}","since":"","deprecated":false},{"type":"command","name":"@{view()}","signature":"@{view(name, [model], [expire], [key])}","since":"","deprecated":false},{"type":"command","name":"@{view_compile()}","signature":"@{view_compile(body, [model], [key])}","since":"","deprecated":false},{"type":"command","name":"@{section}","signature":"@{section name} ... @{end}  /  @{section('name')}","since":"","deprecated":false},{"type":"command","name":"@{helper}","signature":"@{helper name(arguments)} ... @{end}","since":"","deprecated":false},{"type":"property","name":"DEF.helpers","signature":"DEF.helpers.name = function(...args) {}","since":"","deprecated":false},{"type":"command","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"command","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"command","name":"@{import()}","signature":"@{import(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{css()}","signature":"@{css(file1, [file2], ...)}  /  @{js(file1, [file2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{public_js()}","signature":"@{public_js(name)} @{public_css(name)} @{public_image(name)} @{public_video(name)} @{public_font(name)} @{public_download(name)} @{public(name)}","since":"","deprecated":false},{"type":"command","name":"@{meta}","signature":"@{meta}  /  @{meta(title, [description], [keywords], [image])}","since":"","deprecated":false},{"type":"command","name":"@{title}","signature":"@{title}  /  @{title(value)}  /  @{title2(value)}","since":"","deprecated":false},{"type":"command","name":"@{description()}","signature":"@{description(value)} @{keywords(value)} @{author(value)}","since":"","deprecated":false},{"type":"command","name":"@{head()}","signature":"@{head}  /  @{head(value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{place()}","signature":"@{place(name)}  /  @{place(name, value1, [value2], ...)}","since":"","deprecated":false},{"type":"command","name":"@{json()}","signature":"@{json(value, [id], [beautify])}","since":"","deprecated":false},{"type":"command","name":"@{options()}","signature":"@{options(items, [selected], [name], [value], [disabled])}","since":"","deprecated":false},{"type":"command","name":"@{checked()}","signature":"@{checked(condition)} @{selected(condition)} @{disabled(condition)} @{readonly(condition)}","since":"","deprecated":false},{"type":"command","name":"@{text()}","signature":"@{text(name, [attributes])} @{password(name, [attributes])} @{hidden(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{input()}","signature":"@{input(type, name, [attributes])}","since":"0.0.53","deprecated":false},{"type":"command","name":"@{checkbox()}","signature":"@{checkbox(name, [label|attributes])} @{radio(name, value, [label|attributes])}","since":"","deprecated":false},{"type":"command","name":"@{textarea()}","signature":"@{textarea(name, [attributes])}","since":"","deprecated":false},{"type":"command","name":"@{image()}","signature":"@{image(name, [width], [height], [alt], [class])}","since":"","deprecated":false},{"type":"command","name":"@{csrf}","signature":"@{csrf}","since":"0.0.37","deprecated":false},{"type":"command","name":"@{href()}","signature":"@{href()}  /  @{href(key, value)}","since":"","deprecated":false},{"type":"command","name":"@{url}","signature":"@{url}  /  @{url(true)}","since":"","deprecated":false},{"type":"command","name":"@{compile}","signature":"@{compile name} ... @{end}","since":"","deprecated":false},{"type":"command","name":"@{nocompress}","signature":"@{nocompress html|css|js|all}","since":"","deprecated":false},{"type":"method","name":"controller.view()","signature":"controller.view([name], [model], [headers], [partial])","since":"","deprecated":false},{"type":"method","name":"controller.view_compile()","signature":"controller.view_compile(body, [model], [headers], [partial], [key])","since":"","deprecated":false},{"type":"method","name":"controller.layout()","signature":"controller.layout(name)","since":"","deprecated":false},{"type":"method","name":"controller.meta()","signature":"controller.meta(title, [description], [keywords], [image])","since":"","deprecated":false},{"type":"method","name":"controller.section()","signature":"controller.section(name, [value], [replace])","since":"","deprecated":false},{"type":"property","name":"controller.repository","signature":"controller.repository","since":"","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"VIEWCOMPILE()","signature":"VIEWCOMPILE(body, [model], [layout], [repository], [language])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Configuration","summary":"The CONF object, every built-in config key and the functions for loading configuration.","markdown":"---\ntitle: Configuration\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuration\n\n> The CONF object, every built-in config key and the functions for loading configuration.\n\nThe configuration lives in the files `config`, `config-debug` and `config-release` in the root of the application, and in the global object `CONF`. The guide [Configuration](../../guides/configuration/) explains the syntax, the types and environment variables; this page lists the functions and the built-in keys with their defaults.\n\n## API\n\n### CONF\n\nType: `property`\n\nThe global object with the whole configuration of the application.\n\nReturns: `Object`\n\nTotal.js fills `CONF` with default values, then with `options.config` from the start script, and then with the values from `config` and `config-debug` or `config-release`. It is a plain object: read and assign keys as properties. Keys with a dot, like `security.txt`, need the bracket notation.\n\nYour own keys are stored the same way as the built-in ones. Values assigned in code are not saved to the files.\n\nExample: Read values\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: In a view\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nMerges new values into `CONF` at runtime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | The new values. |\n\n`value` can be:\n\n- an object, copied key by key into `CONF`;\n- a string in the config syntax, parsed with `String.parseConfig()`;\n- an array of items `{ id, type, value }` (`key` or `name` instead of `id`, `body` instead of `value`).\n\nFor arrays, `type` converts the value: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). A string value that starts with `hex ` is decoded from hex.\n\nA `root` key is copied to `default_root`, and `default_root` gets a leading and a trailing slash. Changing `mail_smtp` or `mail_smtp_options` clears the cached SMTP settings, and the TMS endpoint is refreshed.\n\nExample: Settings from a database\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: An object or a string\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Typed items\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true` when the application runs in debug mode.\n\nReturns: `Boolean`\n\nIn debug mode Total.js reads `config-debug` and `.env-debug`; otherwise `config-release` and `.env-release`.\n\nExample: Mode-specific code\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true` when the application runs in release mode.\n\nReturns: `Boolean`\n\nThe opposite of `DEBUG`. In release mode Total.js reads `config-release` and `.env-release`, and `default_response_maxage` is used for the `Cache-Control` header of static files.\n\nExample: Release only\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nParses text in the config syntax into an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Default values, copied into the result first. |\n| `onerr` | `Function` | no |  | `function(err, line)` called when an `object` value cannot be evaluated. Without it, an error is thrown. |\n\nReturns: `Object` The parsed values.\n\nEach `key : value` line becomes a property. The value starts two characters after the `:`, so keep a space after it. Lines starting with `#` or `//` are skipped. Types in brackets work as in the config file: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random`, and `config`, which copies the value of another `CONF` key. Without a type the value stays a string.\n\nExample: Parse settings\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nParses text in the `.env` syntax into an object.\n\nReturns: `Object` The parsed variables, all strings.\n\nEach `KEY=value` line becomes a property. Quotes around the value are removed, other values are trimmed, and `\\n` becomes a new line. Lines starting with `#` or `//` are skipped. Total.js uses it for the `.env` files.\n\nExample: Parse variables\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nFiles with environment variables, loaded before the config files.\n\nTotal.js reads `.env` from the root, then `.env-debug` or `.env-release`. Every variable goes into `process.env`, but a variable that already exists there is not replaced. Use the `(env)` type in the config to read a variable into a key.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nReturns the path to a file in the `configs` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name inside the directory. |\n\nReturns: `String` The absolute path.\n\nThe directory is set by `directory_configs` (default `/configs/`). Total.js does not load files from it; it is a place for your own configuration files.\n\nExample: Read a JSON file\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nThe name of the application.\n\nReturns: `String`\n\nUsed in the process title, the console header, the sender name of emails, page titles and the `x-app` header of Total API calls.\n\nDefault: `Total.js`.\n\nExample: In the config file\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nThe version of the application.\n\nReturns: `String`\n\nAlways kept as a string. Without `etag_version`, the version without dots and spaces is used as the ETag suffix of static files; change `etag_version` to make browsers download static files again. `author` holds the author, shown in the console header and used as the default author meta tag.\n\nDefault: `1.0.0`.\n\nExample: In the config file\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nThe public URL of the application.\n\nReturns: `String`\n\nUsed by the Total API logger as the application name and as the base URL for JSON schema references. Not set by default.\n\nExample: In the config file\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nThe key used by `ENCRYPT()` and `DECRYPT()`.\n\nReturns: `String`\n\nThe default value is a hash of the framework path, the machine and the Node.js versions, so it changes when you move the application. Set your own value when encrypted data must survive a move. Always kept as a string.\n\nExample: In the config file\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nA value that makes the generated `UID()` values unique for the application.\n\nReturns: `String`\n\nWithout a value Total.js computes it from `name`.\n\nExample: In the config file\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nEnables encryption of request and response bodies.\n\nReturns: `String`\n\nWhen set, the bodies of routes with the `encrypt` flag (and of WebSockets with encryption) are encrypted with this key. With `allow_static_encryption`, static files are encrypted too.\n\nDefault: `null`.\n\nExample: In the config file\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nEnables CSRF tokens.\n\nReturns: `String`\n\nThe key used to create and check CSRF tokens. Routes with the `csrf` flag are checked only when this key is set. `default_csrf_maxage` (default `30 minutes`) sets how long a token is valid.\n\nDefault: `null`.\n\nExample: In the config file\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nThe URL prefix when the application runs in a subdirectory.\n\nReturns: `String`\n\nTotal.js adds a leading and a trailing slash. The prefix is used for URLs of static files and in redirects, and removed from incoming URLs. `root` is an alias: when set, it is copied to `default_root`. Load it from an environment variable with `default_root (env) : APP_ROOT`.\n\nExample: In the config file\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nThe HTTP port.\n\nReturns: `Number|String`\n\nUsed when the start script does not set a port. `auto` takes `process.env.PORT`. Without any value the port is `8000`.\n\n`default_ip` sets the IP address (without a value, or with `auto`, the server listens on `0.0.0.0`) and `default_unixsocket` a Unix socket path. Both are used only when the start script does not set them.\n\nExample: In the config file\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nThe time zone of the process.\n\nReturns: `String`\n\nAssigned to `process.env.TZ` when the config is loaded.\n\nDefault: `utc`.\n\nExample: In the config file\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nThe default theme.\n\nReturns: `String`\n\nThe name of a folder in `themes/` used by views and static files when no theme is set.\n\nExample: In the config file\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nThe maximum size of a request body, in kilobytes.\n\nReturns: `Number`\n\nApplies to routes without their own length. Parsed as an integer.\n\nDefault: `10`.\n\nExample: In the config file\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nThe request timeout, in milliseconds.\n\nReturns: `Number`\n\nApplies to routes without their own timeout. Parsed as an integer.\n\nDefault: `3000`.\n\nExample: In the config file\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nThe maximum number of keys parsed from a query string or a URL-encoded body.\n\nReturns: `Number`\n\nExtra keys are ignored. `default_request_maxkey` (default `25`) is the maximum length of one key.\n\nDefault: `33`.\n\nExample: In the config file\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nThe default timeout of `RESTBuilder` and `REQUEST()`, in milliseconds.\n\nReturns: `Number`\n\nUsed when the request has no timeout of its own. `default_proxy` sets a proxy server (for example `http://proxy.example.com:3128`) for outgoing requests that do not set their own.\n\nDefault: `10000`.\n\nExample: In the config file\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nThe maximum size of a WebSocket message, in kilobytes.\n\nReturns: `Number`\n\nApplies to WebSocket routes without their own length.\n\nDefault: `2`.\n\nExample: In the config file\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nThe maximum latency of a WebSocket client, in milliseconds.\n\nReturns: `Number`\n\nTotal.js pings clients every `default_interval_websocket_ping` milliseconds and closes clients with a higher latency. `0` disables the pinging.\n\nDefault: `2000`.\n\nExample: In the config file\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nAllowed origins for cross-origin requests.\n\nReturns: `Array`\n\nHostnames separated by commas or spaces, without the protocol (a leading `//` is removed). Requests from other origins get `null` as the allowed origin. The value is stored as a lowercase array.\n\n`default_cors_maxage` (default `120`) sets how long browsers can cache a preflight response, in seconds.\n\nDefault: `null`.\n\nExample: In the config file\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\nThe `max-age` of the `Cache-Control` header for static files, in seconds.\n\nReturns: `String`\n\nUsed only in release mode.\n\nDefault: `11111111`.\n\nExample: In the config file\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nThe default `SameSite` attribute of cookies.\n\nReturns: `String`\n\nUsed when a cookie does not set `samesite`. `default_cookies_secure` (default `false`) adds the `Secure` attribute to cookies that do not set `secure`.\n\nDefault: `Lax`.\n\nExample: In the config file\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nSends all HTTP errors as `ErrorBuilder` JSON.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (default `true`) does the same only for XHR requests. `default_errorbuilder_status` (default `400`) is the HTTP status code of `ErrorBuilder` responses.\n\nDefault: `false`.\n\nExample: In the config file\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nChanges the generator of `UID()`.\n\nReturns: `String`\n\n`r` (or `uidr`) and `f` (or `uidf`) switch to other UID versions. Without a value the default generator is used.\n\nExample: In the config file\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nA Node.js cipher for `ENCRYPT()` and `DECRYPT()`.\n\nReturns: `String`\n\nWhen set, the functions use `crypto.createCipheriv()` with this algorithm and `default_crypto_iv` (a hex string in the file; by default derived from the machine). Without a value Total.js uses its own encryption with `secret`.\n\nExample: In the config file\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nThe command-line tool for `Image`.\n\nReturns: `String`\n\n`gm` is GraphicsMagick and `im` is ImageMagick. `default_image_consumption` (default `0`, disabled) limits the memory and map resources of the tool; the value is a percentage of 1500 MB of memory and 3000 MB of map.\n\nDefault: `gm`.\n\nExample: In the config file\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nThe WebSocket endpoint of the Total.js Message Service.\n\nReturns: `String`\n\nUsed when `allow_tms` is `true`. `default_tms_maxlength` (default `1024`, in kB) sets the maximum message size. `secret_tms` is the token that clients must send; without it the endpoint accepts every client.\n\nDefault: `/$tms/`.\n\nExample: In the config file\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervals of the internal service.\n\n- `default_interval_clear_cache` (default `10`): minutes between cleaning of expired cache items and unused sessions.\n- `default_interval_clear_resources` (default `20`): minutes between clearing of the loaded resources.\n- `default_interval_clear_dnscache` (default `30`): minutes between cleaning of the DNS cache.\n- `default_interval_websocket_ping` (default `20000`): milliseconds between WebSocket pings; values under `1000` mean `20000`.\n\nAll are parsed as integers.\n\nExample: In the config file\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nPaths of the application directories.\n\nEach directory has a key, relative to the root: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` and others. The default value is the name with slashes, for example `/public/`. The `PATH.*()` methods use these keys.\n\nWithout `directory_temp`, a folder in the system temp directory is used. The directories are read when the application starts.\n\nExample: In the config file\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nURL prefixes of static files.\n\nUsed by the view helpers for static files: `static_url` (default empty, a prefix for all of them, for example a CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) and `static_url_components` (`/components.`).\n\nExample: In the config file\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nFile extensions served as static files.\n\nThe default list contains common extensions (images, scripts, styles, fonts, documents, media). In the file, `static_accepts` replaces the whole list; `static_accepts_custom` adds extensions to it.\n\nExample: Add extensions\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nEnables WebSocket routes.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (default `true`) enables the `permessage-deflate` extension.\n\nDefault: `true`.\n\nExample: In the config file\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nServes static files from `public/`.\n\nReturns: `Boolean`\n\nSet to `false` when another server delivers static files.\n\nDefault: `true`.\n\nExample: In the config file\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nCompresses responses with gzip.\n\nReturns: `Boolean`\n\nApplies to compressible content types when the client accepts gzip.\n\nDefault: `true`.\n\nExample: In the config file\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifies static files and HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` and `allow_compile_html` (all `true`) switch the minification of JavaScript, CSS and HTML separately.\n\nDefault: `true`.\n\nExample: In the config file\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nEnables the Total.js Message Service endpoint.\n\nReturns: `Boolean`\n\nThe endpoint is `default_tms_url` and is protected by `secret_tms`.\n\nDefault: `false`.\n\nExample: In the config file\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nThe maximum number of concurrent requests from one IP address.\n\nReturns: `Number`\n\nRequests over the limit get `503 Service Unavailable`. `0` disables the limit.\n\nDefault: `0`.\n\nExample: In the config file\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nValidates TLS certificates of outgoing requests.\n\nReturns: `Boolean`\n\n`false` sets `NODE_TLS_REJECT_UNAUTHORIZED` to `0` and accepts self-signed certificates.\n\nDefault: `true`.\n\nExample: In the config file\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nSaves the cache to a file and loads it after a restart.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (default `false`) synchronizes the cache between cluster instances.\n\nDefault: `false`.\n\nExample: In the config file\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nEnables calls to Total API.\n\nReturns: `Boolean`\n\nThe token is read from `totalapi` or `secret_totalapi`. `allow_totalapilogger` (default `false`) sends logs to Total API. `default_tapi` (default `eu`) selects the server.\n\nDefault: `true`.\n\nExample: In the config file\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nThe SMTP server used by `MAIL()` and `Mail.send()`.\n\nRelated keys:\n\n- `mail_smtp_options`: the options of the SMTP connection, a JavaScript object written as text, for example `{ port: 465, secure: true, user: '...', password: '...' }`;\n- `mail_from`: the sender address, the sender name is `name`;\n- `mail_reply`: the reply-to address;\n- `mail_cc` and `mail_bcc`: copies of every message;\n- `mail_smtp_keepalive` (default `10 minutes`): how long the connection stays open;\n- `mail_api`: sends emails through Total API (`true` uses the `totalapi` token).\n\n`mail_address_from`, `mail_address_reply` and `mail_address_copy` are older names of `mail_from`, `mail_reply` and `mail_bcc`.\n\nExample: In the config file\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nWrites the console output to `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` and the timers are redirected to the file.\n\nExample: In the config file\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nDisables source maps.\n\nReturns: `Boolean`\n\nSource maps are generated only in debug mode; in release mode this key is always `true`.\n\nDefault: `false`.\n\nExample: In the config file\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nThe directory of NPM modules.\n\nReturns: `String`\n\nUsed by `NPMINSTALL()` and `F.require()`. A value starting with `~` is an absolute path.\n\nDefault: `node_modules`.\n\nExample: In the config file\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nThe content of `/security.txt`.\n\nReturns: `String`\n\nIn the file, lines are separated by commas. An empty value disables the response. Read it as `CONF['security.txt']`.\n\nDefault: `Contact: mailto:support@totaljs.com`.\n\nExample: In the config file\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Konfiguration","summary":"Das Objekt CONF, alle eingebauten Konfigurationsschlüssel und die Funktionen zum Laden der Konfiguration.","markdown":"---\ntitle: Konfiguration\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Konfiguration\n\n> Das Objekt CONF, alle eingebauten Konfigurationsschlüssel und die Funktionen zum Laden der Konfiguration.\n\nDie Konfiguration steht in den Dateien `config`, `config-debug` und `config-release` im Stammverzeichnis der Anwendung und im globalen Objekt `CONF`. Die Anleitung [Konfiguration](../../guides/configuration/) erklärt die Syntax, die Typen und die Umgebungsvariablen; diese Seite listet die Funktionen und die eingebauten Schlüssel mit ihren Standardwerten auf.\n\n## API\n\n### CONF\n\nType: `property`\n\nDas globale Objekt mit der gesamten Konfiguration der Anwendung.\n\nReturns: `Object`\n\nTotal.js füllt `CONF` mit Standardwerten, dann mit `options.config` aus dem Startskript und dann mit den Werten aus `config` und `config-debug` oder `config-release`. Es ist ein einfaches Objekt: Lies und weise Schlüssel als Eigenschaften zu. Schlüssel mit einem Punkt, wie `security.txt`, brauchen die Klammernotation.\n\nDeine eigenen Schlüssel werden genauso gespeichert wie die eingebauten. Im Code zugewiesene Werte werden nicht in den Dateien gespeichert.\n\nExample: Werte lesen\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: In einer View\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nFührt zur Laufzeit neue Werte in `CONF` zusammen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | Die neuen Werte. |\n\n`value` kann Folgendes sein:\n\n- ein Objekt, Schlüssel für Schlüssel in `CONF` kopiert;\n- ein String in der Konfigurationssyntax, geparst mit `String.parseConfig()`;\n- ein Array aus Einträgen `{ id, type, value }` (`key` oder `name` statt `id`, `body` statt `value`).\n\nBei Arrays konvertiert `type` den Wert: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). Ein String-Wert, der mit `hex ` beginnt, wird aus Hex dekodiert.\n\nEin Schlüssel `root` wird nach `default_root` kopiert, und `default_root` erhält einen führenden und einen abschließenden Schrägstrich. Eine Änderung von `mail_smtp` oder `mail_smtp_options` leert die gecachten SMTP-Einstellungen, und der TMS-Endpunkt wird aktualisiert.\n\nExample: Einstellungen aus einer Datenbank\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: Ein Objekt oder ein String\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Typisierte Einträge\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true`, wenn die Anwendung im Debug-Modus läuft.\n\nReturns: `Boolean`\n\nIm Debug-Modus liest Total.js `config-debug` und `.env-debug`; sonst `config-release` und `.env-release`.\n\nExample: Modusspezifischer Code\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true`, wenn die Anwendung im Release-Modus läuft.\n\nReturns: `Boolean`\n\nDas Gegenteil von `DEBUG`. Im Release-Modus liest Total.js `config-release` und `.env-release`, und `default_response_maxage` wird für den Header `Cache-Control` statischer Dateien verwendet.\n\nExample: Nur im Release-Modus\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nParst Text in der Konfigurationssyntax zu einem Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Standardwerte, die zuerst ins Ergebnis kopiert werden. |\n| `onerr` | `Function` | no |  | `function(err, line)`, aufgerufen, wenn ein `object`-Wert nicht ausgewertet werden kann. Ohne sie wird ein Fehler geworfen. |\n\nReturns: `Object` Die geparsten Werte.\n\nJede Zeile `key : value` wird zu einer Eigenschaft. Der Wert beginnt zwei Zeichen nach dem `:`, lass also ein Leerzeichen dahinter. Zeilen, die mit `#` oder `//` beginnen, werden übersprungen. Typen in Klammern funktionieren wie in der Konfigurationsdatei: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random` und `config`, das den Wert eines anderen `CONF`-Schlüssels kopiert. Ohne Typ bleibt der Wert ein String.\n\nExample: Einstellungen parsen\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nParst Text in der `.env`-Syntax zu einem Objekt.\n\nReturns: `Object` Die geparsten Variablen, alle als Strings.\n\nJede Zeile `KEY=value` wird zu einer Eigenschaft. Anführungszeichen um den Wert werden entfernt, andere Werte getrimmt, und `\\n` wird zu einem Zeilenumbruch. Zeilen, die mit `#` oder `//` beginnen, werden übersprungen. Total.js verwendet es für die `.env`-Dateien.\n\nExample: Variablen parsen\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nDateien mit Umgebungsvariablen, die vor den Konfigurationsdateien geladen werden.\n\nTotal.js liest `.env` aus dem Stammverzeichnis, dann `.env-debug` oder `.env-release`. Jede Variable kommt in `process.env`, aber eine Variable, die dort bereits existiert, wird nicht ersetzt. Verwende in der Konfiguration den Typ `(env)`, um eine Variable in einen Schlüssel zu lesen.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nGibt den Pfad zu einer Datei im Verzeichnis `configs` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname innerhalb des Verzeichnisses. |\n\nReturns: `String` Der absolute Pfad.\n\nDas Verzeichnis wird durch `directory_configs` festgelegt (Standard `/configs/`). Total.js lädt keine Dateien daraus; es ist ein Ort für deine eigenen Konfigurationsdateien.\n\nExample: Eine JSON-Datei lesen\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nDer Name der Anwendung.\n\nReturns: `String`\n\nWird im Prozesstitel, im Konsolen-Header, als Absendername von E-Mails, in Seitentiteln und im Header `x-app` von Total-API-Aufrufen verwendet.\n\nStandard: `Total.js`.\n\nExample: In der Konfigurationsdatei\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nDie Version der Anwendung.\n\nReturns: `String`\n\nWird immer als String behalten. Ohne `etag_version` wird die Version ohne Punkte und Leerzeichen als ETag-Suffix statischer Dateien verwendet; ändere `etag_version`, damit Browser statische Dateien erneut herunterladen. `author` enthält den Autor, der im Konsolen-Header angezeigt und als Standard-Author-Meta-Tag verwendet wird.\n\nStandard: `1.0.0`.\n\nExample: In der Konfigurationsdatei\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nDie öffentliche URL der Anwendung.\n\nReturns: `String`\n\nWird vom Total-API-Logger als Name der Anwendung und als Basis-URL für Referenzen in JSON-Schemas verwendet. Standardmäßig nicht gesetzt.\n\nExample: In der Konfigurationsdatei\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nDer Schlüssel, den `ENCRYPT()` und `DECRYPT()` verwenden.\n\nReturns: `String`\n\nDer Standardwert ist ein Hash aus dem Framework-Pfad, der Maschine und den Node.js-Versionen, er ändert sich also, wenn du die Anwendung verschiebst. Setze einen eigenen Wert, wenn verschlüsselte Daten ein Verschieben überstehen müssen. Wird immer als String behalten.\n\nExample: In der Konfigurationsdatei\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nEin Wert, der die erzeugten `UID()`-Werte für die Anwendung eindeutig macht.\n\nReturns: `String`\n\nOhne Wert berechnet Total.js ihn aus `name`.\n\nExample: In der Konfigurationsdatei\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nAktiviert die Verschlüsselung von Request- und Response-Bodys.\n\nReturns: `String`\n\nWenn gesetzt, werden die Bodys von Routen mit dem Flag `encrypt` (und von WebSockets mit Verschlüsselung) mit diesem Schlüssel verschlüsselt. Mit `allow_static_encryption` werden auch statische Dateien verschlüsselt.\n\nStandard: `null`.\n\nExample: In der Konfigurationsdatei\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nAktiviert CSRF-Tokens.\n\nReturns: `String`\n\nDer Schlüssel zum Erzeugen und Prüfen von CSRF-Tokens. Routen mit dem Flag `csrf` werden nur geprüft, wenn dieser Schlüssel gesetzt ist. `default_csrf_maxage` (Standard `30 minutes`) legt fest, wie lange ein Token gültig ist.\n\nStandard: `null`.\n\nExample: In der Konfigurationsdatei\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nDas URL-Präfix, wenn die Anwendung in einem Unterverzeichnis läuft.\n\nReturns: `String`\n\nTotal.js fügt einen führenden und einen abschließenden Schrägstrich hinzu. Das Präfix wird für URLs statischer Dateien und in Weiterleitungen verwendet und aus eingehenden URLs entfernt. `root` ist ein Alias: Wenn gesetzt, wird es nach `default_root` kopiert. Lade es mit `default_root (env) : APP_ROOT` aus einer Umgebungsvariablen.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nDer HTTP-Port.\n\nReturns: `Number|String`\n\nWird verwendet, wenn das Startskript keinen Port setzt. `auto` nimmt `process.env.PORT`. Ganz ohne Wert ist der Port `8000`.\n\n`default_ip` legt die IP-Adresse fest (ohne Wert oder mit `auto` lauscht der Server auf `0.0.0.0`) und `default_unixsocket` einen Unix-Socket-Pfad. Beide werden nur verwendet, wenn das Startskript sie nicht setzt.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nDie Zeitzone des Prozesses.\n\nReturns: `String`\n\nWird beim Laden der Konfiguration `process.env.TZ` zugewiesen.\n\nStandard: `utc`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nDas Standard-Theme.\n\nReturns: `String`\n\nDer Name eines Ordners in `themes/`, den Views und statische Dateien verwenden, wenn kein Theme gesetzt ist.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nDie maximale Größe eines Request-Bodys, in Kilobyte.\n\nReturns: `Number`\n\nGilt für Routen ohne eigene Länge. Wird als Ganzzahl geparst.\n\nStandard: `10`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nDas Timeout eines Requests, in Millisekunden.\n\nReturns: `Number`\n\nGilt für Routen ohne eigenes Timeout. Wird als Ganzzahl geparst.\n\nStandard: `3000`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nDie maximale Anzahl an Schlüsseln, die aus einem Query-String oder einem URL-kodierten Body geparst werden.\n\nReturns: `Number`\n\nZusätzliche Schlüssel werden ignoriert. `default_request_maxkey` (Standard `25`) ist die maximale Länge eines Schlüssels.\n\nStandard: `33`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nDas Standard-Timeout von `RESTBuilder` und `REQUEST()`, in Millisekunden.\n\nReturns: `Number`\n\nWird verwendet, wenn der Request kein eigenes Timeout hat. `default_proxy` legt einen Proxy-Server fest (zum Beispiel `http://proxy.example.com:3128`) für ausgehende Requests, die keinen eigenen setzen.\n\nStandard: `10000`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nDie maximale Größe einer WebSocket-Nachricht, in Kilobyte.\n\nReturns: `Number`\n\nGilt für WebSocket-Routen ohne eigene Länge.\n\nStandard: `2`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nDie maximale Latenz eines WebSocket-Clients, in Millisekunden.\n\nReturns: `Number`\n\nTotal.js pingt Clients alle `default_interval_websocket_ping` Millisekunden und schließt Clients mit höherer Latenz. `0` deaktiviert das Pingen.\n\nStandard: `2000`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nErlaubte Origins für Cross-Origin-Requests.\n\nReturns: `Array`\n\nHostnamen, durch Kommas oder Leerzeichen getrennt, ohne Protokoll (ein führendes `//` wird entfernt). Requests von anderen Origins erhalten `null` als erlaubten Origin. Der Wert wird als Array in Kleinbuchstaben gespeichert.\n\n`default_cors_maxage` (Standard `120`) legt fest, wie lange Browser eine Preflight-Response cachen dürfen, in Sekunden.\n\nStandard: `null`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\nDas `max-age` des Headers `Cache-Control` für statische Dateien, in Sekunden.\n\nReturns: `String`\n\nWird nur im Release-Modus verwendet.\n\nStandard: `11111111`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nDas Standard-Attribut `SameSite` von Cookies.\n\nReturns: `String`\n\nWird verwendet, wenn ein Cookie kein `samesite` setzt. `default_cookies_secure` (Standard `false`) fügt Cookies, die kein `secure` setzen, das Attribut `Secure` hinzu.\n\nStandard: `Lax`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nSendet alle HTTP-Fehler als `ErrorBuilder`-JSON.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (Standard `true`) tut dasselbe nur für XHR-Requests. `default_errorbuilder_status` (Standard `400`) ist der HTTP-Statuscode von `ErrorBuilder`-Responses.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nÄndert den Generator von `UID()`.\n\nReturns: `String`\n\n`r` (oder `uidr`) und `f` (oder `uidf`) wechseln zu anderen UID-Versionen. Ohne Wert wird der Standardgenerator verwendet.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nEin Node.js-Cipher für `ENCRYPT()` und `DECRYPT()`.\n\nReturns: `String`\n\nWenn gesetzt, verwenden die Funktionen `crypto.createCipheriv()` mit diesem Algorithmus und `default_crypto_iv` (in der Datei ein Hex-String; standardmäßig von der Maschine abgeleitet). Ohne Wert verwendet Total.js seine eigene Verschlüsselung mit `secret`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nDas Kommandozeilenwerkzeug für `Image`.\n\nReturns: `String`\n\n`gm` ist GraphicsMagick und `im` ist ImageMagick. `default_image_consumption` (Standard `0`, deaktiviert) begrenzt die Speicher- und Map-Ressourcen des Werkzeugs; der Wert ist ein Prozentsatz von 1500 MB Speicher und 3000 MB Map.\n\nStandard: `gm`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nDer WebSocket-Endpunkt des Total.js Message Service.\n\nReturns: `String`\n\nWird verwendet, wenn `allow_tms` gleich `true` ist. `default_tms_maxlength` (Standard `1024`, in kB) legt die maximale Nachrichtengröße fest. `secret_tms` ist das Token, das Clients senden müssen; ohne es akzeptiert der Endpunkt jeden Client.\n\nStandard: `/$tms/`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervalle des internen Dienstes.\n\n- `default_interval_clear_cache` (Standard `10`): Minuten zwischen dem Aufräumen abgelaufener Cache-Einträge und ungenutzter Sessions.\n- `default_interval_clear_resources` (Standard `20`): Minuten zwischen dem Leeren der geladenen Ressourcen.\n- `default_interval_clear_dnscache` (Standard `30`): Minuten zwischen dem Aufräumen des DNS-Caches.\n- `default_interval_websocket_ping` (Standard `20000`): Millisekunden zwischen WebSocket-Pings; Werte unter `1000` bedeuten `20000`.\n\nAlle werden als Ganzzahlen geparst.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nPfade der Anwendungsverzeichnisse.\n\nJedes Verzeichnis hat einen Schlüssel, relativ zum Stammverzeichnis: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` und weitere. Der Standardwert ist der Name mit Schrägstrichen, zum Beispiel `/public/`. Die Methoden `PATH.*()` verwenden diese Schlüssel.\n\nOhne `directory_temp` wird ein Ordner im temporären Verzeichnis des Systems verwendet. Die Verzeichnisse werden beim Start der Anwendung gelesen.\n\nExample: In der Konfigurationsdatei\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nURL-Präfixe statischer Dateien.\n\nWerden von den View-Helpern für statische Dateien verwendet: `static_url` (standardmäßig leer, ein Präfix für alle, zum Beispiel ein CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) und `static_url_components` (`/components.`).\n\nExample: In der Konfigurationsdatei\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nDateiendungen, die als statische Dateien ausgeliefert werden.\n\nDie Standardliste enthält gängige Endungen (Bilder, Skripte, Styles, Schriften, Dokumente, Medien). In der Datei ersetzt `static_accepts` die ganze Liste; `static_accepts_custom` fügt ihr Endungen hinzu.\n\nExample: Endungen hinzufügen\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nAktiviert WebSocket-Routen.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (Standard `true`) aktiviert die Erweiterung `permessage-deflate`.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nLiefert statische Dateien aus `public/` aus.\n\nReturns: `Boolean`\n\nSetze es auf `false`, wenn ein anderer Server die statischen Dateien ausliefert.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nKomprimiert Responses mit gzip.\n\nReturns: `Boolean`\n\nGilt für komprimierbare Content-Types, wenn der Client gzip akzeptiert.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifiziert statische Dateien und HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` und `allow_compile_html` (alle `true`) schalten die Minifizierung von JavaScript, CSS und HTML einzeln.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nAktiviert den Endpunkt des Total.js Message Service.\n\nReturns: `Boolean`\n\nDer Endpunkt ist `default_tms_url` und wird durch `secret_tms` geschützt.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nDie maximale Anzahl gleichzeitiger Requests von einer IP-Adresse.\n\nReturns: `Number`\n\nRequests über dem Limit erhalten `503 Service Unavailable`. `0` deaktiviert das Limit.\n\nStandard: `0`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nValidiert TLS-Zertifikate ausgehender Requests.\n\nReturns: `Boolean`\n\n`false` setzt `NODE_TLS_REJECT_UNAUTHORIZED` auf `0` und akzeptiert selbstsignierte Zertifikate.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nSpeichert den Cache in einer Datei und lädt ihn nach einem Neustart.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (Standard `false`) synchronisiert den Cache zwischen Cluster-Instanzen.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nAktiviert Aufrufe der Total API.\n\nReturns: `Boolean`\n\nDas Token wird aus `totalapi` oder `secret_totalapi` gelesen. `allow_totalapilogger` (Standard `false`) sendet Logs an die Total API. `default_tapi` (Standard `eu`) wählt den Server.\n\nStandard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nDer SMTP-Server, den `MAIL()` und `Mail.send()` verwenden.\n\nZugehörige Schlüssel:\n\n- `mail_smtp_options`: die Optionen der SMTP-Verbindung, ein als Text geschriebenes JavaScript-Objekt, zum Beispiel `{ port: 465, secure: true, user: '...', password: '...' }`;\n- `mail_from`: die Absenderadresse, der Absendername ist `name`;\n- `mail_reply`: die Reply-To-Adresse;\n- `mail_cc` und `mail_bcc`: Kopien jeder Nachricht;\n- `mail_smtp_keepalive` (Standard `10 minutes`): wie lange die Verbindung offen bleibt;\n- `mail_api`: sendet E-Mails über die Total API (`true` verwendet das Token `totalapi`).\n\n`mail_address_from`, `mail_address_reply` und `mail_address_copy` sind ältere Namen von `mail_from`, `mail_reply` und `mail_bcc`.\n\nExample: In der Konfigurationsdatei\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nSchreibt die Konsolenausgabe nach `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` und die Timer werden in die Datei umgeleitet.\n\nExample: In der Konfigurationsdatei\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nDeaktiviert Source Maps.\n\nReturns: `Boolean`\n\nSource Maps werden nur im Debug-Modus erzeugt; im Release-Modus ist dieser Schlüssel immer `true`.\n\nStandard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nDas Verzeichnis der NPM-Module.\n\nReturns: `String`\n\nWird von `NPMINSTALL()` und `F.require()` verwendet. Ein Wert, der mit `~` beginnt, ist ein absoluter Pfad.\n\nStandard: `node_modules`.\n\nExample: In der Konfigurationsdatei\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nDer Inhalt von `/security.txt`.\n\nReturns: `String`\n\nIn der Datei werden Zeilen durch Kommas getrennt. Ein leerer Wert deaktiviert die Response. Lies es als `CONF['security.txt']`.\n\nStandard: `Contact: mailto:support@totaljs.com`.\n\nExample: In der Konfigurationsdatei\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Configuración","summary":"El objeto CONF, todas las claves de configuración integradas y las funciones para cargar la configuración.","markdown":"---\ntitle: \"Configuración\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuración\n\n> El objeto CONF, todas las claves de configuración integradas y las funciones para cargar la configuración.\n\nLa configuración está en los archivos `config`, `config-debug` y `config-release` de la raíz de la aplicación, y en el objeto global `CONF`. La guía [Configuración](../../guides/configuration/) explica la sintaxis, los tipos y las variables de entorno; esta página lista las funciones y las claves integradas con sus valores por defecto.\n\n## API\n\n### CONF\n\nType: `property`\n\nEl objeto global con toda la configuración de la aplicación.\n\nReturns: `Object`\n\nTotal.js llena `CONF` con valores por defecto, luego con `options.config` del script de arranque, y después con los valores de `config` y de `config-debug` o `config-release`. Es un objeto plano: lee y asigna las claves como propiedades. Las claves con un punto, como `security.txt`, necesitan la notación de corchetes.\n\nTus propias claves se guardan igual que las integradas. Los valores asignados en el código no se guardan en los archivos.\n\nExample: Leer valores\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: En una vista\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nCombina valores nuevos en `CONF` en tiempo de ejecución.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | Los valores nuevos. |\n\n`value` puede ser:\n\n- un objeto, copiado clave por clave en `CONF`;\n- una cadena con la sintaxis de configuración, parseada con `String.parseConfig()`;\n- un array de elementos `{ id, type, value }` (`key` o `name` en lugar de `id`, `body` en lugar de `value`).\n\nEn los arrays, `type` convierte el valor: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). Un valor de cadena que empieza por `hex ` se decodifica desde hexadecimal.\n\nUna clave `root` se copia a `default_root`, y `default_root` recibe una barra inicial y una final. Cambiar `mail_smtp` o `mail_smtp_options` borra los ajustes SMTP en caché, y el endpoint de TMS se actualiza.\n\nExample: Ajustes desde una base de datos\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: Un objeto o una cadena\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Elementos con tipo\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true` cuando la aplicación se ejecuta en modo debug.\n\nReturns: `Boolean`\n\nEn modo debug Total.js lee `config-debug` y `.env-debug`; si no, `config-release` y `.env-release`.\n\nExample: Código específico del modo\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true` cuando la aplicación se ejecuta en modo release.\n\nReturns: `Boolean`\n\nLo contrario de `DEBUG`. En modo release Total.js lee `config-release` y `.env-release`, y `default_response_maxage` se usa para la cabecera `Cache-Control` de los archivos estáticos.\n\nExample: Solo en release\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nParsea texto con la sintaxis de configuración a un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valores por defecto, copiados primero en el resultado. |\n| `onerr` | `Function` | no |  | `function(err, line)` que se llama cuando un valor `object` no se puede evaluar. Sin ella, se lanza un error. |\n\nReturns: `Object` Los valores parseados.\n\nCada línea `key : value` se convierte en una propiedad. El valor empieza dos caracteres después de `:`, así que deja un espacio tras él. Las líneas que empiezan por `#` o `//` se omiten. Los tipos entre paréntesis funcionan como en el archivo de configuración: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random`, y `config`, que copia el valor de otra clave de `CONF`. Sin tipo, el valor se queda como cadena.\n\nExample: Parsear ajustes\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nParsea texto con la sintaxis `.env` a un objeto.\n\nReturns: `Object` Las variables parseadas, todas como cadenas.\n\nCada línea `KEY=value` se convierte en una propiedad. Las comillas alrededor del valor se eliminan, a los demás valores se les quitan los espacios sobrantes, y `\\n` se convierte en un salto de línea. Las líneas que empiezan por `#` o `//` se omiten. Total.js lo usa para los archivos `.env`.\n\nExample: Parsear variables\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nArchivos con variables de entorno, cargados antes de los archivos de configuración.\n\nTotal.js lee `.env` de la raíz y luego `.env-debug` o `.env-release`. Cada variable va a `process.env`, pero una variable que ya existe ahí no se reemplaza. Usa el tipo `(env)` en la configuración para leer una variable en una clave.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nDevuelve la ruta de un archivo en el directorio `configs`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo dentro del directorio. |\n\nReturns: `String` La ruta absoluta.\n\nEl directorio lo define `directory_configs` (por defecto `/configs/`). Total.js no carga archivos de él; es un lugar para tus propios archivos de configuración.\n\nExample: Leer un archivo JSON\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nEl nombre de la aplicación.\n\nReturns: `String`\n\nSe usa en el título del proceso, la cabecera de la consola, el nombre del remitente de los emails, los títulos de página y la cabecera `x-app` de las llamadas a Total API.\n\nPor defecto: `Total.js`.\n\nExample: En el archivo de configuración\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nLa versión de la aplicación.\n\nReturns: `String`\n\nSiempre se guarda como cadena. Sin `etag_version`, la versión sin puntos ni espacios se usa como sufijo ETag de los archivos estáticos; cambia `etag_version` para que los navegadores vuelvan a descargar los archivos estáticos. `author` contiene el autor, que se muestra en la cabecera de la consola y se usa como etiqueta meta de autor por defecto.\n\nPor defecto: `1.0.0`.\n\nExample: En el archivo de configuración\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nLa URL pública de la aplicación.\n\nReturns: `String`\n\nLa usa el logger de Total API como nombre de la aplicación y como URL base para las referencias de JSON schema. No está definida por defecto.\n\nExample: En el archivo de configuración\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nLa clave que usan `ENCRYPT()` y `DECRYPT()`.\n\nReturns: `String`\n\nEl valor por defecto es un hash de la ruta del framework, la máquina y las versiones de Node.js, así que cambia cuando mueves la aplicación. Define tu propio valor cuando los datos cifrados deban sobrevivir a un traslado. Siempre se guarda como cadena.\n\nExample: En el archivo de configuración\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nUn valor que hace únicos para la aplicación los valores generados por `UID()`.\n\nReturns: `String`\n\nSin valor, Total.js lo calcula a partir de `name`.\n\nExample: En el archivo de configuración\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nActiva el cifrado de los cuerpos de petición y respuesta.\n\nReturns: `String`\n\nCuando está definida, los cuerpos de las rutas con el flag `encrypt` (y de los WebSockets con cifrado) se cifran con esta clave. Con `allow_static_encryption`, también se cifran los archivos estáticos.\n\nPor defecto: `null`.\n\nExample: En el archivo de configuración\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nActiva los tokens CSRF.\n\nReturns: `String`\n\nLa clave que se usa para crear y comprobar tokens CSRF. Las rutas con el flag `csrf` solo se comprueban cuando esta clave está definida. `default_csrf_maxage` (por defecto `30 minutes`) define cuánto tiempo es válido un token.\n\nPor defecto: `null`.\n\nExample: En el archivo de configuración\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nEl prefijo de URL cuando la aplicación se ejecuta en un subdirectorio.\n\nReturns: `String`\n\nTotal.js añade una barra inicial y una final. El prefijo se usa en las URLs de los archivos estáticos y en las redirecciones, y se elimina de las URLs entrantes. `root` es un alias: cuando está definido, se copia a `default_root`. Cárgalo desde una variable de entorno con `default_root (env) : APP_ROOT`.\n\nExample: En el archivo de configuración\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nEl puerto HTTP.\n\nReturns: `Number|String`\n\nSe usa cuando el script de arranque no define un puerto. `auto` toma `process.env.PORT`. Sin ningún valor, el puerto es `8000`.\n\n`default_ip` define la dirección IP (sin valor, o con `auto`, el servidor escucha en `0.0.0.0`) y `default_unixsocket` la ruta de un socket Unix. Ambas se usan solo cuando el script de arranque no las define.\n\nExample: En el archivo de configuración\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nLa zona horaria del proceso.\n\nReturns: `String`\n\nSe asigna a `process.env.TZ` cuando se carga la configuración.\n\nPor defecto: `utc`.\n\nExample: En el archivo de configuración\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nEl tema por defecto.\n\nReturns: `String`\n\nEl nombre de una carpeta en `themes/` que usan las vistas y los archivos estáticos cuando no hay ningún tema definido.\n\nExample: En el archivo de configuración\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nEl tamaño máximo del cuerpo de una petición, en kilobytes.\n\nReturns: `Number`\n\nSe aplica a las rutas sin longitud propia. Se parsea como entero.\n\nPor defecto: `10`.\n\nExample: En el archivo de configuración\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nEl timeout de la petición, en milisegundos.\n\nReturns: `Number`\n\nSe aplica a las rutas sin timeout propio. Se parsea como entero.\n\nPor defecto: `3000`.\n\nExample: En el archivo de configuración\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nEl número máximo de claves que se parsean de un query string o de un cuerpo URL-encoded.\n\nReturns: `Number`\n\nLas claves sobrantes se ignoran. `default_request_maxkey` (por defecto `25`) es la longitud máxima de una clave.\n\nPor defecto: `33`.\n\nExample: En el archivo de configuración\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nEl timeout por defecto de `RESTBuilder` y `REQUEST()`, en milisegundos.\n\nReturns: `Number`\n\nSe usa cuando la petición no tiene timeout propio. `default_proxy` define un servidor proxy (por ejemplo `http://proxy.example.com:3128`) para las peticiones salientes que no definen el suyo.\n\nPor defecto: `10000`.\n\nExample: En el archivo de configuración\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nEl tamaño máximo de un mensaje WebSocket, en kilobytes.\n\nReturns: `Number`\n\nSe aplica a las rutas WebSocket sin longitud propia.\n\nPor defecto: `2`.\n\nExample: En el archivo de configuración\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nLa latencia máxima de un cliente WebSocket, en milisegundos.\n\nReturns: `Number`\n\nTotal.js hace ping a los clientes cada `default_interval_websocket_ping` milisegundos y cierra los clientes con una latencia mayor. `0` desactiva el ping.\n\nPor defecto: `2000`.\n\nExample: En el archivo de configuración\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nOrígenes permitidos para peticiones cross-origin.\n\nReturns: `Array`\n\nNombres de host separados por comas o espacios, sin el protocolo (un `//` inicial se elimina). Las peticiones desde otros orígenes reciben `null` como origen permitido. El valor se guarda como un array en minúsculas.\n\n`default_cors_maxage` (por defecto `120`) define cuánto tiempo pueden los navegadores guardar en caché una respuesta preflight, en segundos.\n\nPor defecto: `null`.\n\nExample: En el archivo de configuración\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\nEl `max-age` de la cabecera `Cache-Control` para los archivos estáticos, en segundos.\n\nReturns: `String`\n\nSolo se usa en modo release.\n\nPor defecto: `11111111`.\n\nExample: En el archivo de configuración\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nEl atributo `SameSite` por defecto de las cookies.\n\nReturns: `String`\n\nSe usa cuando una cookie no define `samesite`. `default_cookies_secure` (por defecto `false`) añade el atributo `Secure` a las cookies que no definen `secure`.\n\nPor defecto: `Lax`.\n\nExample: En el archivo de configuración\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nEnvía todos los errores HTTP como JSON de `ErrorBuilder`.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (por defecto `true`) hace lo mismo solo para peticiones XHR. `default_errorbuilder_status` (por defecto `400`) es el código de estado HTTP de las respuestas `ErrorBuilder`.\n\nPor defecto: `false`.\n\nExample: En el archivo de configuración\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nCambia el generador de `UID()`.\n\nReturns: `String`\n\n`r` (o `uidr`) y `f` (o `uidf`) cambian a otras versiones de UID. Sin valor se usa el generador por defecto.\n\nExample: En el archivo de configuración\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nUn cifrado de Node.js para `ENCRYPT()` y `DECRYPT()`.\n\nReturns: `String`\n\nCuando está definido, las funciones usan `crypto.createCipheriv()` con este algoritmo y `default_crypto_iv` (una cadena hexadecimal en el archivo; por defecto se deriva de la máquina). Sin valor, Total.js usa su propio cifrado con `secret`.\n\nExample: En el archivo de configuración\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nLa herramienta de línea de comandos para `Image`.\n\nReturns: `String`\n\n`gm` es GraphicsMagick e `im` es ImageMagick. `default_image_consumption` (por defecto `0`, desactivado) limita los recursos de memoria y de map de la herramienta; el valor es un porcentaje de 1500 MB de memoria y 3000 MB de map.\n\nPor defecto: `gm`.\n\nExample: En el archivo de configuración\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nEl endpoint WebSocket del Total.js Message Service.\n\nReturns: `String`\n\nSe usa cuando `allow_tms` es `true`. `default_tms_maxlength` (por defecto `1024`, en kB) define el tamaño máximo del mensaje. `secret_tms` es el token que deben enviar los clientes; sin él, el endpoint acepta a cualquier cliente.\n\nPor defecto: `/$tms/`.\n\nExample: En el archivo de configuración\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervalos del servicio interno.\n\n- `default_interval_clear_cache` (por defecto `10`): minutos entre limpiezas de elementos de caché caducados y sesiones sin usar.\n- `default_interval_clear_resources` (por defecto `20`): minutos entre limpiezas de los recursos cargados.\n- `default_interval_clear_dnscache` (por defecto `30`): minutos entre limpiezas de la caché DNS.\n- `default_interval_websocket_ping` (por defecto `20000`): milisegundos entre pings de WebSocket; los valores por debajo de `1000` significan `20000`.\n\nTodos se parsean como enteros.\n\nExample: En el archivo de configuración\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nRutas de los directorios de la aplicación.\n\nCada directorio tiene una clave, relativa a la raíz: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` y otras. El valor por defecto es el nombre entre barras, por ejemplo `/public/`. Los métodos `PATH.*()` usan estas claves.\n\nSin `directory_temp`, se usa una carpeta en el directorio temporal del sistema. Los directorios se leen cuando arranca la aplicación.\n\nExample: En el archivo de configuración\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nPrefijos de URL de los archivos estáticos.\n\nLos usan los helpers de vista para archivos estáticos: `static_url` (vacío por defecto, un prefijo para todos ellos, por ejemplo un CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) y `static_url_components` (`/components.`).\n\nExample: En el archivo de configuración\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nExtensiones de archivo que se sirven como archivos estáticos.\n\nLa lista por defecto contiene extensiones comunes (imágenes, scripts, estilos, fuentes, documentos, multimedia). En el archivo, `static_accepts` reemplaza la lista completa; `static_accepts_custom` le añade extensiones.\n\nExample: Añadir extensiones\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nActiva las rutas WebSocket.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (por defecto `true`) activa la extensión `permessage-deflate`.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nSirve archivos estáticos desde `public/`.\n\nReturns: `Boolean`\n\nAsígnale `false` cuando otro servidor entrega los archivos estáticos.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nComprime las respuestas con gzip.\n\nReturns: `Boolean`\n\nSe aplica a los tipos de contenido comprimibles cuando el cliente acepta gzip.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifica los archivos estáticos y el HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` y `allow_compile_html` (todos `true`) activan o desactivan por separado la minificación de JavaScript, CSS y HTML.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nActiva el endpoint del Total.js Message Service.\n\nReturns: `Boolean`\n\nEl endpoint es `default_tms_url` y está protegido por `secret_tms`.\n\nPor defecto: `false`.\n\nExample: En el archivo de configuración\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nEl número máximo de peticiones simultáneas desde una dirección IP.\n\nReturns: `Number`\n\nLas peticiones que superan el límite reciben `503 Service Unavailable`. `0` desactiva el límite.\n\nPor defecto: `0`.\n\nExample: En el archivo de configuración\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nValida los certificados TLS de las peticiones salientes.\n\nReturns: `Boolean`\n\n`false` asigna `0` a `NODE_TLS_REJECT_UNAUTHORIZED` y acepta certificados autofirmados.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nGuarda la caché en un archivo y la carga tras un reinicio.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (por defecto `false`) sincroniza la caché entre las instancias del clúster.\n\nPor defecto: `false`.\n\nExample: En el archivo de configuración\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nActiva las llamadas a Total API.\n\nReturns: `Boolean`\n\nEl token se lee de `totalapi` o de `secret_totalapi`. `allow_totalapilogger` (por defecto `false`) envía los logs a Total API. `default_tapi` (por defecto `eu`) selecciona el servidor.\n\nPor defecto: `true`.\n\nExample: En el archivo de configuración\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nEl servidor SMTP que usan `MAIL()` y `Mail.send()`.\n\nClaves relacionadas:\n\n- `mail_smtp_options`: las opciones de la conexión SMTP, un objeto JavaScript escrito como texto, por ejemplo `{ port: 465, secure: true, user: '...', password: '...' }`;\n- `mail_from`: la dirección del remitente; el nombre del remitente es `name`;\n- `mail_reply`: la dirección de respuesta;\n- `mail_cc` y `mail_bcc`: copias de cada mensaje;\n- `mail_smtp_keepalive` (por defecto `10 minutes`): cuánto tiempo se mantiene abierta la conexión;\n- `mail_api`: envía los emails a través de Total API (`true` usa el token `totalapi`).\n\n`mail_address_from`, `mail_address_reply` y `mail_address_copy` son nombres antiguos de `mail_from`, `mail_reply` y `mail_bcc`.\n\nExample: En el archivo de configuración\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nEscribe la salida de la consola en `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` y los temporizadores se redirigen al archivo.\n\nExample: En el archivo de configuración\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nDesactiva los source maps.\n\nReturns: `Boolean`\n\nLos source maps solo se generan en modo debug; en modo release esta clave siempre es `true`.\n\nPor defecto: `false`.\n\nExample: En el archivo de configuración\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nEl directorio de los módulos NPM.\n\nReturns: `String`\n\nLo usan `NPMINSTALL()` y `F.require()`. Un valor que empieza por `~` es una ruta absoluta.\n\nPor defecto: `node_modules`.\n\nExample: En el archivo de configuración\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nEl contenido de `/security.txt`.\n\nReturns: `String`\n\nEn el archivo, las líneas se separan con comas. Un valor vacío desactiva la respuesta. Léelo como `CONF['security.txt']`.\n\nPor defecto: `Contact: mailto:support@totaljs.com`.\n\nExample: En el archivo de configuración\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Configuration","summary":"L'objet CONF, toutes les clés de configuration intégrées et les fonctions de chargement de la configuration.","markdown":"---\ntitle: Configuration\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configuration\n\n> L'objet CONF, toutes les clés de configuration intégrées et les fonctions de chargement de la configuration.\n\nLa configuration réside dans les fichiers `config`, `config-debug` et `config-release` à la racine de l'application, ainsi que dans l'objet global `CONF`. Le guide [Configuration](../../guides/configuration/) explique la syntaxe, les types et les variables d'environnement ; cette page liste les fonctions et les clés intégrées avec leurs valeurs par défaut.\n\n## API\n\n### CONF\n\nType: `property`\n\nL'objet global contenant toute la configuration de l'application.\n\nReturns: `Object`\n\nTotal.js remplit `CONF` avec des valeurs par défaut, puis avec `options.config` du script de démarrage, puis avec les valeurs de `config` et de `config-debug` ou `config-release`. C'est un objet simple : lis et affecte les clés comme des propriétés. Les clés contenant un point, comme `security.txt`, nécessitent la notation entre crochets.\n\nTes propres clés sont stockées de la même façon que les clés intégrées. Les valeurs affectées dans le code ne sont pas enregistrées dans les fichiers.\n\nExample: Lire des valeurs\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: Dans une vue\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nFusionne de nouvelles valeurs dans `CONF` à l'exécution.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | Les nouvelles valeurs. |\n\n`value` peut être :\n\n- un objet, copié clé par clé dans `CONF` ;\n- une chaîne dans la syntaxe de configuration, analysée avec `String.parseConfig()` ;\n- un tableau d'éléments `{ id, type, value }` (`key` ou `name` au lieu de `id`, `body` au lieu de `value`).\n\nPour les tableaux, `type` convertit la valeur : `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). Une valeur chaîne qui commence par `hex ` est décodée depuis l'hexadécimal.\n\nUne clé `root` est copiée dans `default_root`, et `default_root` reçoit une barre oblique initiale et finale. Modifier `mail_smtp` ou `mail_smtp_options` vide les réglages SMTP en cache, et l'endpoint TMS est actualisé.\n\nExample: Réglages issus d'une base de données\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: Un objet ou une chaîne\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Éléments typés\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true` lorsque l'application s'exécute en mode debug.\n\nReturns: `Boolean`\n\nEn mode debug, Total.js lit `config-debug` et `.env-debug` ; sinon `config-release` et `.env-release`.\n\nExample: Code propre au mode\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true` lorsque l'application s'exécute en mode release.\n\nReturns: `Boolean`\n\nL'inverse de `DEBUG`. En mode release, Total.js lit `config-release` et `.env-release`, et `default_response_maxage` est utilisé pour l'en-tête `Cache-Control` des fichiers statiques.\n\nExample: Release uniquement\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nAnalyse un texte dans la syntaxe de configuration et le transforme en objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valeurs par défaut, copiées d'abord dans le résultat. |\n| `onerr` | `Function` | no |  | `function(err, line)` appelée lorsqu'une valeur `object` ne peut pas être évaluée. Sans elle, une erreur est levée. |\n\nReturns: `Object` Les valeurs analysées.\n\nChaque ligne `key : value` devient une propriété. La valeur commence deux caractères après le `:` : garde donc un espace après celui-ci. Les lignes qui commencent par `#` ou `//` sont ignorées. Les types entre parenthèses fonctionnent comme dans le fichier de configuration : `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random`, et `config`, qui copie la valeur d'une autre clé de `CONF`. Sans type, la valeur reste une chaîne.\n\nExample: Analyser des réglages\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nAnalyse un texte dans la syntaxe `.env` et le transforme en objet.\n\nReturns: `Object` Les variables analysées, toutes sous forme de chaînes.\n\nChaque ligne `KEY=value` devient une propriété. Les guillemets autour de la valeur sont supprimés, les autres valeurs sont débarrassées de leurs espaces, et `\\n` devient un saut de ligne. Les lignes qui commencent par `#` ou `//` sont ignorées. Total.js l'utilise pour les fichiers `.env`.\n\nExample: Analyser des variables\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nFichiers contenant des variables d'environnement, chargés avant les fichiers de configuration.\n\nTotal.js lit `.env` à la racine, puis `.env-debug` ou `.env-release`. Chaque variable est placée dans `process.env`, mais une variable qui y existe déjà n'est pas remplacée. Utilise le type `(env)` dans la configuration pour lire une variable dans une clé.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nRetourne le chemin d'un fichier du répertoire `configs`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier à l'intérieur du répertoire. |\n\nReturns: `String` Le chemin absolu.\n\nLe répertoire est défini par `directory_configs` (par défaut `/configs/`). Total.js n'en charge aucun fichier ; c'est un emplacement pour tes propres fichiers de configuration.\n\nExample: Lire un fichier JSON\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nLe nom de l'application.\n\nReturns: `String`\n\nUtilisé dans le titre du processus, l'en-tête de la console, le nom de l'expéditeur des e-mails, les titres de pages et l'en-tête `x-app` des appels à Total API.\n\nPar défaut : `Total.js`.\n\nExample: Dans le fichier de configuration\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nLa version de l'application.\n\nReturns: `String`\n\nToujours conservée sous forme de chaîne. Sans `etag_version`, la version sans points ni espaces est utilisée comme suffixe ETag des fichiers statiques ; modifie `etag_version` pour que les navigateurs téléchargent de nouveau les fichiers statiques. `author` contient l'auteur, affiché dans l'en-tête de la console et utilisé comme balise meta author par défaut.\n\nPar défaut : `1.0.0`.\n\nExample: Dans le fichier de configuration\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nL'URL publique de l'application.\n\nReturns: `String`\n\nUtilisée par le logger de Total API comme nom de l'application et comme URL de base des références de JSON schema. Non définie par défaut.\n\nExample: Dans le fichier de configuration\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nLa clé utilisée par `ENCRYPT()` et `DECRYPT()`.\n\nReturns: `String`\n\nLa valeur par défaut est un hash du chemin du framework, de la machine et des versions de Node.js : elle change donc lorsque tu déplaces l'application. Définis ta propre valeur lorsque des données chiffrées doivent survivre à un déplacement. Toujours conservée sous forme de chaîne.\n\nExample: Dans le fichier de configuration\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nUne valeur qui rend les valeurs `UID()` générées uniques pour l'application.\n\nReturns: `String`\n\nSans valeur, Total.js la calcule à partir de `name`.\n\nExample: Dans le fichier de configuration\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nActive le chiffrement des corps de requête et de réponse.\n\nReturns: `String`\n\nLorsqu'elle est définie, les corps des routes avec le flag `encrypt` (et des WebSockets avec chiffrement) sont chiffrés avec cette clé. Avec `allow_static_encryption`, les fichiers statiques sont également chiffrés.\n\nPar défaut : `null`.\n\nExample: Dans le fichier de configuration\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nActive les jetons CSRF.\n\nReturns: `String`\n\nLa clé utilisée pour créer et vérifier les jetons CSRF. Les routes avec le flag `csrf` ne sont vérifiées que lorsque cette clé est définie. `default_csrf_maxage` (par défaut `30 minutes`) définit la durée de validité d'un jeton.\n\nPar défaut : `null`.\n\nExample: Dans le fichier de configuration\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nLe préfixe d'URL lorsque l'application s'exécute dans un sous-répertoire.\n\nReturns: `String`\n\nTotal.js ajoute une barre oblique initiale et finale. Le préfixe est utilisé pour les URL des fichiers statiques et dans les redirections, et retiré des URL entrantes. `root` est un alias : lorsqu'il est défini, il est copié dans `default_root`. Charge-le depuis une variable d'environnement avec `default_root (env) : APP_ROOT`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nLe port HTTP.\n\nReturns: `Number|String`\n\nUtilisé lorsque le script de démarrage ne définit pas de port. `auto` prend `process.env.PORT`. Sans aucune valeur, le port est `8000`.\n\n`default_ip` définit l'adresse IP (sans valeur, ou avec `auto`, le serveur écoute sur `0.0.0.0`) et `default_unixsocket` un chemin de socket Unix. Les deux ne sont utilisés que lorsque le script de démarrage ne les définit pas.\n\nExample: Dans le fichier de configuration\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nLe fuseau horaire du processus.\n\nReturns: `String`\n\nAffecté à `process.env.TZ` lors du chargement de la configuration.\n\nPar défaut : `utc`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nLe thème par défaut.\n\nReturns: `String`\n\nLe nom d'un dossier de `themes/` utilisé par les vues et les fichiers statiques lorsqu'aucun thème n'est défini.\n\nExample: Dans le fichier de configuration\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nLa taille maximale du corps d'une requête, en kilo-octets.\n\nReturns: `Number`\n\nS'applique aux routes qui n'ont pas leur propre longueur. Analysée comme un entier.\n\nPar défaut : `10`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nLe délai d'expiration des requêtes, en millisecondes.\n\nReturns: `Number`\n\nS'applique aux routes qui n'ont pas leur propre délai d'expiration. Analysé comme un entier.\n\nPar défaut : `3000`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nLe nombre maximal de clés analysées depuis une query string ou un corps encodé en URL.\n\nReturns: `Number`\n\nLes clés supplémentaires sont ignorées. `default_request_maxkey` (par défaut `25`) est la longueur maximale d'une clé.\n\nPar défaut : `33`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nLe délai d'expiration par défaut de `RESTBuilder` et `REQUEST()`, en millisecondes.\n\nReturns: `Number`\n\nUtilisé lorsque la requête n'a pas son propre délai d'expiration. `default_proxy` définit un serveur proxy (par exemple `http://proxy.example.com:3128`) pour les requêtes sortantes qui n'en définissent pas.\n\nPar défaut : `10000`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nLa taille maximale d'un message WebSocket, en kilo-octets.\n\nReturns: `Number`\n\nS'applique aux routes WebSocket qui n'ont pas leur propre longueur.\n\nPar défaut : `2`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nLa latence maximale d'un client WebSocket, en millisecondes.\n\nReturns: `Number`\n\nTotal.js envoie un ping aux clients toutes les `default_interval_websocket_ping` millisecondes et ferme les clients dont la latence est plus élevée. `0` désactive le ping.\n\nPar défaut : `2000`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nOrigines autorisées pour les requêtes cross-origin.\n\nReturns: `Array`\n\nNoms d'hôtes séparés par des virgules ou des espaces, sans le protocole (un `//` initial est supprimé). Les requêtes provenant d'autres origines reçoivent `null` comme origine autorisée. La valeur est stockée sous forme de tableau en minuscules.\n\n`default_cors_maxage` (par défaut `120`) définit, en secondes, combien de temps les navigateurs peuvent mettre en cache une réponse preflight.\n\nPar défaut : `null`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\nLe `max-age` de l'en-tête `Cache-Control` des fichiers statiques, en secondes.\n\nReturns: `String`\n\nUtilisé uniquement en mode release.\n\nPar défaut : `11111111`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nL'attribut `SameSite` par défaut des cookies.\n\nReturns: `String`\n\nUtilisé lorsqu'un cookie ne définit pas `samesite`. `default_cookies_secure` (par défaut `false`) ajoute l'attribut `Secure` aux cookies qui ne définissent pas `secure`.\n\nPar défaut : `Lax`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nEnvoie toutes les erreurs HTTP sous forme de JSON `ErrorBuilder`.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (par défaut `true`) fait de même uniquement pour les requêtes XHR. `default_errorbuilder_status` (par défaut `400`) est le code de statut HTTP des réponses `ErrorBuilder`.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nChange le générateur de `UID()`.\n\nReturns: `String`\n\n`r` (ou `uidr`) et `f` (ou `uidf`) basculent vers d'autres versions d'UID. Sans valeur, le générateur par défaut est utilisé.\n\nExample: Dans le fichier de configuration\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nUn algorithme de chiffrement Node.js pour `ENCRYPT()` et `DECRYPT()`.\n\nReturns: `String`\n\nLorsqu'elle est définie, les fonctions utilisent `crypto.createCipheriv()` avec cet algorithme et `default_crypto_iv` (une chaîne hexadécimale dans le fichier ; par défaut dérivée de la machine). Sans valeur, Total.js utilise son propre chiffrement avec `secret`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nL'outil en ligne de commande pour `Image`.\n\nReturns: `String`\n\n`gm` est GraphicsMagick et `im` est ImageMagick. `default_image_consumption` (par défaut `0`, désactivé) limite les ressources mémoire et map de l'outil ; la valeur est un pourcentage de 1500 Mo de mémoire et de 3000 Mo de map.\n\nPar défaut : `gm`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nL'endpoint WebSocket du Total.js Message Service.\n\nReturns: `String`\n\nUtilisé lorsque `allow_tms` vaut `true`. `default_tms_maxlength` (par défaut `1024`, en ko) définit la taille maximale d'un message. `secret_tms` est le jeton que les clients doivent envoyer ; sans lui, l'endpoint accepte tous les clients.\n\nPar défaut : `/$tms/`.\n\nExample: Dans le fichier de configuration\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervalles du service interne.\n\n- `default_interval_clear_cache` (par défaut `10`) : minutes entre deux nettoyages des éléments de cache expirés et des sessions inutilisées.\n- `default_interval_clear_resources` (par défaut `20`) : minutes entre deux vidages des ressources chargées.\n- `default_interval_clear_dnscache` (par défaut `30`) : minutes entre deux nettoyages du cache DNS.\n- `default_interval_websocket_ping` (par défaut `20000`) : millisecondes entre deux pings WebSocket ; les valeurs inférieures à `1000` signifient `20000`.\n\nToutes sont analysées comme des entiers.\n\nExample: Dans le fichier de configuration\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nChemins des répertoires de l'application.\n\nChaque répertoire a une clé, relative à la racine : `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` et d'autres. La valeur par défaut est le nom entouré de barres obliques, par exemple `/public/`. Les méthodes `PATH.*()` utilisent ces clés.\n\nSans `directory_temp`, un dossier du répertoire temporaire du système est utilisé. Les répertoires sont lus au démarrage de l'application.\n\nExample: Dans le fichier de configuration\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nPréfixes d'URL des fichiers statiques.\n\nUtilisés par les helpers de vue pour les fichiers statiques : `static_url` (vide par défaut, un préfixe pour tous, par exemple un CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) et `static_url_components` (`/components.`).\n\nExample: Dans le fichier de configuration\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nExtensions de fichiers servies comme fichiers statiques.\n\nLa liste par défaut contient les extensions courantes (images, scripts, styles, polices, documents, médias). Dans le fichier, `static_accepts` remplace toute la liste ; `static_accepts_custom` y ajoute des extensions.\n\nExample: Ajouter des extensions\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nActive les routes WebSocket.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (par défaut `true`) active l'extension `permessage-deflate`.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nSert les fichiers statiques depuis `public/`.\n\nReturns: `Boolean`\n\nDéfinis-la à `false` lorsqu'un autre serveur fournit les fichiers statiques.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nCompresse les réponses avec gzip.\n\nReturns: `Boolean`\n\nS'applique aux types de contenu compressibles lorsque le client accepte gzip.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifie les fichiers statiques et le HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` et `allow_compile_html` (tous à `true`) activent ou désactivent séparément la minification du JavaScript, du CSS et du HTML.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nActive l'endpoint du Total.js Message Service.\n\nReturns: `Boolean`\n\nL'endpoint est `default_tms_url` et il est protégé par `secret_tms`.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nLe nombre maximal de requêtes simultanées depuis une même adresse IP.\n\nReturns: `Number`\n\nLes requêtes au-delà de la limite reçoivent `503 Service Unavailable`. `0` désactive la limite.\n\nPar défaut : `0`.\n\nExample: Dans le fichier de configuration\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nValide les certificats TLS des requêtes sortantes.\n\nReturns: `Boolean`\n\n`false` définit `NODE_TLS_REJECT_UNAUTHORIZED` à `0` et accepte les certificats auto-signés.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nEnregistre le cache dans un fichier et le recharge après un redémarrage.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (par défaut `false`) synchronise le cache entre les instances du cluster.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nActive les appels à Total API.\n\nReturns: `Boolean`\n\nLe jeton est lu depuis `totalapi` ou `secret_totalapi`. `allow_totalapilogger` (par défaut `false`) envoie les logs à Total API. `default_tapi` (par défaut `eu`) sélectionne le serveur.\n\nPar défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nLe serveur SMTP utilisé par `MAIL()` et `Mail.send()`.\n\nClés associées :\n\n- `mail_smtp_options` : les options de la connexion SMTP, un objet JavaScript écrit sous forme de texte, par exemple `{ port: 465, secure: true, user: '...', password: '...' }` ;\n- `mail_from` : l'adresse de l'expéditeur, le nom de l'expéditeur étant `name` ;\n- `mail_reply` : l'adresse de réponse ;\n- `mail_cc` et `mail_bcc` : copies de chaque message ;\n- `mail_smtp_keepalive` (par défaut `10 minutes`) : durée pendant laquelle la connexion reste ouverte ;\n- `mail_api` : envoie les e-mails via Total API (`true` utilise le jeton `totalapi`).\n\n`mail_address_from`, `mail_address_reply` et `mail_address_copy` sont les anciens noms de `mail_from`, `mail_reply` et `mail_bcc`.\n\nExample: Dans le fichier de configuration\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nÉcrit la sortie de la console dans `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` et les timers sont redirigés vers le fichier.\n\nExample: Dans le fichier de configuration\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nDésactive les source maps.\n\nReturns: `Boolean`\n\nLes source maps ne sont générées qu'en mode debug ; en mode release, cette clé vaut toujours `true`.\n\nPar défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nLe répertoire des modules NPM.\n\nReturns: `String`\n\nUtilisé par `NPMINSTALL()` et `F.require()`. Une valeur qui commence par `~` est un chemin absolu.\n\nPar défaut : `node_modules`.\n\nExample: Dans le fichier de configuration\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nLe contenu de `/security.txt`.\n\nReturns: `String`\n\nDans le fichier, les lignes sont séparées par des virgules. Une valeur vide désactive la réponse. Lis-la avec `CONF['security.txt']`.\n\nPar défaut : `Contact: mailto:support@totaljs.com`.\n\nExample: Dans le fichier de configuration\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Configurazione","summary":"L'oggetto CONF, tutte le chiavi di configurazione predefinite e le funzioni per caricare la configurazione.","markdown":"---\ntitle: Configurazione\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Configurazione\n\n> L'oggetto CONF, tutte le chiavi di configurazione predefinite e le funzioni per caricare la configurazione.\n\nLa configurazione si trova nei file `config`, `config-debug` e `config-release` nella radice dell'applicazione, e nell'oggetto globale `CONF`. La guida [Configurazione](../../guides/configuration/) spiega la sintassi, i tipi e le variabili d'ambiente; questa pagina elenca le funzioni e le chiavi predefinite con i loro valori predefiniti.\n\n## API\n\n### CONF\n\nType: `property`\n\nL'oggetto globale con l'intera configurazione dell'applicazione.\n\nReturns: `Object`\n\nTotal.js riempie `CONF` con i valori predefiniti, poi con `options.config` dallo script di avvio, e poi con i valori di `config` e `config-debug` o `config-release`. È un oggetto semplice: leggi e assegna le chiavi come proprietà. Le chiavi con un punto, come `security.txt`, richiedono la notazione con parentesi quadre.\n\nLe tue chiavi vengono memorizzate allo stesso modo di quelle predefinite. I valori assegnati nel codice non vengono salvati nei file.\n\nExample: Leggere valori\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: In una vista\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nUnisce nuovi valori in `CONF` a runtime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | I nuovi valori. |\n\n`value` può essere:\n\n- un oggetto, copiato chiave per chiave in `CONF`;\n- una stringa nella sintassi della configurazione, analizzata con `String.parseConfig()`;\n- un array di elementi `{ id, type, value }` (`key` o `name` al posto di `id`, `body` al posto di `value`).\n\nPer gli array, `type` converte il valore: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). Un valore stringa che inizia con `hex ` viene decodificato da esadecimale.\n\nUna chiave `root` viene copiata in `default_root`, e `default_root` riceve una barra iniziale e una finale. Modificare `mail_smtp` o `mail_smtp_options` svuota le impostazioni SMTP in cache, e l'endpoint TMS viene aggiornato.\n\nExample: Impostazioni da un database\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: Un oggetto o una stringa\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Elementi tipizzati\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true` quando l'applicazione è in esecuzione in modalità debug.\n\nReturns: `Boolean`\n\nIn modalità debug Total.js legge `config-debug` e `.env-debug`; altrimenti `config-release` e `.env-release`.\n\nExample: Codice specifico per modalità\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true` quando l'applicazione è in esecuzione in modalità release.\n\nReturns: `Boolean`\n\nL'opposto di `DEBUG`. In modalità release Total.js legge `config-release` e `.env-release`, e `default_response_maxage` viene usato per l'intestazione `Cache-Control` dei file statici.\n\nExample: Solo release\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nAnalizza testo nella sintassi della configurazione e lo trasforma in un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valori predefiniti, copiati prima nel risultato. |\n| `onerr` | `Function` | no |  | `function(err, line)` chiamata quando un valore `object` non può essere valutato. Senza di essa viene lanciato un errore. |\n\nReturns: `Object` I valori analizzati.\n\nOgni riga `key : value` diventa una proprietà. Il valore inizia due caratteri dopo il `:`, quindi lascia uno spazio dopo di esso. Le righe che iniziano con `#` o `//` vengono saltate. I tipi tra parentesi funzionano come nel file di configurazione: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random`, e `config`, che copia il valore di un'altra chiave di `CONF`. Senza un tipo il valore resta una stringa.\n\nExample: Analizzare le impostazioni\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nAnalizza testo nella sintassi `.env` e lo trasforma in un oggetto.\n\nReturns: `Object` Le variabili analizzate, tutte stringhe.\n\nOgni riga `KEY=value` diventa una proprietà. Le virgolette intorno al valore vengono rimosse, gli altri valori vengono ripuliti dagli spazi, e `\\n` diventa un a capo. Le righe che iniziano con `#` o `//` vengono saltate. Total.js lo usa per i file `.env`.\n\nExample: Analizzare le variabili\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nFile con variabili d'ambiente, caricati prima dei file di configurazione.\n\nTotal.js legge `.env` dalla radice, poi `.env-debug` o `.env-release`. Ogni variabile va in `process.env`, ma una variabile che esiste già lì non viene sostituita. Usa il tipo `(env)` nella configurazione per leggere una variabile in una chiave.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nRestituisce il percorso di un file nella directory `configs`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file all'interno della directory. |\n\nReturns: `String` Il percorso assoluto.\n\nLa directory è impostata da `directory_configs` (predefinita `/configs/`). Total.js non carica file da essa; è un posto per i tuoi file di configurazione.\n\nExample: Leggere un file JSON\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nIl nome dell'applicazione.\n\nReturns: `String`\n\nUsato nel titolo del processo, nell'intestazione della console, nel nome del mittente delle email, nei titoli delle pagine e nell'intestazione `x-app` delle chiamate a Total API.\n\nPredefinito: `Total.js`.\n\nExample: Nel file di configurazione\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nLa versione dell'applicazione.\n\nReturns: `String`\n\nConservata sempre come stringa. Senza `etag_version`, la versione senza punti e spazi viene usata come suffisso ETag dei file statici; cambia `etag_version` per far scaricare di nuovo i file statici ai browser. `author` contiene l'autore, mostrato nell'intestazione della console e usato come meta tag dell'autore predefinito.\n\nPredefinito: `1.0.0`.\n\nExample: Nel file di configurazione\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nL'URL pubblico dell'applicazione.\n\nReturns: `String`\n\nUsato dal logger di Total API come nome dell'applicazione e come URL di base per i riferimenti degli schemi JSON. Non impostato per impostazione predefinita.\n\nExample: Nel file di configurazione\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nLa chiave usata da `ENCRYPT()` e `DECRYPT()`.\n\nReturns: `String`\n\nIl valore predefinito è un hash del percorso del framework, della macchina e delle versioni di Node.js, quindi cambia quando sposti l'applicazione. Imposta un tuo valore quando i dati cifrati devono sopravvivere a uno spostamento. Conservata sempre come stringa.\n\nExample: Nel file di configurazione\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nUn valore che rende univoci per l'applicazione i valori generati da `UID()`.\n\nReturns: `String`\n\nSenza un valore Total.js lo calcola da `name`.\n\nExample: Nel file di configurazione\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nAbilita la cifratura dei corpi di richieste e risposte.\n\nReturns: `String`\n\nQuando è impostata, i corpi delle route con il flag `encrypt` (e dei WebSocket con cifratura) vengono cifrati con questa chiave. Con `allow_static_encryption`, vengono cifrati anche i file statici.\n\nPredefinito: `null`.\n\nExample: Nel file di configurazione\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nAbilita i token CSRF.\n\nReturns: `String`\n\nLa chiave usata per creare e controllare i token CSRF. Le route con il flag `csrf` vengono controllate solo quando questa chiave è impostata. `default_csrf_maxage` (predefinito `30 minutes`) imposta per quanto tempo un token è valido.\n\nPredefinito: `null`.\n\nExample: Nel file di configurazione\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nIl prefisso dell'URL quando l'applicazione è in esecuzione in una sottodirectory.\n\nReturns: `String`\n\nTotal.js aggiunge una barra iniziale e una finale. Il prefisso viene usato per gli URL dei file statici e nei redirect, e rimosso dagli URL in arrivo. `root` è un alias: quando è impostato, viene copiato in `default_root`. Caricalo da una variabile d'ambiente con `default_root (env) : APP_ROOT`.\n\nExample: Nel file di configurazione\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nLa porta HTTP.\n\nReturns: `Number|String`\n\nUsata quando lo script di avvio non imposta una porta. `auto` prende `process.env.PORT`. Senza alcun valore la porta è `8000`.\n\n`default_ip` imposta l'indirizzo IP (senza un valore, o con `auto`, il server ascolta su `0.0.0.0`) e `default_unixsocket` il percorso di un socket Unix. Entrambi vengono usati solo quando lo script di avvio non li imposta.\n\nExample: Nel file di configurazione\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nIl fuso orario del processo.\n\nReturns: `String`\n\nAssegnato a `process.env.TZ` quando viene caricata la configurazione.\n\nPredefinito: `utc`.\n\nExample: Nel file di configurazione\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nIl tema predefinito.\n\nReturns: `String`\n\nIl nome di una cartella in `themes/` usata dalle viste e dai file statici quando non è impostato alcun tema.\n\nExample: Nel file di configurazione\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nLa dimensione massima del corpo di una richiesta, in kilobyte.\n\nReturns: `Number`\n\nSi applica alle route senza una propria lunghezza. Analizzato come intero.\n\nPredefinito: `10`.\n\nExample: Nel file di configurazione\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nIl timeout della richiesta, in millisecondi.\n\nReturns: `Number`\n\nSi applica alle route senza un proprio timeout. Analizzato come intero.\n\nPredefinito: `3000`.\n\nExample: Nel file di configurazione\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nIl numero massimo di chiavi analizzate da una query string o da un corpo URL-encoded.\n\nReturns: `Number`\n\nLe chiavi in più vengono ignorate. `default_request_maxkey` (predefinito `25`) è la lunghezza massima di una chiave.\n\nPredefinito: `33`.\n\nExample: Nel file di configurazione\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nIl timeout predefinito di `RESTBuilder` e `REQUEST()`, in millisecondi.\n\nReturns: `Number`\n\nUsato quando la richiesta non ha un proprio timeout. `default_proxy` imposta un server proxy (per esempio `http://proxy.example.com:3128`) per le richieste in uscita che non ne impostano uno proprio.\n\nPredefinito: `10000`.\n\nExample: Nel file di configurazione\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nLa dimensione massima di un messaggio WebSocket, in kilobyte.\n\nReturns: `Number`\n\nSi applica alle route WebSocket senza una propria lunghezza.\n\nPredefinito: `2`.\n\nExample: Nel file di configurazione\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nLa latenza massima di un client WebSocket, in millisecondi.\n\nReturns: `Number`\n\nTotal.js invia un ping ai client ogni `default_interval_websocket_ping` millisecondi e chiude i client con una latenza superiore. `0` disattiva il ping.\n\nPredefinito: `2000`.\n\nExample: Nel file di configurazione\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nOrigini consentite per le richieste cross-origin.\n\nReturns: `Array`\n\nHostname separati da virgole o spazi, senza il protocollo (un `//` iniziale viene rimosso). Le richieste da altre origini ricevono `null` come origine consentita. Il valore viene memorizzato come array in minuscolo.\n\n`default_cors_maxage` (predefinito `120`) imposta per quanto tempo i browser possono mettere in cache una risposta di preflight, in secondi.\n\nPredefinito: `null`.\n\nExample: Nel file di configurazione\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\nIl `max-age` dell'intestazione `Cache-Control` per i file statici, in secondi.\n\nReturns: `String`\n\nUsato solo in modalità release.\n\nPredefinito: `11111111`.\n\nExample: Nel file di configurazione\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nL'attributo `SameSite` predefinito dei cookie.\n\nReturns: `String`\n\nUsato quando un cookie non imposta `samesite`. `default_cookies_secure` (predefinito `false`) aggiunge l'attributo `Secure` ai cookie che non impostano `secure`.\n\nPredefinito: `Lax`.\n\nExample: Nel file di configurazione\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nInvia tutti gli errori HTTP come JSON di `ErrorBuilder`.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (predefinito `true`) fa lo stesso solo per le richieste XHR. `default_errorbuilder_status` (predefinito `400`) è il codice di stato HTTP delle risposte di `ErrorBuilder`.\n\nPredefinito: `false`.\n\nExample: Nel file di configurazione\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nCambia il generatore di `UID()`.\n\nReturns: `String`\n\n`r` (o `uidr`) e `f` (o `uidf`) passano ad altre versioni di UID. Senza un valore viene usato il generatore predefinito.\n\nExample: Nel file di configurazione\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nUn cifrario di Node.js per `ENCRYPT()` e `DECRYPT()`.\n\nReturns: `String`\n\nQuando è impostato, le funzioni usano `crypto.createCipheriv()` con questo algoritmo e `default_crypto_iv` (una stringa esadecimale nel file; per impostazione predefinita derivata dalla macchina). Senza un valore Total.js usa la propria cifratura con `secret`.\n\nExample: Nel file di configurazione\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nLo strumento a riga di comando per `Image`.\n\nReturns: `String`\n\n`gm` è GraphicsMagick e `im` è ImageMagick. `default_image_consumption` (predefinito `0`, disattivato) limita le risorse di memoria e di map dello strumento; il valore è una percentuale di 1500 MB di memoria e 3000 MB di map.\n\nPredefinito: `gm`.\n\nExample: Nel file di configurazione\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nL'endpoint WebSocket del Total.js Message Service.\n\nReturns: `String`\n\nUsato quando `allow_tms` è `true`. `default_tms_maxlength` (predefinito `1024`, in kB) imposta la dimensione massima del messaggio. `secret_tms` è il token che i client devono inviare; senza di esso l'endpoint accetta qualsiasi client.\n\nPredefinito: `/$tms/`.\n\nExample: Nel file di configurazione\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervalli del servizio interno.\n\n- `default_interval_clear_cache` (predefinito `10`): minuti tra una pulizia e l'altra degli elementi della cache scaduti e delle sessioni inutilizzate.\n- `default_interval_clear_resources` (predefinito `20`): minuti tra uno svuotamento e l'altro delle risorse caricate.\n- `default_interval_clear_dnscache` (predefinito `30`): minuti tra una pulizia e l'altra della cache DNS.\n- `default_interval_websocket_ping` (predefinito `20000`): millisecondi tra un ping WebSocket e l'altro; i valori sotto `1000` significano `20000`.\n\nTutti vengono analizzati come interi.\n\nExample: Nel file di configurazione\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nPercorsi delle directory dell'applicazione.\n\nOgni directory ha una chiave, relativa alla radice: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` e altre. Il valore predefinito è il nome tra barre, per esempio `/public/`. I metodi `PATH.*()` usano queste chiavi.\n\nSenza `directory_temp`, viene usata una cartella nella directory temporanea del sistema. Le directory vengono lette all'avvio dell'applicazione.\n\nExample: Nel file di configurazione\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nPrefissi degli URL dei file statici.\n\nUsati dagli helper delle viste per i file statici: `static_url` (predefinito vuoto, un prefisso per tutti, per esempio una CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) e `static_url_components` (`/components.`).\n\nExample: Nel file di configurazione\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nEstensioni di file servite come file statici.\n\nL'elenco predefinito contiene le estensioni comuni (immagini, script, stili, font, documenti, media). Nel file, `static_accepts` sostituisce l'intero elenco; `static_accepts_custom` vi aggiunge estensioni.\n\nExample: Aggiungere estensioni\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nAbilita le route WebSocket.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (predefinito `true`) abilita l'estensione `permessage-deflate`.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nServe i file statici da `public/`.\n\nReturns: `Boolean`\n\nImpostalo a `false` quando un altro server distribuisce i file statici.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nComprime le risposte con gzip.\n\nReturns: `Boolean`\n\nSi applica ai content type comprimibili quando il client accetta gzip.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifica i file statici e l'HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` e `allow_compile_html` (tutti `true`) attivano o disattivano separatamente la minificazione di JavaScript, CSS e HTML.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nAbilita l'endpoint del Total.js Message Service.\n\nReturns: `Boolean`\n\nL'endpoint è `default_tms_url` ed è protetto da `secret_tms`.\n\nPredefinito: `false`.\n\nExample: Nel file di configurazione\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nIl numero massimo di richieste concorrenti da un indirizzo IP.\n\nReturns: `Number`\n\nLe richieste oltre il limite ricevono `503 Service Unavailable`. `0` disattiva il limite.\n\nPredefinito: `0`.\n\nExample: Nel file di configurazione\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nConvalida i certificati TLS delle richieste in uscita.\n\nReturns: `Boolean`\n\n`false` imposta `NODE_TLS_REJECT_UNAUTHORIZED` a `0` e accetta i certificati autofirmati.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nSalva la cache in un file e la carica dopo un riavvio.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (predefinito `false`) sincronizza la cache tra le istanze del cluster.\n\nPredefinito: `false`.\n\nExample: Nel file di configurazione\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nAbilita le chiamate a Total API.\n\nReturns: `Boolean`\n\nIl token viene letto da `totalapi` o `secret_totalapi`. `allow_totalapilogger` (predefinito `false`) invia i log a Total API. `default_tapi` (predefinito `eu`) seleziona il server.\n\nPredefinito: `true`.\n\nExample: Nel file di configurazione\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nIl server SMTP usato da `MAIL()` e `Mail.send()`.\n\nChiavi correlate:\n\n- `mail_smtp_options`: le opzioni della connessione SMTP, un oggetto JavaScript scritto come testo, per esempio `{ port: 465, secure: true, user: '...', password: '...' }`;\n- `mail_from`: l'indirizzo del mittente, il nome del mittente è `name`;\n- `mail_reply`: l'indirizzo di risposta (reply-to);\n- `mail_cc` e `mail_bcc`: copie di ogni messaggio;\n- `mail_smtp_keepalive` (predefinito `10 minutes`): per quanto tempo la connessione resta aperta;\n- `mail_api`: invia le email tramite Total API (`true` usa il token `totalapi`).\n\n`mail_address_from`, `mail_address_reply` e `mail_address_copy` sono nomi più vecchi di `mail_from`, `mail_reply` e `mail_bcc`.\n\nExample: Nel file di configurazione\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nScrive l'output della console in `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` e i timer vengono reindirizzati al file.\n\nExample: Nel file di configurazione\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nDisattiva le source map.\n\nReturns: `Boolean`\n\nLe source map vengono generate solo in modalità debug; in modalità release questa chiave è sempre `true`.\n\nPredefinito: `false`.\n\nExample: Nel file di configurazione\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nLa directory dei moduli NPM.\n\nReturns: `String`\n\nUsata da `NPMINSTALL()` e `F.require()`. Un valore che inizia con `~` è un percorso assoluto.\n\nPredefinito: `node_modules`.\n\nExample: Nel file di configurazione\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nIl contenuto di `/security.txt`.\n\nReturns: `String`\n\nNel file, le righe sono separate da virgole. Un valore vuoto disattiva la risposta. Leggilo come `CONF['security.txt']`.\n\nPredefinito: `Contact: mailto:support@totaljs.com`.\n\nExample: Nel file di configurazione\n\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWty1eO61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/configuration/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Konfigurácia","summary":"Objekt CONF, všetky vstavané konfiguračné kľúče a funkcie na načítanie konfigurácie.","markdown":"---\ntitle: \"Konfigurácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/configuration/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Konfigurácia\n\n> Objekt CONF, všetky vstavané konfiguračné kľúče a funkcie na načítanie konfigurácie.\n\nKonfigurácia sa nachádza v súboroch `config`, `config-debug` a `config-release` v koreni aplikácie a v globálnom objekte `CONF`. Príručka [Konfigurácia](../../guides/configuration/) vysvetľuje syntax, typy a premenné prostredia; táto stránka uvádza funkcie a vstavané kľúče s ich predvolenými hodnotami.\n\n## API\n\n### CONF\n\nType: `property`\n\nGlobálny objekt s celou konfiguráciou aplikácie.\n\nReturns: `Object`\n\nTotal.js naplní `CONF` predvolenými hodnotami, potom hodnotami `options.config` zo štartovacieho skriptu a potom hodnotami z `config` a `config-debug` alebo `config-release`. Je to obyčajný objekt: kľúče čítaj a priraďuj ako vlastnosti. Kľúče s bodkou, napríklad `security.txt`, potrebujú zápis s hranatými zátvorkami.\n\nTvoje vlastné kľúče sa ukladajú rovnako ako vstavané. Hodnoty priradené v kóde sa neukladajú do súborov.\n\nExample: Čítanie hodnôt\n```js\nexports.install = function() {\n\tROUTE('GET /api/info/', info);\n};\n\nfunction info() {\n\tthis.json({ name: CONF.name, version: CONF.version });\n}\n```\n\nExample: V pohľade\n```html\n<footer>@{CONF.name} v@{CONF.version}</footer>\n```\n\n### LOADCONFIG(value)\n\nType: `method`\n\nZlúči za behu nové hodnoty do `CONF`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Array` | yes |  | Nové hodnoty. |\n\n`value` môže byť:\n\n- objekt, skopírovaný kľúč po kľúči do `CONF`;\n- reťazec v konfiguračnej syntaxi, sparsovaný pomocou `String.parseConfig()`;\n- pole položiek `{ id, type, value }` (`key` alebo `name` namiesto `id`, `body` namiesto `value`).\n\nPri poliach `type` prevedie hodnotu: `number`, `boolean` (`bool`), `json` (`object`), `date`, `string`, `[string]`, `[number]`, `[boolean]` (`[bool]`). Reťazcová hodnota, ktorá začína `hex `, sa dekóduje z hex.\n\nKľúč `root` sa skopíruje do `default_root` a `default_root` dostane lomku na začiatku aj na konci. Zmena `mail_smtp` alebo `mail_smtp_options` vymaže nastavenia SMTP v cache a TMS endpoint sa obnoví.\n\nExample: Nastavenia z databázy\n```js\n// Items stored e.g. in a database: [{ id, type, value }]\nfunction applysettings(items) {\n\tLOADCONFIG(items);\n}\n```\n\nExample: Objekt alebo reťazec\n```js\nLOADCONFIG({ allow_tms: true, secret_tms: 'token' });\nLOADCONFIG('name : My Shop\\nlimit (number) : 50');\n```\n\nExample: Typové položky\n```js\nLOADCONFIG([\n\t{ id: 'limit', type: 'number', value: '50' },\n\t{ id: 'languages', type: '[string]', value: 'en, sk' },\n\t{ id: 'newsletter', type: 'boolean', value: 'on' }\n]);\n```\n\n### DEBUG\n\nType: `property`\n\n`true`, keď aplikácia beží v režime debug.\n\nReturns: `Boolean`\n\nV režime debug Total.js číta `config-debug` a `.env-debug`; inak `config-release` a `.env-release`.\n\nExample: Kód pre konkrétny režim\n```js\nif (DEBUG)\n\tconsole.log('Running with config-debug');\n```\n\n### RELEASE\n\nType: `property`\n\n`true`, keď aplikácia beží v režime release.\n\nReturns: `Boolean`\n\nOpak `DEBUG`. V režime release Total.js číta `config-release` a `.env-release` a pre hlavičku `Cache-Control` statických súborov sa použije `default_response_maxage`.\n\nExample: Iba release\n```js\nif (RELEASE)\n\tCONF.allow_tms = true;\n```\n\n### String.parseConfig([def], [onerr])\n\nType: `method`\n\nSparsuje text v konfiguračnej syntaxi do objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Predvolené hodnoty, najprv skopírované do výsledku. |\n| `onerr` | `Function` | no |  | `function(err, line)` sa zavolá, keď sa hodnota `object` nedá vyhodnotiť. Bez nej sa vyhodí chyba. |\n\nReturns: `Object` Sparsované hodnoty.\n\nKaždý riadok `key : value` sa stane vlastnosťou. Hodnota začína dva znaky za `:`, takže za ňou nechaj medzeru. Riadky, ktoré začínajú `#` alebo `//`, sa preskočia. Typy v zátvorkách fungujú rovnako ako v konfiguračnom súbore: `string`, `number` (`float`, `double`, `currency`), `boolean` (`bool`), `array`, `json`, `object` (`eval`), `env` (`environment`), `date` (`time`, `datetime`), `random` a `config`, ktorý skopíruje hodnotu iného kľúča `CONF`. Bez typu zostane hodnota reťazcom.\n\nExample: Parsovanie nastavení\n```js\nvar obj = 'name : Shop\\nlimit (number) : 10\\nhost (config) : url'.parseConfig();\n// obj.limit === 10, obj.host === CONF.url\n```\n\n### String.parseENV()\n\nType: `method`\n\nSparsuje text v syntaxi `.env` do objektu.\n\nReturns: `Object` Sparsované premenné, všetky ako reťazce.\n\nKaždý riadok `KEY=value` sa stane vlastnosťou. Úvodzovky okolo hodnoty sa odstránia, ostatné hodnoty sa orežú a `\\n` sa zmení na nový riadok. Riadky, ktoré začínajú `#` alebo `//`, sa preskočia. Total.js ju používa pre súbory `.env`.\n\nExample: Parsovanie premenných\n```js\nvar env = 'PORT=8000\\nNAME=\"My app\"'.parseENV();\n// { PORT: '8000', NAME: 'My app' }\n```\n\n### KEY=value\n\nType: `config`\n\nSúbory s premennými prostredia, načítané pred konfiguračnými súbormi.\n\nTotal.js načíta `.env` z koreňa, potom `.env-debug` alebo `.env-release`. Každá premenná ide do `process.env`, ale premenná, ktorá tam už existuje, sa nenahradí. Ak chceš načítať premennú do kľúča, použi v konfigurácii typ `(env)`.\n\nExample: .env\n```text\nDATABASE_URL=postgresql://user:pass@localhost:5432/shop\nPORT=8000\n```\n\nExample: config\n```text\ndatabase (env) : DATABASE_URL\ndefault_port   : auto\n```\n\n### PATH.configs([filename])\n\nType: `method`\n\nVráti cestu k súboru v adresári `configs`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru v adresári. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár nastavuje `directory_configs` (predvolene `/configs/`). Total.js z neho nenačítava žiadne súbory; je to miesto pre tvoje vlastné konfiguračné súbory.\n\nExample: Načítanie JSON súboru\n```js\nvar menu = require('fs').readFileSync(PATH.configs('menu.json')).toString('utf8').parseJSON();\n```\n\n### name : Total.js\n\nType: `config`\n\nNázov aplikácie.\n\nReturns: `String`\n\nPoužíva sa v názve procesu, v hlavičke konzoly, v mene odosielateľa e-mailov, v titulkoch stránok a v hlavičke `x-app` volaní Total API.\n\nPredvolene: `Total.js`.\n\nExample: V konfiguračnom súbore\n```text\nname : My Shop\n```\n\n### version : 1.0.0\n\nType: `config`\n\nVerzia aplikácie.\n\nReturns: `String`\n\nVždy sa uchováva ako reťazec. Bez `etag_version` sa ako prípona ETag statických súborov použije verzia bez bodiek a medzier; zmeň `etag_version`, aby prehliadače stiahli statické súbory znova. `author` obsahuje autora, zobrazuje sa v hlavičke konzoly a používa sa ako predvolený meta tag autora.\n\nPredvolene: `1.0.0`.\n\nExample: V konfiguračnom súbore\n```text\nversion : 2.1.0\n```\n\n### url : <value>\n\nType: `config`\n\nVerejná URL aplikácie.\n\nReturns: `String`\n\nTotal API logger ju používa ako názov aplikácie a ako základnú URL pre referencie JSON schém. Predvolene nie je nastavená.\n\nExample: V konfiguračnom súbore\n```text\nurl : https://www.example.com\n```\n\n### secret : <value>\n\nType: `config`\n\nKľúč, ktorý používajú `ENCRYPT()` a `DECRYPT()`.\n\nReturns: `String`\n\nPredvolená hodnota je hash cesty k frameworku, stroja a verzií Node.js, takže sa zmení, keď aplikáciu presunieš. Nastav vlastnú hodnotu, keď šifrované dáta musia presun prežiť. Vždy sa uchováva ako reťazec.\n\nExample: V konfiguračnom súbore\n```text\nsecret : my-long-random-secret\n```\n\n### secret_uid : <value>\n\nType: `config`\n\nHodnota, ktorá robí generované hodnoty `UID()` jedinečnými pre aplikáciu.\n\nReturns: `String`\n\nBez hodnoty ju Total.js vypočíta z `name`.\n\nExample: V konfiguračnom súbore\n```text\nsecret_uid : shop\n```\n\n### secret_encryption : null\n\nType: `config`\n\nZapne šifrovanie tiel požiadaviek a odpovedí.\n\nReturns: `String`\n\nKeď je nastavený, telá rout s flagom `encrypt` (a WebSocketov so šifrovaním) sa šifrujú týmto kľúčom. S `allow_static_encryption` sa šifrujú aj statické súbory.\n\nPredvolene: `null`.\n\nExample: V konfiguračnom súbore\n```text\nsecret_encryption : my-encryption-key\n```\n\n### secret_csrf : null\n\nType: `config`\n\nZapne CSRF tokeny.\n\nReturns: `String`\n\nKľúč na vytváranie a overovanie CSRF tokenov. Routy s flagom `csrf` sa overujú, iba keď je tento kľúč nastavený. `default_csrf_maxage` (predvolene `30 minutes`) určuje, ako dlho je token platný.\n\nPredvolene: `null`.\n\nExample: V konfiguračnom súbore\n```text\nsecret_csrf : my-csrf-key\ndefault_csrf_maxage : 30 minutes\n```\n\n### default_root : <value>\n\nType: `config`\n\nPrefix URL, keď aplikácia beží v podadresári.\n\nReturns: `String`\n\nTotal.js pridá lomku na začiatok aj na koniec. Prefix sa používa pre URL statických súborov a pri presmerovaniach a odstraňuje sa z prichádzajúcich URL. `root` je alias: keď je nastavený, skopíruje sa do `default_root`. Z premennej prostredia ho načítaš pomocou `default_root (env) : APP_ROOT`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_root : /shop/\n```\n\n### default_port : <value>\n\nType: `config`\n\nHTTP port.\n\nReturns: `Number|String`\n\nPoužije sa, keď štartovací skript port nenastaví. `auto` vezme `process.env.PORT`. Bez akejkoľvek hodnoty je port `8000`.\n\n`default_ip` nastaví IP adresu (bez hodnoty alebo s `auto` server počúva na `0.0.0.0`) a `default_unixsocket` cestu k Unix socketu. Obe sa použijú, iba keď ich štartovací skript nenastaví.\n\nExample: V konfiguračnom súbore\n```text\ndefault_port : auto\ndefault_ip   : 127.0.0.1\n```\n\n### default_timezone : utc\n\nType: `config`\n\nČasové pásmo procesu.\n\nReturns: `String`\n\nPri načítaní konfigurácie sa priradí do `process.env.TZ`.\n\nPredvolene: `utc`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_timezone : Europe/Berlin\n```\n\n### default_theme : <value>\n\nType: `config`\n\nPredvolená téma.\n\nReturns: `String`\n\nNázov priečinka v `themes/`, ktorý používajú pohľady a statické súbory, keď nie je nastavená žiadna téma.\n\nExample: V konfiguračnom súbore\n```text\ndefault_theme : default\n```\n\n### default_request_maxlength : 10\n\nType: `config`\n\nMaximálna veľkosť tela požiadavky v kilobajtoch.\n\nReturns: `Number`\n\nPlatí pre routy bez vlastnej dĺžky. Parsuje sa ako celé číslo.\n\nPredvolene: `10`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_request_maxlength : 1024\n```\n\n### default_request_timeout : 3000\n\nType: `config`\n\nTimeout požiadavky v milisekundách.\n\nReturns: `Number`\n\nPlatí pre routy bez vlastného timeoutu. Parsuje sa ako celé číslo.\n\nPredvolene: `3000`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_request_timeout : 10000\n```\n\n### default_request_maxkeys : 33\n\nType: `config`\n\nMaximálny počet kľúčov sparsovaných z query stringu alebo z URL-encoded tela.\n\nReturns: `Number`\n\nKľúče navyše sa ignorujú. `default_request_maxkey` (predvolene `25`) je maximálna dĺžka jedného kľúča.\n\nPredvolene: `33`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_request_maxkeys : 50\n```\n\n### default_restbuilder_timeout : 10000\n\nType: `config`\n\nPredvolený timeout `RESTBuilder` a `REQUEST()` v milisekundách.\n\nReturns: `Number`\n\nPoužije sa, keď požiadavka nemá vlastný timeout. `default_proxy` nastaví proxy server (napríklad `http://proxy.example.com:3128`) pre odchádzajúce požiadavky, ktoré nenastavia vlastný.\n\nPredvolene: `10000`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_restbuilder_timeout : 30000\n```\n\n### default_websocket_maxlength : 2\n\nType: `config`\n\nMaximálna veľkosť WebSocket správy v kilobajtoch.\n\nReturns: `Number`\n\nPlatí pre WebSocket routy bez vlastnej dĺžky.\n\nPredvolene: `2`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_websocket_maxlength : 64\n```\n\n### default_websocket_maxlatency : 2000\n\nType: `config`\n\nMaximálna latencia WebSocket klienta v milisekundách.\n\nReturns: `Number`\n\nTotal.js pinguje klientov každých `default_interval_websocket_ping` milisekúnd a zatvára klientov s vyššou latenciou. `0` pingovanie vypne.\n\nPredvolene: `2000`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_websocket_maxlatency : 5000\n```\n\n### default_cors : null\n\nType: `config`\n\nPovolené pôvody pre cross-origin požiadavky.\n\nReturns: `Array`\n\nNázvy hostiteľov oddelené čiarkami alebo medzerami, bez protokolu (úvodné `//` sa odstráni). Požiadavky z iných pôvodov dostanú ako povolený pôvod `null`. Hodnota sa uloží ako pole malými písmenami.\n\n`default_cors_maxage` (predvolene `120`) určuje, ako dlho môžu prehliadače držať preflight odpoveď v cache, v sekundách.\n\nPredvolene: `null`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_cors : example.com, app.example.com\n```\n\n### default_response_maxage : 11111111\n\nType: `config`\n\n`max-age` hlavičky `Cache-Control` pre statické súbory, v sekundách.\n\nReturns: `String`\n\nPoužíva sa iba v režime release.\n\nPredvolene: `11111111`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_response_maxage : 86400\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nPredvolený atribút `SameSite` pre cookies.\n\nReturns: `String`\n\nPoužije sa, keď cookie nenastaví `samesite`. `default_cookies_secure` (predvolene `false`) pridá atribút `Secure` ku cookies, ktoré nenastavia `secure`.\n\nPredvolene: `Lax`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_cookies_samesite : Strict\ndefault_cookies_secure   : true\n```\n\n### default_errorbuilder_errors : false\n\nType: `config`\n\nPosiela všetky HTTP chyby ako JSON `ErrorBuilder`.\n\nReturns: `Boolean`\n\n`default_errorbuilder_forxhr` (predvolene `true`) robí to isté iba pre XHR požiadavky. `default_errorbuilder_status` (predvolene `400`) je HTTP stavový kód odpovedí `ErrorBuilder`.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_errorbuilder_errors (bool) : true\n```\n\n### default_uid : <value>\n\nType: `config`\n\nZmení generátor `UID()`.\n\nReturns: `String`\n\n`r` (alebo `uidr`) a `f` (alebo `uidf`) prepnú na iné verzie UID. Bez hodnoty sa použije predvolený generátor.\n\nExample: V konfiguračnom súbore\n```text\ndefault_uid : f\n```\n\n### default_crypto : <value>\n\nType: `config`\n\nNode.js šifra pre `ENCRYPT()` a `DECRYPT()`.\n\nReturns: `String`\n\nKeď je nastavená, funkcie použijú `crypto.createCipheriv()` s týmto algoritmom a `default_crypto_iv` (v súbore hex reťazec; predvolene odvodený zo stroja). Bez hodnoty Total.js použije vlastné šifrovanie so `secret`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_crypto    : aes-256-cbc\ndefault_crypto_iv : 000102030405060708090a0b0c0d0e0f\n```\n\n### default_image_converter : gm\n\nType: `config`\n\nNástroj príkazového riadka pre `Image`.\n\nReturns: `String`\n\n`gm` je GraphicsMagick a `im` je ImageMagick. `default_image_consumption` (predvolene `0`, vypnuté) obmedzí pamäť a map zdroje nástroja; hodnota je percento z 1500 MB pamäte a 3000 MB map.\n\nPredvolene: `gm`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_image_converter   : im\ndefault_image_consumption : 50\n```\n\n### default_tms_url : /$tms/\n\nType: `config`\n\nWebSocket endpoint služby Total.js Message Service.\n\nReturns: `String`\n\nPoužíva sa, keď je `allow_tms` `true`. `default_tms_maxlength` (predvolene `1024`, v kB) nastaví maximálnu veľkosť správy. `secret_tms` je token, ktorý musia klienti posielať; bez neho endpoint prijme každého klienta.\n\nPredvolene: `/$tms/`.\n\nExample: V konfiguračnom súbore\n```text\nallow_tms       : true\ndefault_tms_url : /$tms/\nsecret_tms      : my-token\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nIntervaly internej služby.\n\n- `default_interval_clear_cache` (predvolene `10`): minúty medzi čistením expirovaných položiek cache a nepoužívaných sessions.\n- `default_interval_clear_resources` (predvolene `20`): minúty medzi vymazaním načítaných zdrojov.\n- `default_interval_clear_dnscache` (predvolene `30`): minúty medzi čistením DNS cache.\n- `default_interval_websocket_ping` (predvolene `20000`): milisekundy medzi WebSocket pingmi; hodnoty pod `1000` znamenajú `20000`.\n\nVšetky sa parsujú ako celé čísla.\n\nExample: V konfiguračnom súbore\n```text\ndefault_interval_clear_cache    : 5\ndefault_interval_websocket_ping : 30000\n```\n\n### directory_public : /public/\n\nType: `config`\n\nCesty k adresárom aplikácie.\n\nKaždý adresár má kľúč, relatívny ku koreňu: `directory_controllers`, `directory_definitions`, `directory_views`, `directory_public`, `directory_schemas`, `directory_models`, `directory_actions`, `directory_modules`, `directory_plugins`, `directory_resources`, `directory_databases`, `directory_logs`, `directory_temp`, `directory_themes`, `directory_components`, `directory_middleware`, `directory_packages`, `directory_flowstreams`, `directory_jsonschemas`, `directory_operations`, `directory_tasks`, `directory_extensions`, `directory_builds`, `directory_workers`, `directory_private`, `directory_configs`, `directory_tests` a ďalšie. Predvolená hodnota je názov s lomkami, napríklad `/public/`. Metódy `PATH.*()` tieto kľúče používajú.\n\nBez `directory_temp` sa použije priečinok v systémovom dočasnom adresári. Adresáre sa načítajú pri štarte aplikácie.\n\nExample: V konfiguračnom súbore\n```text\ndirectory_public    : /www/\ndirectory_databases : /data/\n```\n\n### static_url_script : /js/\n\nType: `config`\n\nPrefixy URL statických súborov.\n\nPoužívajú ich helpery pohľadov pre statické súbory: `static_url` (predvolene prázdne, prefix pre všetky, napríklad CDN), `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`), `static_url_download` (`/download/`) a `static_url_components` (`/components.`).\n\nExample: V konfiguračnom súbore\n```text\nstatic_url        : https://cdn.example.com\nstatic_url_script : /scripts/\n```\n\n### static_accepts : jpg, png, css, js\n\nType: `config`\n\nPrípony súborov, ktoré sa servírujú ako statické súbory.\n\nPredvolený zoznam obsahuje bežné prípony (obrázky, skripty, štýly, fonty, dokumenty, médiá). V súbore `static_accepts` nahradí celý zoznam; `static_accepts_custom` doň pridá prípony.\n\nExample: Pridanie prípon\n```text\nstatic_accepts_custom : glb, gltf\n```\n\n### allow_websocket : true\n\nType: `config`\n\nZapne WebSocket routy.\n\nReturns: `Boolean`\n\n`allow_websocket_compression` (predvolene `true`) zapne rozšírenie `permessage-deflate`.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\nallow_websocket : false\n```\n\n### allow_static_files : true\n\nType: `config`\n\nServíruje statické súbory z `public/`.\n\nReturns: `Boolean`\n\nNastav na `false`, keď statické súbory doručuje iný server.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\nallow_static_files : false\n```\n\n### allow_gzip : true\n\nType: `config`\n\nKomprimuje odpovede pomocou gzip.\n\nReturns: `Boolean`\n\nPlatí pre komprimovateľné typy obsahu, keď klient akceptuje gzip.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\nallow_gzip : false\n```\n\n### allow_compile : true\n\nType: `config`\n\nMinifikuje statické súbory a HTML.\n\nReturns: `Boolean`\n\n`allow_compile_script`, `allow_compile_style` a `allow_compile_html` (všetky `true`) zapínajú minifikáciu JavaScriptu, CSS a HTML samostatne.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\nallow_compile_html : false\n```\n\n### allow_tms : false\n\nType: `config`\n\nZapne endpoint služby Total.js Message Service.\n\nReturns: `Boolean`\n\nEndpoint je `default_tms_url` a chráni ho `secret_tms`.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\nallow_tms : true\n```\n\n### allow_reqlimit : 0\n\nType: `config`\n\nMaximálny počet súbežných požiadaviek z jednej IP adresy.\n\nReturns: `Number`\n\nPožiadavky nad limit dostanú `503 Service Unavailable`. `0` limit vypne.\n\nPredvolene: `0`.\n\nExample: V konfiguračnom súbore\n```text\nallow_reqlimit (number) : 20\n```\n\n### allow_ssc_validation : true\n\nType: `config`\n\nOveruje TLS certifikáty odchádzajúcich požiadaviek.\n\nReturns: `Boolean`\n\n`false` nastaví `NODE_TLS_REJECT_UNAUTHORIZED` na `0` a akceptuje self-signed certifikáty.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\nallow_ssc_validation : false\n```\n\n### allow_cache_snapshot : false\n\nType: `config`\n\nUloží cache do súboru a po reštarte ju načíta.\n\nReturns: `Boolean`\n\n`allow_cache_cluster` (predvolene `false`) synchronizuje cache medzi inštanciami klástra.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\nallow_cache_snapshot : true\n```\n\n### allow_totalapi : true\n\nType: `config`\n\nZapne volania Total API.\n\nReturns: `Boolean`\n\nToken sa načíta z `totalapi` alebo `secret_totalapi`. `allow_totalapilogger` (predvolene `false`) posiela logy do Total API. `default_tapi` (predvolene `eu`) vyberie server.\n\nPredvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\ntotalapi       : my-token\nallow_totalapi : true\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nSMTP server, ktorý používajú `MAIL()` a `Mail.send()`.\n\nSúvisiace kľúče:\n\n- `mail_smtp_options`: možnosti SMTP spojenia, JavaScript objekt zapísaný ako text, napríklad `{ port: 465, secure: true, user: '...', password: '...' }`;\n- `mail_from`: adresa odosielateľa, meno odosielateľa je `name`;\n- `mail_reply`: adresa pre odpoveď (reply-to);\n- `mail_cc` a `mail_bcc`: kópie každej správy;\n- `mail_smtp_keepalive` (predvolene `10 minutes`): ako dlho zostane spojenie otvorené;\n- `mail_api`: posiela e-maily cez Total API (`true` použije token `totalapi`).\n\n`mail_address_from`, `mail_address_reply` a `mail_address_copy` sú staršie názvy pre `mail_from`, `mail_reply` a `mail_bcc`.\n\nExample: V konfiguračnom súbore\n```text\nmail_smtp         : smtp.example.com\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\nmail_from         : info@example.com\nmail_reply        : support@example.com\n```\n\n### logger : <value>\n\nType: `config`\n\nZapisuje výstup konzoly do `logs/debug.log`.\n\nReturns: `Boolean`\n\n`console.log`, `console.warn`, `console.error` a časovače sa presmerujú do súboru.\n\nExample: V konfiguračnom súbore\n```text\nlogger : true\n```\n\n### nosourcemap : false\n\nType: `config`\n\nVypne source mapy.\n\nReturns: `Boolean`\n\nSource mapy sa generujú iba v režime debug; v režime release je tento kľúč vždy `true`.\n\nPredvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\nnosourcemap : true\n```\n\n### node_modules : node_modules\n\nType: `config`\n\nAdresár NPM modulov.\n\nReturns: `String`\n\nPoužívajú ho `NPMINSTALL()` a `F.require()`. Hodnota, ktorá začína `~`, je absolútna cesta.\n\nPredvolene: `node_modules`.\n\nExample: V konfiguračnom súbore\n```text\nnode_modules : ~/opt/shared/node_modules\n```\n\n### security.txt : Contact: mailto:support@totaljs.com\n\nType: `config`\n\nObsah `/security.txt`.\n\nReturns: `String`\n\nV súbore sú riadky oddelené čiarkami. Prázdna hodnota odpoveď vypne. Čítaj ho ako `CONF['security.txt']`.\n\nPredvolene: `Contact: mailto:support@totaljs.com`.\n\nExample: V konfiguračnom súbore\n```text\nsecurity.txt : Contact: mailto:security@example.com, Expires: 2026-12-31T00:00:00.000Z\n```\n","entries":[{"type":"property","name":"CONF","signature":"CONF","since":"","deprecated":false},{"type":"method","name":"LOADCONFIG(value)","signature":"LOADCONFIG(value)","since":"","deprecated":false},{"type":"property","name":"DEBUG","signature":"DEBUG","since":"","deprecated":false},{"type":"property","name":"RELEASE","signature":"RELEASE","since":"","deprecated":false},{"type":"method","name":"String.parseConfig([def], [onerr])","signature":"String.parseConfig([def], [onerr])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"config","name":".env","signature":"KEY=value","since":"","deprecated":false},{"type":"method","name":"PATH.configs([filename])","signature":"PATH.configs([filename])","since":"","deprecated":false},{"type":"config","name":"name","signature":"name : Total.js","since":"","deprecated":false},{"type":"config","name":"version","signature":"version : 1.0.0","since":"","deprecated":false},{"type":"config","name":"url","signature":"url : <value>","since":"","deprecated":false},{"type":"config","name":"secret","signature":"secret : <value>","since":"","deprecated":false},{"type":"config","name":"secret_uid","signature":"secret_uid : <value>","since":"","deprecated":false},{"type":"config","name":"secret_encryption","signature":"secret_encryption : null","since":"","deprecated":false},{"type":"config","name":"secret_csrf","signature":"secret_csrf : null","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root : <value>","since":"","deprecated":false},{"type":"config","name":"default_port","signature":"default_port : <value>","since":"","deprecated":false},{"type":"config","name":"default_timezone","signature":"default_timezone : utc","since":"","deprecated":false},{"type":"config","name":"default_theme","signature":"default_theme : <value>","since":"","deprecated":false},{"type":"config","name":"default_request_maxlength","signature":"default_request_maxlength : 10","since":"","deprecated":false},{"type":"config","name":"default_request_timeout","signature":"default_request_timeout : 3000","since":"","deprecated":false},{"type":"config","name":"default_request_maxkeys","signature":"default_request_maxkeys : 33","since":"","deprecated":false},{"type":"config","name":"default_restbuilder_timeout","signature":"default_restbuilder_timeout : 10000","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"default_websocket_maxlength : 2","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"default_websocket_maxlatency : 2000","since":"","deprecated":false},{"type":"config","name":"default_cors","signature":"default_cors : null","since":"","deprecated":false},{"type":"config","name":"default_response_maxage","signature":"default_response_maxage : 11111111","since":"","deprecated":false},{"type":"config","name":"default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_errors","signature":"default_errorbuilder_errors : false","since":"","deprecated":false},{"type":"config","name":"default_uid","signature":"default_uid : <value>","since":"","deprecated":false},{"type":"config","name":"default_crypto","signature":"default_crypto : <value>","since":"","deprecated":false},{"type":"config","name":"default_image_converter","signature":"default_image_converter : gm","since":"","deprecated":false},{"type":"config","name":"default_tms_url","signature":"default_tms_url : /$tms/","since":"","deprecated":false},{"type":"config","name":"default_interval_*","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"directory_*","signature":"directory_public : /public/","since":"","deprecated":false},{"type":"config","name":"static_url_*","signature":"static_url_script : /js/","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts : jpg, png, css, js","since":"","deprecated":false},{"type":"config","name":"allow_websocket","signature":"allow_websocket : true","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files : true","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip : true","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile : true","since":"","deprecated":false},{"type":"config","name":"allow_tms","signature":"allow_tms : false","since":"","deprecated":false},{"type":"config","name":"allow_reqlimit","signature":"allow_reqlimit : 0","since":"","deprecated":false},{"type":"config","name":"allow_ssc_validation","signature":"allow_ssc_validation : true","since":"","deprecated":false},{"type":"config","name":"allow_cache_snapshot","signature":"allow_cache_snapshot : false","since":"","deprecated":false},{"type":"config","name":"allow_totalapi","signature":"allow_totalapi : true","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"logger","signature":"logger : <value>","since":"","deprecated":false},{"type":"config","name":"nosourcemap","signature":"nosourcemap : false","since":"","deprecated":false},{"type":"config","name":"node_modules","signature":"node_modules : node_modules","since":"","deprecated":false},{"type":"config","name":"security.txt","signature":"security.txt : Contact: mailto:support@totaljs.com","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Authorization","summary":"AUTH(), route flags, roles, cookies and the SESSION() store.","markdown":"---\ntitle: Authorization\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Authorization\n\n> AUTH(), route flags, roles, cookies and the SESSION() store.\n\nTotal.js signs in requests with the `AUTH()` delegate, limits routes with the `+` and `-` flags, and keeps sessions with the built-in cookie session or the `SESSION()` store. The guide [Authorization](../../guides/authorization/) explains how to use them with examples; this page is the exact reference.\n\nEncryption has its own page: [Encryption](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nRegisters the delegate that signs in every request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | The delegate. `$` is the authorization object. |\n\nReturns: `undefined`\n\nThe delegate runs for every HTTP request that reaches routing and for every WebSocket connection. It receives an authorization object `$` (see `$.success()`, `$.invalid()` and the properties of `$`). It must call exactly one of `$.success(user)`, `$.invalid()` or `$.cancel()`. Registering a new delegate replaces the previous one.\n\nPassing an object instead of a function starts the built-in cookie session, see `AUTH(options)`.\n\nExample: Sign in with a token header\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nStarts the built-in cookie session mechanism.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Options and delegates of the session, see the table. |\n\nReturns: `undefined` Methods are added to `options`.\n\nWith an object, `AUTH()` registers its own delegate. It reads the session token from the cookie `options.cookie` (or from the header `options.header`), decrypts it with `options.secret`, and keeps the user data in memory for `options.expire`. When the data is not cached, it calls `options.onread()`. Requests waiting for the same session share one `onread()` call.\n\n`AUTH()` does not return anything, but it adds methods to the object you pass: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` and `auth()` (the delegate itself). Keep a reference to the object.\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `secret` | String | Key for encrypting the token. Always set it. |\n| `cookie` | String | Name of the cookie with the token. |\n| `header` | String | Name of a request header with the token, used when the cookie is missing. Write it in lower case. |\n| `expire` | String | How long user data stays in memory. Default `'5 minutes'`. |\n| `strict` | Boolean | The cached session works only with the same user agent. Default `true`. |\n| `ddos` | Number | Failed attempts per IP address before every request of that IP is invalid. The counters reset with each cleaning. |\n| `cleaner` | Number | Cleaning interval in minutes. Default `5`. |\n| `options` | Object | Cookie options used when the cookie is written or removed. |\n| `onread` | Function(meta, next, $) | Loads the user data, see `options.onread`. |\n| `onsession` | Function(session, $, init) | Called when a session is found. Return `true` to stop the processing; then answer `$` yourself. `init` is `true` when the data was just loaded. |\n| `onauthorize` | Function($) | Called first for every request. Return `true` to skip the built-in processing; then answer `$` yourself. |\n| `onlogout` | Function(session) | Called by `logout()`. |\n| `onfree` | Function(meta) | Called after cleaning with `{ sessions: Array, users: Array }`: the removed session IDs and the user IDs without any live session. |\n| `onddos` | Function($) | Called when a blocked IP address makes a request. |\n| `locale` | Function(data, req) | Returns the language of the request. `data` is `null` for anonymous visitors. |\n\nAn invalid or unknown token removes the cookie.\n\nExample: Built-in session\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Language of the user\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nLoads the user data for a session token in the built-in session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback with the user data. |\n| `$` | `Object` | yes |  | The authorization object. |\n\nCalled when a valid token has no cached data. `meta` contains `sessionid`, `userid`, `ip` and `ua`. Call `next(err, data)`: with data, the session is cached for `options.expire` and the request is signed in; without data, the cookie is removed and the request is anonymous. Check in your database that the session still exists, so a signed-out session cannot be used again.\n\nExample: Read the user\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nWrites the session cookie of the built-in session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Object with a `cookie()` method. |\n| `sessionid` | `String` | yes |  | Your session ID. |\n| `userid` | `String` | yes |  | The user ID. |\n| `expiration` | `String|Date` | yes |  | Expiration of the cookie, for example `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Cookie options. |\n\nSigns `sessionid` and `userid` with `options.sign()` and writes them to the cookie `options.cookie`. Call it after you check the credentials and store the session. `options.sign(sessionid, userid)` returns the same token without writing a cookie, for clients that send it in the header `options.header`. `$` is anything with a `cookie()` method: a controller, a schema `$` or the authorization `$`.\n\nExample: Sign in\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nSigns out the current session of the built-in session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | The controller or the session ID. |\n\nReturns: `Boolean` `true` when a session was removed.\n\n`$` is the controller (or another object with `sessionid`), or a session ID string. Removes the session from memory, calls `options.onlogout(session)` and removes the cookie when `$` has a `cookie()` method. Returns `true` when the session was found. Delete the session from your database in `onlogout`, otherwise `onread` can load it again.\n\nExample: Sign out\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nChanges the cached data of all sessions of a user in the built-in session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | The user ID. |\n| `fn` | `Function(data, session)` | yes |  | Called for each session. |\n\nReturns: `Number` Count of sessions.\n\nCalls `fn(data, session)` for every cached session of `userid`, so you can change the user object in place.\n\nExample: Rename the user\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nDrops the cached data of a user in the built-in session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | The user ID. |\n| `exceptsessionid` | `String` | no |  | A session ID to keep. |\n\nReturns: `Number` Count of removed sessions.\n\nRemoves the user's sessions from memory, so the next request calls `onread` again. The cookies stay valid. Pass `exceptsessionid` to keep one session, for example the current one.\n\nExample: Reload after a change\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nThe `$` object the AUTH() delegate receives.\n\nProperties (read-only): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (lower-case path), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` and `$.websocket` (`true` for a WebSocket connection).\n\nMethods: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` and `$.next(is, user)` (alias `$.callback()`). Only the first answer counts; later calls are ignored.\n\nIn a WebSocket connection `$.res` is the WebSocket client, so you cannot write cookies.\n\nExample: Different rules for WebSockets\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nSigns the request in with a user object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | The signed-in user. |\n\nThe user object becomes `controller.user`, `$.user` in schemas and `client.user` in WebSockets. Routes with `+` match; routes with `-` do not. `$.done([user])` returns a callback `function(is, user)` for asynchronous code: a truthy `is` (or `null` with a user) signs the request in, an `Error` marks it as anonymous.\n\nExample: Sign in\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nMarks the request as not signed in.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Optional data for an anonymous visitor. |\n\nRoutes with `-` and routes without a flag match. A user object passed here is still set as `controller.user`, but the request counts as anonymous.\n\nExample: No token\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nStops the authorization and the request processing.\n\nReturns: `AuthOptions` The same object.\n\nUse it when you answer the request yourself in the delegate, for example with a redirect through `$.res`. After `$.cancel()` the framework does not route the request.\n\nExample: Redirect old domains\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nReads or writes a cookie inside the AUTH() delegate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cookie name. |\n| `value` | `String|null` | no |  | New value; `null` removes the cookie. |\n| `expire` | `String|Date` | no |  | Expiration, for example `'1 month'`. |\n| `options` | `Object` | no |  | Cookie options, see `controller.cookie()`. |\n\nReturns: `String|AuthOptions` The value when reading, otherwise `$`.\n\nWith only `name`, returns the cookie value (an empty string when it is missing). With `value`, writes the cookie. With `value` set to `null`, removes it. The same method exists on schema and operation `$` objects.\n\nExample: Remove an invalid cookie\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nLimits a route to signed-in or anonymous visitors.\n\nA URL that starts with `+` (or `🔒`) matches only requests signed in with `$.success()`. A URL that starts with `-` matches only requests marked with `$.invalid()`. A route without a flag matches both. In the flags array, `'authorize'`, `'authorized'` and `'logged'` mean `+`; `'unauthorize'`, `'unauthorized'` and `'unlogged'` mean `-`.\n\nThe same URL can have a `+` and a `-` route. When the only route is for the other state, the response is `401`; with no route at all, `404`. WebSocket routes use the same prefixes; a WebSocket that does not match is closed with code `4001`.\n\nThe flags are checked only when `AUTH()` is registered.\n\nExample: One URL, two routes\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flags in an array\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nMarks a route with roles.\n\nA flag that starts with `@` is a role. It is lower-cased and kept in `controller.route.flags`, and the route needs a signed-in user (as with `+`) unless you add `-`. Total.js does not compare roles with the user: check them in the action, for example with `UNAUTHORIZED()`.\n\nExample: Check the role of the route\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nChecks the roles of the signed-in user and answers 401 when none matches.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | A controller or a schema/operation `$`. |\n| `role` | `String` | yes |  | One or more roles as separate arguments. |\n\nReturns: `Boolean` `true` when the request was refused.\n\nCompares the roles with `$.user.permissions` or `$.user.roles` (an array, or an object whose keys are roles). Returns `false` when the user has one of the roles or when `user.sa` or `user.su` is truthy. Otherwise calls `$.invalid(401)` and returns `true`, also when there is no user.\n\nExample: In a schema\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nCounts attempts from an IP address and tells when to block it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Object with `ip`. |\n| `limit` | `Number` | no | `5` | Allowed attempts. |\n| `expiration` | `String` | no | `'15 minutes'` | How long the counter lives. |\n\nReturns: `Boolean` `true` when the IP address is blocked.\n\nUse it to slow down password guessing. Each call adds one attempt for `$.ip`. Returns `true` when the count is above `limit`. With `limit` set to `-1` or `null`, clears the counter of that IP address, for example after a successful sign-in.\n\nExample: Login form\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nThe user object of a signed-in request.\n\nReturns: `Object`\n\nSet by `$.success(user)`. It is `undefined` for anonymous requests. You can assign it. In schemas and operations read `$.user`; in WebSockets `client.user`.\n\nExample: Use the user\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nThe signed-in user inside schemas and operations.\n\nReturns: `Object`\n\nReturns `controller.user` of the request, or `null` when the operation runs without a controller.\n\nExample: Owner of a record\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nThe session object and the session ID of the request.\n\nReturns: `Object / String`\n\nBoth read and write `req.session` and `req.sessionid`. The built-in `AUTH(options)` sets them to the cached session (`{ sessionid, userid, data, ua, expire }`) and its ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` and `settoken()` set `sessionid`. The same properties exist on schema `$` objects and WebSocket clients.\n\nExample: Sign out of a SESSION() store\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nReads or writes a cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cookie name. |\n| `value` | `String` | no |  | New value. |\n| `expires` | `String|Date|Object` | no |  | Expiration, or the options. |\n| `options` | `Object` | no |  | Cookie options. |\n\nReturns: `String|Controller` The value when reading, otherwise the controller.\n\nWith only `name`, returns the decoded value of the cookie, or an empty string. With `value`, adds a `Set-Cookie` header and returns the controller. To remove a cookie, write an empty value with a past expiration such as `'-1 day'`.\n\n`expires` is a `Date` or a string like `'1 month'`. Instead of `expires` you can pass the options object, which then may contain `expires`.\n\n| Option | Description |\n| --- | --- |\n| `domain` | Cookie domain. |\n| `path` | Cookie path. Default `/`. |\n| `secure` | `true` adds `Secure`. Default `CONF.default_cookies_secure`. |\n| `httponly` | `true` adds `HttpOnly`. |\n| `samesite` or `security` | `'Lax'`, `'Strict'` or `'None'` (or `1` for Lax, `2` for Strict). Default `CONF.default_cookies_samesite`. |\n\nA cookie is not written once the response has been sent.\n\nExample: Write and read\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Remove\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nWrites a cookie to the HTTP response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cookie name. |\n| `value` | `String` | yes |  | Value. |\n| `expires` | `String|Date|Object` | no |  | Expiration, or the options. |\n| `options` | `Object` | no |  | Cookie options. |\n\nReturns: `Response`\n\nThe low-level method behind `controller.cookie()`, with the same options. Use it where you only have the response, for example `$.res` in the AUTH() delegate. `req.cookie(name)` reads a cookie from the request.\n\nExample: From the delegate\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nDefault SameSite attribute of cookies.\n\nReturns: `String`\n\nUsed when a cookie has no `samesite`/`security` option. Default `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nAdds the Secure attribute to every cookie.\n\nReturns: `Boolean`\n\nUsed when a cookie has no `secure` option. Default `false`. Turn it on when the app runs only on HTTPS.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nReturns a named session store.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Name of the store. |\n\nReturns: `Session` The store.\n\nThe first call creates the store and loads its saved sessions; later calls return the same instance. The default name is `default`, saved in `databases/sessions.txt`; other names use `databases/sessions_NAME.txt`. The file is written 10 seconds after a change and holds only the metadata of each session: `sessionid`, `id`, `expire`, `used`, `created`, `note` and `settings`. The user data stays in memory; after a restart the store loads it with `session.ondata`.\n\nA session item has the properties `sessionid`, `id` (user ID), `data`, `expire`, `used`, `created`, `note`, `settings` and `released`. Store properties: `name` and `items` (a `Map` of items by session ID).\n\nExpired sessions are removed every 10 minutes. In a cluster, changes are sent to the other processes.\n\nExample: Create a store\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nLoads the data of a session that is not in memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | The session item: `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback with the data. |\n\nCalled by `get()`, `getcookie()` and `gettoken()` when the item has no data: after a restart or after the data was released. `meta` is the session item. Call `next(err, data)`. Calls for the same user ID wait for one load. Without `ondata`, `release()`, `release2()` do nothing.\n\nExample: Load the user\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nCalled when a session is removed or expires.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | The session item. |\n\nAlso called by `clear()` and `remove2()`. The sibling delegate `session.onrelease = function(item)` is called when the data of a session is released from memory.\n\nExample: Log removed sessions\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nCreates a session and writes its cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Where the cookie is written. |\n| `opt` | `Object` | yes |  | Options, see the table. |\n| `callback` | `Function(err, data, meta)` | no |  | Called after the session is created. |\n\nCalls `session.set()` and writes an encrypted cookie (made with `ENCRYPTREQ()`) with the session ID and the user ID. `res` can be a controller, a schema `$`, the authorization `$` or a response.\n\n| Option | Description |\n| --- | --- |\n| `name` | Cookie name. |\n| `sessionid` | Session ID. Default `UID()`. |\n| `id` | User ID. |\n| `data` | Session data. |\n| `expire` | Expiration, for example `'1 month'`. |\n| `key` (or `secret`) | Encryption key. |\n| `strict` | Bind the cookie to the IP address too. Default `false`. |\n| `note` | A note, for example the user agent. |\n| `settings` | A string with settings. |\n| `options` | Cookie options. Default `{ httponly: true, security: 'lax' }`. |\n\nExample: Sign in\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nReads the session from the cookie of a request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | The authorization `$`, a controller or a request. |\n| `opt` | `Object` | yes |  | Options, see the table. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` is the session data, `meta` the item, `init` is `true` when `ondata` loaded the data. |\n| `param` | `Any` | no |  | A value passed to the callback. |\n\nDecrypts the cookie with `DECRYPTREQ()` and calls `session.get()`. `req` can be the authorization `$`, a controller or a request. Tokens shorter than 20 characters are ignored. An invalid cookie is removed, and with `ddos` each failed attempt is counted for the IP address.\n\n| Option | Description |\n| --- | --- |\n| `name` | Cookie name. |\n| `expire` | Extends the session and the cookie by this time. |\n| `key` (or `secret`) | Encryption key. |\n| `extendcookie` | Extend the cookie with `expire`. Default `true`. |\n| `removecookie` | Remove an invalid cookie. Default `true`. |\n| `options` | Cookie options. |\n| `ddos` | Failed attempts per IP address before the cookie is not checked anymore. |\n\nExample: In AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nCreates a session and returns a token instead of a cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | A controller, a schema `$` or a response. |\n| `opt` | `Object` | yes |  | Options of `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Receives the token. |\n\nTakes the options of `setcookie()` except `name` and `options`, and passes the encrypted token to the callback. Send the token to the client, for example in JSON.\n\nExample: API sign-in\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nReads the session from a token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | The authorization `$` or a request. |\n| `opt` | `Object` | yes |  | Options. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Called with the session. |\n| `param` | `Any` | no |  | A value passed to the callback. |\n\nLike `getcookie()`, with the token in `opt.token`. Options: `token`, `expire`, `key` (or `secret`) and `ddos`.\n\nExample: Token header\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nCreates or replaces a session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session ID. |\n| `id` | `String` | no |  | User ID. |\n| `data` | `Object` | yes |  | Session data. |\n| `expire` | `String` | yes |  | Expiration. |\n| `note` | `String` | no |  | A note. |\n| `settings` | `String` | no |  | Settings. |\n| `callback` | `Function(err, data, meta)` | no |  | Called after the change. |\n\n`id` is the user ID; it can be left out when `data` is an object. `expire` is required, for example `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` replaces the data of all loaded sessions of user `id` and passes the count of updated sessions.\n\nExample: Create a session\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nReads a session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session ID. |\n| `expire` | `String` | no |  | Extends the session by this time. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Called with the session. |\n\nReturns the data through the callback and updates `used`. With `expire`, the session is extended. An expired session is removed. When the data is not in memory, `ondata` loads it and `init` is `true`. `session.get2(id, callback(err, items))` returns all live items of user `id`.\n\nExample: Read\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nChanges a session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session ID. |\n| `data` | `Object` | yes |  | New data. |\n| `expire` | `String` | no |  | New expiration from now. |\n| `note` | `String` | no |  | New note. |\n| `settings` | `String` | no |  | New settings. |\n| `callback` | `Function` | no |  | Called after the change. |\n\nReplaces the data only when it is loaded; `note`, `settings` and `expire` change always. The callback receives `(null, data, meta)`, or no arguments when the session is missing or not loaded. `session.update2(id, data, [expire], [note], [settings], [callback])` does the same for all sessions of user `id` and passes the count of updated sessions.\n\nExample: Update all sessions of a user\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nRemoves a session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | Session ID or item. |\n| `callback` | `Function(err, item)` | no |  | Called after the removal. |\n\n`sessionid` can also be a session item. The callback receives `(null, item)`. `session.remove2(id, [callback])` removes all sessions of user `id` and passes the count, for example to sign a user out everywhere.\n\nExample: Sign out\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Sign out everywhere\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nFrees the data of a session from memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | Session ID or item. |\n| `expire` | `String` | no |  | Used by `release2()`. |\n| `callback` | `Function(err, count)` | no |  | Called with the count. |\n\nThe session stays valid; the next read loads the data again with `ondata`. Without `sessionid` (or with `null`), releases every session and passes the count. `session.release2(id, [expire], [callback])` releases all sessions of user `id` and, with `expire`, sets their new expiration. `session.releaseunused(lastusage, [callback])` releases sessions not used for `lastusage`, for example `'30 minutes'`; the framework calls it every 10 minutes with `CONF.allow_sessions_unused` (default `'-20 minutes'`). Without `ondata`, `release()` and `release2()` do nothing.\n\nExample: Reload a user after a change\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nReturns a session only when its data is in memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session ID. |\n| `callback` | `Function(err, data, meta)` | yes |  | Called with the result. |\n\nUnlike `get()`, it never calls `ondata`. The callback receives `(null, data, meta)` or no arguments. `session.contains2(id, callback)` finds the first such session of user `id`. `session.has(sessionid, callback(err, bool))` and `session.has2(id, callback(err, bool))` only tell whether a session exists.\n\nExample: Is the user online?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nLists the live sessions of a user.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | User ID. |\n| `callback` | `Function(err, items)` | yes |  | Called with the items. |\n\nPasses an array of session items of user `id` and removes expired items. `session.listlive(callback)` lists all sessions with loaded data, for any user.\n\nExample: Devices of a user\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nCounts sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | User ID. |\n| `callback` | `Function(err, stats)` | yes |  | Called with the counts. |\n\nPasses `{ used, free, count }`: `used` sessions have loaded data, `free` do not. With `id`, counts only the sessions of that user. `session.usage()` returns the same object for all sessions directly.\n\nExample: Stats\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nRemoves sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Unused time. |\n| `callback` | `Function(err, count)` | no |  | Called after the removal. |\n\nWith `lastusage` (for example `'7 days'`), removes the sessions not used for that time and passes their count. Without it, removes every session. `session.clean()` removes only expired sessions; the framework calls it every 10 minutes. `session.load([callback])` reads the saved sessions from the file again; `SESSION()` calls it on creation.\n\nExample: Remove old sessions\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nReleases the data of SESSION() items unused for this time.\n\nReturns: `String`\n\nEvery 10 minutes the framework calls `releaseunused()` with this value on every session store. Default `'-20 minutes'`. The sessions stay valid; their data is loaded again with `ondata`.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Autorisierung","summary":"AUTH(), Routen-Flags, Rollen, Cookies und der Store SESSION().","markdown":"---\ntitle: Autorisierung\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorisierung\n\n> AUTH(), Routen-Flags, Rollen, Cookies und der Store SESSION().\n\nTotal.js meldet Requests mit dem Delegate `AUTH()` an, beschränkt Routen mit den Flags `+` und `-` und verwaltet Sessions mit der eingebauten Cookie-Session oder dem Store `SESSION()`. Der Guide [Autorisierung](../../guides/authorization/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\nDie Verschlüsselung hat eine eigene Seite: [Verschlüsselung](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nRegistriert das Delegate, das jeden Request anmeldet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | Das Delegate. `$` ist das Autorisierungsobjekt. |\n\nReturns: `undefined`\n\nDas Delegate läuft für jeden HTTP-Request, der das Routing erreicht, und für jede WebSocket-Verbindung. Es erhält ein Autorisierungsobjekt `$` (siehe `$.success()`, `$.invalid()` und die Eigenschaften von `$`). Es muss genau eine der Methoden `$.success(user)`, `$.invalid()` oder `$.cancel()` aufrufen. Ein neu registriertes Delegate ersetzt das vorherige.\n\nÜbergibst du statt einer Funktion ein Objekt, startet die eingebaute Cookie-Session, siehe `AUTH(options)`.\n\nExample: Anmeldung mit einem Token-Header\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nStartet den eingebauten Cookie-Session-Mechanismus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Optionen und Delegates der Session, siehe Tabelle. |\n\nReturns: `undefined` Die Methoden werden zu `options` hinzugefügt.\n\nMit einem Objekt registriert `AUTH()` sein eigenes Delegate. Es liest das Session-Token aus dem Cookie `options.cookie` (oder aus dem Header `options.header`), entschlüsselt es mit `options.secret` und hält die Benutzerdaten für `options.expire` im Speicher. Sind die Daten nicht im Cache, ruft es `options.onread()` auf. Requests, die auf dieselbe Session warten, teilen sich einen Aufruf von `onread()`.\n\n`AUTH()` gibt nichts zurück, fügt aber dem übergebenen Objekt Methoden hinzu: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` und `auth()` (das Delegate selbst). Behalte eine Referenz auf das Objekt.\n\n| Option | Typ | Beschreibung |\n| --- | --- | --- |\n| `secret` | String | Schlüssel zum Verschlüsseln des Tokens. Setze ihn immer. |\n| `cookie` | String | Name des Cookies mit dem Token. |\n| `header` | String | Name eines Request-Headers mit dem Token, verwendet, wenn das Cookie fehlt. Schreibe ihn in Kleinbuchstaben. |\n| `expire` | String | Wie lange Benutzerdaten im Speicher bleiben. Standard `'5 minutes'`. |\n| `strict` | Boolean | Die gecachte Session funktioniert nur mit demselben User-Agent. Standard `true`. |\n| `ddos` | Number | Fehlversuche pro IP-Adresse, bevor jeder Request dieser IP ungültig ist. Die Zähler werden bei jeder Bereinigung zurückgesetzt. |\n| `cleaner` | Number | Bereinigungsintervall in Minuten. Standard `5`. |\n| `options` | Object | Cookie-Optionen, die beim Schreiben oder Entfernen des Cookies verwendet werden. |\n| `onread` | Function(meta, next, $) | Lädt die Benutzerdaten, siehe `options.onread`. |\n| `onsession` | Function(session, $, init) | Wird aufgerufen, wenn eine Session gefunden wird. Gib `true` zurück, um die Verarbeitung zu beenden; beantworte `$` dann selbst. `init` ist `true`, wenn die Daten gerade geladen wurden. |\n| `onauthorize` | Function($) | Wird für jeden Request zuerst aufgerufen. Gib `true` zurück, um die eingebaute Verarbeitung zu überspringen; beantworte `$` dann selbst. |\n| `onlogout` | Function(session) | Wird von `logout()` aufgerufen. |\n| `onfree` | Function(meta) | Wird nach der Bereinigung mit `{ sessions: Array, users: Array }` aufgerufen: die entfernten Session-IDs und die Benutzer-IDs ohne aktive Session. |\n| `onddos` | Function($) | Wird aufgerufen, wenn eine blockierte IP-Adresse einen Request stellt. |\n| `locale` | Function(data, req) | Gibt die Sprache des Requests zurück. `data` ist `null` für anonyme Besucher. |\n\nEin ungültiges oder unbekanntes Token entfernt das Cookie.\n\nExample: Eingebaute Session\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Sprache des Benutzers\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nLädt in der eingebauten Session die Benutzerdaten zu einem Session-Token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback mit den Benutzerdaten. |\n| `$` | `Object` | yes |  | Das Autorisierungsobjekt. |\n\nWird aufgerufen, wenn ein gültiges Token keine gecachten Daten hat. `meta` enthält `sessionid`, `userid`, `ip` und `ua`. Rufe `next(err, data)` auf: Mit Daten wird die Session für `options.expire` gecacht und der Request ist angemeldet; ohne Daten wird das Cookie entfernt und der Request ist anonym. Prüfe in deiner Datenbank, ob die Session noch existiert, damit eine abgemeldete Session nicht erneut verwendet werden kann.\n\nExample: Den Benutzer lesen\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nSchreibt das Session-Cookie der eingebauten Session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objekt mit einer Methode `cookie()`. |\n| `sessionid` | `String` | yes |  | Deine Session-ID. |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n| `expiration` | `String|Date` | yes |  | Ablauf des Cookies, zum Beispiel `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Cookie-Optionen. |\n\nSigniert `sessionid` und `userid` mit `options.sign()` und schreibt sie in das Cookie `options.cookie`. Rufe es auf, nachdem du die Zugangsdaten geprüft und die Session gespeichert hast. `options.sign(sessionid, userid)` gibt dasselbe Token zurück, ohne ein Cookie zu schreiben, für Clients, die es im Header `options.header` senden. `$` ist alles mit einer Methode `cookie()`: ein Controller, ein Schema-`$` oder das Autorisierungs-`$`.\n\nExample: Anmelden\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nMeldet die aktuelle Session der eingebauten Session ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | Der Controller oder die Session-ID. |\n\nReturns: `Boolean` `true`, wenn eine Session entfernt wurde.\n\n`$` ist der Controller (oder ein anderes Objekt mit `sessionid`) oder ein String mit der Session-ID. Entfernt die Session aus dem Speicher, ruft `options.onlogout(session)` auf und entfernt das Cookie, wenn `$` eine Methode `cookie()` hat. Gibt `true` zurück, wenn die Session gefunden wurde. Lösche die Session in `onlogout` aus deiner Datenbank, sonst kann `onread` sie wieder laden.\n\nExample: Abmelden\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nÄndert in der eingebauten Session die gecachten Daten aller Sessions eines Benutzers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n| `fn` | `Function(data, session)` | yes |  | Wird für jede Session aufgerufen. |\n\nReturns: `Number` Anzahl der Sessions.\n\nRuft `fn(data, session)` für jede gecachte Session von `userid` auf, sodass du das Benutzerobjekt direkt ändern kannst.\n\nExample: Den Benutzer umbenennen\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nVerwirft in der eingebauten Session die gecachten Daten eines Benutzers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | Die Benutzer-ID. |\n| `exceptsessionid` | `String` | no |  | Eine Session-ID, die erhalten bleibt. |\n\nReturns: `Number` Anzahl der entfernten Sessions.\n\nEntfernt die Sessions des Benutzers aus dem Speicher, sodass der nächste Request wieder `onread` aufruft. Die Cookies bleiben gültig. Übergib `exceptsessionid`, um eine Session zu behalten, zum Beispiel die aktuelle.\n\nExample: Nach einer Änderung neu laden\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nDas Objekt `$`, das das Delegate AUTH() erhält.\n\nEigenschaften (schreibgeschützt): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (Pfad in Kleinbuchstaben), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` und `$.websocket` (`true` bei einer WebSocket-Verbindung).\n\nMethoden: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` und `$.next(is, user)` (Alias `$.callback()`). Nur die erste Antwort zählt; spätere Aufrufe werden ignoriert.\n\nBei einer WebSocket-Verbindung ist `$.res` der WebSocket-Client, daher kannst du keine Cookies schreiben.\n\nExample: Unterschiedliche Regeln für WebSockets\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nMeldet den Request mit einem Benutzerobjekt an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Der angemeldete Benutzer. |\n\nDas Benutzerobjekt wird zu `controller.user`, zu `$.user` in Schemas und zu `client.user` in WebSockets. Routen mit `+` passen, Routen mit `-` nicht. `$.done([user])` gibt für asynchronen Code ein Callback `function(is, user)` zurück: Ein truthy `is` (oder `null` mit einem Benutzer) meldet den Request an, ein `Error` markiert ihn als anonym.\n\nExample: Anmelden\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nMarkiert den Request als nicht angemeldet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Optionale Daten für einen anonymen Besucher. |\n\nRouten mit `-` und Routen ohne Flag passen. Ein hier übergebenes Benutzerobjekt wird trotzdem als `controller.user` gesetzt, aber der Request gilt als anonym.\n\nExample: Kein Token\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nBeendet die Autorisierung und die Verarbeitung des Requests.\n\nReturns: `AuthOptions` Dasselbe Objekt.\n\nVerwende es, wenn du den Request im Delegate selbst beantwortest, zum Beispiel mit einer Weiterleitung über `$.res`. Nach `$.cancel()` routet das Framework den Request nicht.\n\nExample: Alte Domains weiterleiten\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLiest oder schreibt ein Cookie im Delegate AUTH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Cookies. |\n| `value` | `String|null` | no |  | Neuer Wert; `null` entfernt das Cookie. |\n| `expire` | `String|Date` | no |  | Ablauf, zum Beispiel `'1 month'`. |\n| `options` | `Object` | no |  | Cookie-Optionen, siehe `controller.cookie()`. |\n\nReturns: `String|AuthOptions` Beim Lesen der Wert, sonst `$`.\n\nNur mit `name` gibt es den Wert des Cookies zurück (einen leeren String, wenn es fehlt). Mit `value` schreibt es das Cookie. Ist `value` auf `null` gesetzt, entfernt es das Cookie. Dieselbe Methode gibt es bei den `$`-Objekten von Schemas und Operationen.\n\nExample: Ein ungültiges Cookie entfernen\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nBeschränkt eine Route auf angemeldete oder anonyme Besucher.\n\nEine URL, die mit `+` (oder `🔒`) beginnt, passt nur zu Requests, die mit `$.success()` angemeldet wurden. Eine URL, die mit `-` beginnt, passt nur zu Requests, die mit `$.invalid()` markiert wurden. Eine Route ohne Flag passt zu beiden. Im Flags-Array bedeuten `'authorize'`, `'authorized'` und `'logged'` dasselbe wie `+`; `'unauthorize'`, `'unauthorized'` und `'unlogged'` dasselbe wie `-`.\n\nDieselbe URL kann eine Route mit `+` und eine mit `-` haben. Gibt es nur eine Route für den anderen Zustand, lautet die Response `401`; gibt es gar keine Route, `404`. WebSocket-Routen verwenden dieselben Präfixe; ein WebSocket, der nicht passt, wird mit dem Code `4001` geschlossen.\n\nDie Flags werden nur geprüft, wenn `AUTH()` registriert ist.\n\nExample: Eine URL, zwei Routen\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flags in einem Array\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nKennzeichnet eine Route mit Rollen.\n\nEin Flag, das mit `@` beginnt, ist eine Rolle. Es wird in Kleinbuchstaben umgewandelt und in `controller.route.flags` gespeichert, und die Route braucht einen angemeldeten Benutzer (wie bei `+`), sofern du nicht `-` hinzufügst. Total.js vergleicht die Rollen nicht mit dem Benutzer: Prüfe sie in der Action, zum Beispiel mit `UNAUTHORIZED()`.\n\nExample: Die Rolle der Route prüfen\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nPrüft die Rollen des angemeldeten Benutzers und antwortet mit 401, wenn keine passt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Ein Controller oder ein `$` eines Schemas/einer Operation. |\n| `role` | `String` | yes |  | Eine oder mehrere Rollen als einzelne Argumente. |\n\nReturns: `Boolean` `true`, wenn der Request abgelehnt wurde.\n\nVergleicht die Rollen mit `$.user.permissions` oder `$.user.roles` (ein Array oder ein Objekt, dessen Schlüssel Rollen sind). Gibt `false` zurück, wenn der Benutzer eine der Rollen hat oder wenn `user.sa` oder `user.su` truthy ist. Andernfalls ruft es `$.invalid(401)` auf und gibt `true` zurück, auch wenn kein Benutzer vorhanden ist.\n\nExample: In einem Schema\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nZählt Versuche von einer IP-Adresse und sagt, wann sie blockiert werden soll.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objekt mit `ip`. |\n| `limit` | `Number` | no | `5` | Erlaubte Versuche. |\n| `expiration` | `String` | no | `'15 minutes'` | Wie lange der Zähler bestehen bleibt. |\n\nReturns: `Boolean` `true`, wenn die IP-Adresse blockiert ist.\n\nVerwende es, um das Erraten von Passwörtern zu bremsen. Jeder Aufruf fügt einen Versuch für `$.ip` hinzu. Gibt `true` zurück, wenn die Anzahl über `limit` liegt. Ist `limit` auf `-1` oder `null` gesetzt, wird der Zähler dieser IP-Adresse gelöscht, zum Beispiel nach einer erfolgreichen Anmeldung.\n\nExample: Anmeldeformular\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nDas Benutzerobjekt eines angemeldeten Requests.\n\nReturns: `Object`\n\nWird von `$.success(user)` gesetzt. Bei anonymen Requests ist es `undefined`. Du kannst es zuweisen. In Schemas und Operationen liest du `$.user`, in WebSockets `client.user`.\n\nExample: Den Benutzer verwenden\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nDer angemeldete Benutzer in Schemas und Operationen.\n\nReturns: `Object`\n\nGibt `controller.user` des Requests zurück oder `null`, wenn die Operation ohne Controller läuft.\n\nExample: Eigentümer eines Datensatzes\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nDas Session-Objekt und die Session-ID des Requests.\n\nReturns: `Object / String`\n\nBeide lesen und schreiben `req.session` und `req.sessionid`. Das eingebaute `AUTH(options)` setzt sie auf die gecachte Session (`{ sessionid, userid, data, ua, expire }`) und ihre ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` und `settoken()` setzen `sessionid`. Dieselben Eigenschaften gibt es bei den `$`-Objekten von Schemas und bei WebSocket-Clients.\n\nExample: Von einem Store SESSION() abmelden\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLiest oder schreibt ein Cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Cookies. |\n| `value` | `String` | no |  | Neuer Wert. |\n| `expires` | `String|Date|Object` | no |  | Ablauf oder die Optionen. |\n| `options` | `Object` | no |  | Cookie-Optionen. |\n\nReturns: `String|Controller` Beim Lesen der Wert, sonst der Controller.\n\nNur mit `name` gibt es den dekodierten Wert des Cookies zurück oder einen leeren String. Mit `value` fügt es einen Header `Set-Cookie` hinzu und gibt den Controller zurück. Um ein Cookie zu entfernen, schreibe einen leeren Wert mit einem Ablauf in der Vergangenheit wie `'-1 day'`.\n\n`expires` ist ein `Date` oder ein String wie `'1 month'`. Statt `expires` kannst du das Options-Objekt übergeben, das dann `expires` enthalten darf.\n\n| Option | Beschreibung |\n| --- | --- |\n| `domain` | Domain des Cookies. |\n| `path` | Pfad des Cookies. Standard `/`. |\n| `secure` | `true` fügt `Secure` hinzu. Standard `CONF.default_cookies_secure`. |\n| `httponly` | `true` fügt `HttpOnly` hinzu. |\n| `samesite` oder `security` | `'Lax'`, `'Strict'` oder `'None'` (oder `1` für Lax, `2` für Strict). Standard `CONF.default_cookies_samesite`. |\n\nNachdem die Response gesendet wurde, wird kein Cookie mehr geschrieben.\n\nExample: Schreiben und lesen\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Entfernen\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nSchreibt ein Cookie in die HTTP-Response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Cookies. |\n| `value` | `String` | yes |  | Wert. |\n| `expires` | `String|Date|Object` | no |  | Ablauf oder die Optionen. |\n| `options` | `Object` | no |  | Cookie-Optionen. |\n\nReturns: `Response`\n\nDie Low-Level-Methode hinter `controller.cookie()`, mit denselben Optionen. Verwende sie dort, wo du nur die Response hast, zum Beispiel `$.res` im Delegate AUTH(). `req.cookie(name)` liest ein Cookie aus dem Request.\n\nExample: Aus dem Delegate\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nStandardwert des Attributs SameSite von Cookies.\n\nReturns: `String`\n\nWird verwendet, wenn ein Cookie keine Option `samesite`/`security` hat. Standard `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nFügt jedem Cookie das Attribut Secure hinzu.\n\nReturns: `Boolean`\n\nWird verwendet, wenn ein Cookie keine Option `secure` hat. Standard `false`. Schalte es ein, wenn die App nur über HTTPS läuft.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nGibt einen benannten Session-Store zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Name des Stores. |\n\nReturns: `Session` Der Store.\n\nDer erste Aufruf erstellt den Store und lädt seine gespeicherten Sessions; spätere Aufrufe geben dieselbe Instanz zurück. Der Standardname ist `default`, gespeichert in `databases/sessions.txt`; andere Namen verwenden `databases/sessions_NAME.txt`. Die Datei wird 10 Sekunden nach einer Änderung geschrieben und enthält nur die Metadaten jeder Session: `sessionid`, `id`, `expire`, `used`, `created`, `note` und `settings`. Die Benutzerdaten bleiben im Speicher; nach einem Neustart lädt der Store sie mit `session.ondata`.\n\nEin Session-Eintrag hat die Eigenschaften `sessionid`, `id` (Benutzer-ID), `data`, `expire`, `used`, `created`, `note`, `settings` und `released`. Eigenschaften des Stores: `name` und `items` (eine `Map` der Einträge nach Session-ID).\n\nAbgelaufene Sessions werden alle 10 Minuten entfernt. In einem Cluster werden Änderungen an die anderen Prozesse gesendet.\n\nExample: Einen Store erstellen\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nLädt die Daten einer Session, die nicht im Speicher ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Der Session-Eintrag: `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback mit den Daten. |\n\nWird von `get()`, `getcookie()` und `gettoken()` aufgerufen, wenn der Eintrag keine Daten hat: nach einem Neustart oder nachdem die Daten freigegeben wurden. `meta` ist der Session-Eintrag. Rufe `next(err, data)` auf. Aufrufe für dieselbe Benutzer-ID warten auf einen einzigen Ladevorgang. Ohne `ondata` tun `release()`, `release2()` nichts.\n\nExample: Den Benutzer laden\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nWird aufgerufen, wenn eine Session entfernt wird oder abläuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Der Session-Eintrag. |\n\nWird auch von `clear()` und `remove2()` aufgerufen. Das verwandte Delegate `session.onrelease = function(item)` wird aufgerufen, wenn die Daten einer Session aus dem Speicher freigegeben werden.\n\nExample: Entfernte Sessions protokollieren\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nErstellt eine Session und schreibt ihr Cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Wohin das Cookie geschrieben wird. |\n| `opt` | `Object` | yes |  | Optionen, siehe Tabelle. |\n| `callback` | `Function(err, data, meta)` | no |  | Wird aufgerufen, nachdem die Session erstellt wurde. |\n\nRuft `session.set()` auf und schreibt ein verschlüsseltes Cookie (erzeugt mit `ENCRYPTREQ()`) mit der Session-ID und der Benutzer-ID. `res` kann ein Controller, ein Schema-`$`, das Autorisierungs-`$` oder eine Response sein.\n\n| Option | Beschreibung |\n| --- | --- |\n| `name` | Name des Cookies. |\n| `sessionid` | Session-ID. Standard `UID()`. |\n| `id` | Benutzer-ID. |\n| `data` | Session-Daten. |\n| `expire` | Ablauf, zum Beispiel `'1 month'`. |\n| `key` (oder `secret`) | Verschlüsselungsschlüssel. |\n| `strict` | Das Cookie auch an die IP-Adresse binden. Standard `false`. |\n| `note` | Eine Notiz, zum Beispiel der User-Agent. |\n| `settings` | Ein String mit Einstellungen. |\n| `options` | Cookie-Optionen. Standard `{ httponly: true, security: 'lax' }`. |\n\nExample: Anmelden\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nLiest die Session aus dem Cookie eines Requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Das Autorisierungs-`$`, ein Controller oder ein Request. |\n| `opt` | `Object` | yes |  | Optionen, siehe Tabelle. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` sind die Session-Daten, `meta` der Eintrag, `init` ist `true`, wenn `ondata` die Daten geladen hat. |\n| `param` | `Any` | no |  | Ein Wert, der an das Callback übergeben wird. |\n\nEntschlüsselt das Cookie mit `DECRYPTREQ()` und ruft `session.get()` auf. `req` kann das Autorisierungs-`$`, ein Controller oder ein Request sein. Tokens mit weniger als 20 Zeichen werden ignoriert. Ein ungültiges Cookie wird entfernt, und mit `ddos` wird jeder Fehlversuch für die IP-Adresse gezählt.\n\n| Option | Beschreibung |\n| --- | --- |\n| `name` | Name des Cookies. |\n| `expire` | Verlängert die Session und das Cookie um diese Zeit. |\n| `key` (oder `secret`) | Verschlüsselungsschlüssel. |\n| `extendcookie` | Das Cookie um `expire` verlängern. Standard `true`. |\n| `removecookie` | Ein ungültiges Cookie entfernen. Standard `true`. |\n| `options` | Cookie-Optionen. |\n| `ddos` | Fehlversuche pro IP-Adresse, bevor das Cookie nicht mehr geprüft wird. |\n\nExample: In AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nErstellt eine Session und gibt statt eines Cookies ein Token zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | Ein Controller, ein Schema-`$` oder eine Response. |\n| `opt` | `Object` | yes |  | Optionen von `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Erhält das Token. |\n\nNimmt die Optionen von `setcookie()` außer `name` und `options` und übergibt das verschlüsselte Token an das Callback. Sende das Token an den Client, zum Beispiel in JSON.\n\nExample: Anmeldung über die API\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nLiest die Session aus einem Token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Das Autorisierungs-`$` oder ein Request. |\n| `opt` | `Object` | yes |  | Optionen. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Wird mit der Session aufgerufen. |\n| `param` | `Any` | no |  | Ein Wert, der an das Callback übergeben wird. |\n\nWie `getcookie()`, mit dem Token in `opt.token`. Optionen: `token`, `expire`, `key` (oder `secret`) und `ddos`.\n\nExample: Token-Header\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nErstellt oder ersetzt eine Session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session-ID. |\n| `id` | `String` | no |  | Benutzer-ID. |\n| `data` | `Object` | yes |  | Session-Daten. |\n| `expire` | `String` | yes |  | Ablauf. |\n| `note` | `String` | no |  | Eine Notiz. |\n| `settings` | `String` | no |  | Einstellungen. |\n| `callback` | `Function(err, data, meta)` | no |  | Wird nach der Änderung aufgerufen. |\n\n`id` ist die Benutzer-ID; sie kann weggelassen werden, wenn `data` ein Objekt ist. `expire` ist erforderlich, zum Beispiel `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` ersetzt die Daten aller geladenen Sessions des Benutzers `id` und übergibt die Anzahl der aktualisierten Sessions.\n\nExample: Eine Session erstellen\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nLiest eine Session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session-ID. |\n| `expire` | `String` | no |  | Verlängert die Session um diese Zeit. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Wird mit der Session aufgerufen. |\n\nGibt die Daten über das Callback zurück und aktualisiert `used`. Mit `expire` wird die Session verlängert. Eine abgelaufene Session wird entfernt. Sind die Daten nicht im Speicher, lädt `ondata` sie und `init` ist `true`. `session.get2(id, callback(err, items))` gibt alle aktiven Einträge des Benutzers `id` zurück.\n\nExample: Lesen\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nÄndert eine Session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session-ID. |\n| `data` | `Object` | yes |  | Neue Daten. |\n| `expire` | `String` | no |  | Neuer Ablauf ab jetzt. |\n| `note` | `String` | no |  | Neue Notiz. |\n| `settings` | `String` | no |  | Neue Einstellungen. |\n| `callback` | `Function` | no |  | Wird nach der Änderung aufgerufen. |\n\nErsetzt die Daten nur, wenn sie geladen sind; `note`, `settings` und `expire` ändern sich immer. Das Callback erhält `(null, data, meta)` oder keine Argumente, wenn die Session fehlt oder nicht geladen ist. `session.update2(id, data, [expire], [note], [settings], [callback])` tut dasselbe für alle Sessions des Benutzers `id` und übergibt die Anzahl der aktualisierten Sessions.\n\nExample: Alle Sessions eines Benutzers aktualisieren\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nEntfernt eine Session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | Session-ID oder Eintrag. |\n| `callback` | `Function(err, item)` | no |  | Wird nach dem Entfernen aufgerufen. |\n\n`sessionid` kann auch ein Session-Eintrag sein. Das Callback erhält `(null, item)`. `session.remove2(id, [callback])` entfernt alle Sessions des Benutzers `id` und übergibt die Anzahl, zum Beispiel um einen Benutzer überall abzumelden.\n\nExample: Abmelden\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Überall abmelden\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nGibt die Daten einer Session aus dem Speicher frei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | Session-ID oder Eintrag. |\n| `expire` | `String` | no |  | Wird von `release2()` verwendet. |\n| `callback` | `Function(err, count)` | no |  | Wird mit der Anzahl aufgerufen. |\n\nDie Session bleibt gültig; beim nächsten Lesen werden die Daten wieder mit `ondata` geladen. Ohne `sessionid` (oder mit `null`) werden alle Sessions freigegeben und die Anzahl übergeben. `session.release2(id, [expire], [callback])` gibt alle Sessions des Benutzers `id` frei und setzt mit `expire` ihren neuen Ablauf. `session.releaseunused(lastusage, [callback])` gibt Sessions frei, die seit `lastusage` nicht verwendet wurden, zum Beispiel `'30 minutes'`; das Framework ruft es alle 10 Minuten mit `CONF.allow_sessions_unused` auf (Standard `'-20 minutes'`). Ohne `ondata` tun `release()` und `release2()` nichts.\n\nExample: Einen Benutzer nach einer Änderung neu laden\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nGibt eine Session nur zurück, wenn ihre Daten im Speicher sind.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | Session-ID. |\n| `callback` | `Function(err, data, meta)` | yes |  | Wird mit dem Ergebnis aufgerufen. |\n\nAnders als `get()` ruft es nie `ondata` auf. Das Callback erhält `(null, data, meta)` oder keine Argumente. `session.contains2(id, callback)` findet die erste solche Session des Benutzers `id`. `session.has(sessionid, callback(err, bool))` und `session.has2(id, callback(err, bool))` sagen nur, ob eine Session existiert.\n\nExample: Ist der Benutzer online?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nListet die aktiven Sessions eines Benutzers auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Benutzer-ID. |\n| `callback` | `Function(err, items)` | yes |  | Wird mit den Einträgen aufgerufen. |\n\nÜbergibt ein Array der Session-Einträge des Benutzers `id` und entfernt abgelaufene Einträge. `session.listlive(callback)` listet alle Sessions mit geladenen Daten auf, für beliebige Benutzer.\n\nExample: Geräte eines Benutzers\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nZählt Sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | Benutzer-ID. |\n| `callback` | `Function(err, stats)` | yes |  | Wird mit den Zählern aufgerufen. |\n\nÜbergibt `{ used, free, count }`: `used`-Sessions haben geladene Daten, `free`-Sessions nicht. Mit `id` werden nur die Sessions dieses Benutzers gezählt. `session.usage()` gibt dasselbe Objekt für alle Sessions direkt zurück.\n\nExample: Statistik\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nEntfernt Sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Ungenutzte Zeit. |\n| `callback` | `Function(err, count)` | no |  | Wird nach dem Entfernen aufgerufen. |\n\nMit `lastusage` (zum Beispiel `'7 days'`) werden die Sessions entfernt, die so lange nicht verwendet wurden, und ihre Anzahl übergeben. Ohne den Parameter werden alle Sessions entfernt. `session.clean()` entfernt nur abgelaufene Sessions; das Framework ruft es alle 10 Minuten auf. `session.load([callback])` liest die gespeicherten Sessions erneut aus der Datei; `SESSION()` ruft es beim Erstellen auf.\n\nExample: Alte Sessions entfernen\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nGibt die Daten von SESSION()-Einträgen frei, die so lange nicht verwendet wurden.\n\nReturns: `String`\n\nAlle 10 Minuten ruft das Framework bei jedem Session-Store `releaseunused()` mit diesem Wert auf. Standard `'-20 minutes'`. Die Sessions bleiben gültig; ihre Daten werden wieder mit `ondata` geladen.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Autorización","summary":"AUTH(), flags de ruta, roles, cookies y el almacén SESSION().","markdown":"---\ntitle: \"Autorización\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorización\n\n> AUTH(), flags de ruta, roles, cookies y el almacén SESSION().\n\nTotal.js autentica las peticiones con el delegado `AUTH()`, limita las rutas con los flags `+` y `-`, y mantiene las sesiones con la sesión por cookie integrada o con el almacén `SESSION()`. La guía [Autorización](../../guides/authorization/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\nEl cifrado tiene su propia página: [Cifrado](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nRegistra el delegado que autentica cada petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | El delegado. `$` es el objeto de autorización. |\n\nReturns: `undefined`\n\nEl delegado se ejecuta en cada petición HTTP que llega al enrutamiento y en cada conexión WebSocket. Recibe un objeto de autorización `$` (consulta `$.success()`, `$.invalid()` y las propiedades de `$`). Debe llamar exactamente a uno de `$.success(user)`, `$.invalid()` o `$.cancel()`. Registrar un nuevo delegado reemplaza al anterior.\n\nPasar un objeto en lugar de una función inicia la sesión por cookie integrada, consulta `AUTH(options)`.\n\nExample: Autenticar con una cabecera de token\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nInicia el mecanismo integrado de sesión por cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Opciones y delegados de la sesión, consulta la tabla. |\n\nReturns: `undefined` Los métodos se añaden a `options`.\n\nCon un objeto, `AUTH()` registra su propio delegado. Lee el token de sesión de la cookie `options.cookie` (o de la cabecera `options.header`), lo descifra con `options.secret` y guarda los datos del usuario en memoria durante `options.expire`. Cuando los datos no están en caché, llama a `options.onread()`. Las peticiones que esperan la misma sesión comparten una única llamada a `onread()`.\n\n`AUTH()` no devuelve nada, pero añade métodos al objeto que le pasas: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` y `auth()` (el propio delegado). Guarda una referencia al objeto.\n\n| Opción | Tipo | Descripción |\n| --- | --- | --- |\n| `secret` | String | Clave para cifrar el token. Defínela siempre. |\n| `cookie` | String | Nombre de la cookie con el token. |\n| `header` | String | Nombre de una cabecera de la petición con el token, usada cuando falta la cookie. Escríbela en minúsculas. |\n| `expire` | String | Cuánto tiempo permanecen los datos del usuario en memoria. Por defecto `'5 minutes'`. |\n| `strict` | Boolean | La sesión en caché solo funciona con el mismo user agent. Por defecto `true`. |\n| `ddos` | Number | Intentos fallidos por dirección IP antes de que todas las peticiones de esa IP sean inválidas. Los contadores se reinician con cada limpieza. |\n| `cleaner` | Number | Intervalo de limpieza en minutos. Por defecto `5`. |\n| `options` | Object | Opciones de cookie usadas cuando la cookie se escribe o se elimina. |\n| `onread` | Function(meta, next, $) | Carga los datos del usuario, consulta `options.onread`. |\n| `onsession` | Function(session, $, init) | Se llama cuando se encuentra una sesión. Devuelve `true` para detener el procesamiento; entonces responde tú mismo a `$`. `init` es `true` cuando los datos se acaban de cargar. |\n| `onauthorize` | Function($) | Se llama primero en cada petición. Devuelve `true` para omitir el procesamiento integrado; entonces responde tú mismo a `$`. |\n| `onlogout` | Function(session) | Lo llama `logout()`. |\n| `onfree` | Function(meta) | Se llama tras la limpieza con `{ sessions: Array, users: Array }`: los IDs de sesión eliminados y los IDs de usuario sin ninguna sesión activa. |\n| `onddos` | Function($) | Se llama cuando una dirección IP bloqueada hace una petición. |\n| `locale` | Function(data, req) | Devuelve el idioma de la petición. `data` es `null` para visitantes anónimos. |\n\nUn token inválido o desconocido elimina la cookie.\n\nExample: Sesión integrada\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Idioma del usuario\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nCarga los datos del usuario para un token de sesión en la sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback con los datos del usuario. |\n| `$` | `Object` | yes |  | El objeto de autorización. |\n\nSe llama cuando un token válido no tiene datos en caché. `meta` contiene `sessionid`, `userid`, `ip` y `ua`. Llama a `next(err, data)`: con datos, la sesión se guarda en caché durante `options.expire` y la petición queda autenticada; sin datos, la cookie se elimina y la petición es anónima. Comprueba en tu base de datos que la sesión sigue existiendo, para que una sesión cerrada no pueda volver a usarse.\n\nExample: Leer el usuario\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nEscribe la cookie de sesión de la sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objeto con un método `cookie()`. |\n| `sessionid` | `String` | yes |  | Tu ID de sesión. |\n| `userid` | `String` | yes |  | El ID del usuario. |\n| `expiration` | `String|Date` | yes |  | Caducidad de la cookie, por ejemplo `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Opciones de la cookie. |\n\nFirma `sessionid` y `userid` con `options.sign()` y los escribe en la cookie `options.cookie`. Llámalo después de comprobar las credenciales y guardar la sesión. `options.sign(sessionid, userid)` devuelve el mismo token sin escribir una cookie, para clientes que lo envían en la cabecera `options.header`. `$` es cualquier cosa con un método `cookie()`: un controlador, un `$` de esquema o el `$` de autorización.\n\nExample: Iniciar sesión\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nCierra la sesión actual de la sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | El controlador o el ID de sesión. |\n\nReturns: `Boolean` `true` cuando se eliminó una sesión.\n\n`$` es el controlador (u otro objeto con `sessionid`), o una cadena con el ID de sesión. Elimina la sesión de la memoria, llama a `options.onlogout(session)` y elimina la cookie cuando `$` tiene un método `cookie()`. Devuelve `true` cuando se encontró la sesión. Borra la sesión de tu base de datos en `onlogout`; si no, `onread` puede volver a cargarla.\n\nExample: Cerrar sesión\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nCambia los datos en caché de todas las sesiones de un usuario en la sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | El ID del usuario. |\n| `fn` | `Function(data, session)` | yes |  | Se llama para cada sesión. |\n\nReturns: `Number` Número de sesiones.\n\nLlama a `fn(data, session)` para cada sesión en caché de `userid`, así puedes cambiar el objeto del usuario directamente.\n\nExample: Renombrar el usuario\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nDescarta los datos en caché de un usuario en la sesión integrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | El ID del usuario. |\n| `exceptsessionid` | `String` | no |  | Un ID de sesión que se conserva. |\n\nReturns: `Number` Número de sesiones eliminadas.\n\nElimina de la memoria las sesiones del usuario, de modo que la siguiente petición vuelve a llamar a `onread`. Las cookies siguen siendo válidas. Pasa `exceptsessionid` para conservar una sesión, por ejemplo la actual.\n\nExample: Recargar tras un cambio\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nEl objeto `$` que recibe el delegado AUTH().\n\nPropiedades (solo lectura): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (ruta en minúsculas), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` y `$.websocket` (`true` para una conexión WebSocket).\n\nMétodos: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` y `$.next(is, user)` (alias `$.callback()`). Solo cuenta la primera respuesta; las llamadas posteriores se ignoran.\n\nEn una conexión WebSocket `$.res` es el cliente WebSocket, así que no puedes escribir cookies.\n\nExample: Reglas distintas para WebSockets\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nAutentica la petición con un objeto de usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | El usuario autenticado. |\n\nEl objeto de usuario se convierte en `controller.user`, en `$.user` en los esquemas y en `client.user` en los WebSockets. Las rutas con `+` coinciden; las rutas con `-` no. `$.done([user])` devuelve un callback `function(is, user)` para código asíncrono: un `is` verdadero (o `null` con un usuario) autentica la petición, un `Error` la marca como anónima.\n\nExample: Iniciar sesión\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nMarca la petición como no autenticada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Datos opcionales para un visitante anónimo. |\n\nCoinciden las rutas con `-` y las rutas sin flag. Un objeto de usuario pasado aquí se asigna igualmente a `controller.user`, pero la petición cuenta como anónima.\n\nExample: Sin token\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nDetiene la autorización y el procesamiento de la petición.\n\nReturns: `AuthOptions` El mismo objeto.\n\nÚsalo cuando respondes tú mismo a la petición en el delegado, por ejemplo con una redirección a través de `$.res`. Después de `$.cancel()` el framework no enruta la petición.\n\nExample: Redirigir dominios antiguos\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLee o escribe una cookie dentro del delegado AUTH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cookie. |\n| `value` | `String|null` | no |  | Nuevo valor; `null` elimina la cookie. |\n| `expire` | `String|Date` | no |  | Caducidad, por ejemplo `'1 month'`. |\n| `options` | `Object` | no |  | Opciones de la cookie, consulta `controller.cookie()`. |\n\nReturns: `String|AuthOptions` El valor al leer; en otro caso, `$`.\n\nSolo con `name`, devuelve el valor de la cookie (una cadena vacía cuando falta). Con `value`, escribe la cookie. Con `value` igual a `null`, la elimina. El mismo método existe en los objetos `$` de esquemas y operaciones.\n\nExample: Eliminar una cookie inválida\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nLimita una ruta a visitantes autenticados o anónimos.\n\nUna URL que empieza con `+` (o `🔒`) coincide solo con peticiones autenticadas con `$.success()`. Una URL que empieza con `-` coincide solo con peticiones marcadas con `$.invalid()`. Una ruta sin flag coincide con ambas. En el array de flags, `'authorize'`, `'authorized'` y `'logged'` significan `+`; `'unauthorize'`, `'unauthorized'` y `'unlogged'` significan `-`.\n\nLa misma URL puede tener una ruta `+` y una ruta `-`. Cuando la única ruta es para el otro estado, la respuesta es `401`; sin ninguna ruta, `404`. Las rutas WebSocket usan los mismos prefijos; un WebSocket que no coincide se cierra con el código `4001`.\n\nLos flags solo se comprueban cuando `AUTH()` está registrado.\n\nExample: Una URL, dos rutas\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flags en un array\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nMarca una ruta con roles.\n\nUn flag que empieza con `@` es un rol. Se pasa a minúsculas y se guarda en `controller.route.flags`, y la ruta necesita un usuario autenticado (como con `+`) salvo que añadas `-`. Total.js no compara los roles con el usuario: compruébalos en la acción, por ejemplo con `UNAUTHORIZED()`.\n\nExample: Comprobar el rol de la ruta\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nComprueba los roles del usuario autenticado y responde 401 cuando ninguno coincide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Un controlador o un `$` de esquema/operación. |\n| `role` | `String` | yes |  | Uno o más roles como argumentos separados. |\n\nReturns: `Boolean` `true` cuando la petición fue rechazada.\n\nCompara los roles con `$.user.permissions` o `$.user.roles` (un array, o un objeto cuyas claves son roles). Devuelve `false` cuando el usuario tiene uno de los roles o cuando `user.sa` o `user.su` es verdadero. En caso contrario, llama a `$.invalid(401)` y devuelve `true`, también cuando no hay usuario.\n\nExample: En un esquema\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nCuenta los intentos de una dirección IP e indica cuándo bloquearla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objeto con `ip`. |\n| `limit` | `Number` | no | `5` | Intentos permitidos. |\n| `expiration` | `String` | no | `'15 minutes'` | Cuánto tiempo vive el contador. |\n\nReturns: `Boolean` `true` cuando la dirección IP está bloqueada.\n\nÚsalo para frenar los intentos de adivinar contraseñas. Cada llamada suma un intento para `$.ip`. Devuelve `true` cuando el número supera `limit`. Con `limit` igual a `-1` o `null`, borra el contador de esa dirección IP, por ejemplo tras un inicio de sesión correcto.\n\nExample: Formulario de inicio de sesión\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nEl objeto de usuario de una petición autenticada.\n\nReturns: `Object`\n\nLo asigna `$.success(user)`. Es `undefined` en las peticiones anónimas. Puedes asignarlo. En esquemas y operaciones lee `$.user`; en WebSockets, `client.user`.\n\nExample: Usar el usuario\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nEl usuario autenticado dentro de esquemas y operaciones.\n\nReturns: `Object`\n\nDevuelve `controller.user` de la petición, o `null` cuando la operación se ejecuta sin controlador.\n\nExample: Propietario de un registro\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nEl objeto de sesión y el ID de sesión de la petición.\n\nReturns: `Object / String`\n\nAmbos leen y escriben `req.session` y `req.sessionid`. El `AUTH(options)` integrado los asigna a la sesión en caché (`{ sessionid, userid, data, ua, expire }`) y a su ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` y `settoken()` asignan `sessionid`. Las mismas propiedades existen en los objetos `$` de esquema y en los clientes WebSocket.\n\nExample: Cerrar sesión en un almacén SESSION()\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLee o escribe una cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cookie. |\n| `value` | `String` | no |  | Nuevo valor. |\n| `expires` | `String|Date|Object` | no |  | Caducidad, o las opciones. |\n| `options` | `Object` | no |  | Opciones de la cookie. |\n\nReturns: `String|Controller` El valor al leer; en otro caso, el controlador.\n\nSolo con `name`, devuelve el valor decodificado de la cookie, o una cadena vacía. Con `value`, añade una cabecera `Set-Cookie` y devuelve el controlador. Para eliminar una cookie, escribe un valor vacío con una caducidad pasada como `'-1 day'`.\n\n`expires` es un `Date` o una cadena como `'1 month'`. En lugar de `expires` puedes pasar el objeto de opciones, que entonces puede contener `expires`.\n\n| Opción | Descripción |\n| --- | --- |\n| `domain` | Dominio de la cookie. |\n| `path` | Ruta de la cookie. Por defecto `/`. |\n| `secure` | `true` añade `Secure`. Por defecto `CONF.default_cookies_secure`. |\n| `httponly` | `true` añade `HttpOnly`. |\n| `samesite` o `security` | `'Lax'`, `'Strict'` o `'None'` (o `1` para Lax, `2` para Strict). Por defecto `CONF.default_cookies_samesite`. |\n\nUna cookie no se escribe una vez enviada la respuesta.\n\nExample: Escribir y leer\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Eliminar\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nEscribe una cookie en la respuesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cookie. |\n| `value` | `String` | yes |  | Valor. |\n| `expires` | `String|Date|Object` | no |  | Caducidad, o las opciones. |\n| `options` | `Object` | no |  | Opciones de la cookie. |\n\nReturns: `Response`\n\nEl método de bajo nivel detrás de `controller.cookie()`, con las mismas opciones. Úsalo donde solo tienes la respuesta, por ejemplo `$.res` en el delegado AUTH(). `req.cookie(name)` lee una cookie de la petición.\n\nExample: Desde el delegado\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nAtributo SameSite por defecto de las cookies.\n\nReturns: `String`\n\nSe usa cuando una cookie no tiene la opción `samesite`/`security`. Por defecto `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nAñade el atributo Secure a todas las cookies.\n\nReturns: `Boolean`\n\nSe usa cuando una cookie no tiene la opción `secure`. Por defecto `false`. Actívalo cuando la app funcione solo con HTTPS.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nDevuelve un almacén de sesiones con nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Nombre del almacén. |\n\nReturns: `Session` El almacén.\n\nLa primera llamada crea el almacén y carga sus sesiones guardadas; las llamadas posteriores devuelven la misma instancia. El nombre por defecto es `default`, guardado en `databases/sessions.txt`; otros nombres usan `databases/sessions_NAME.txt`. El archivo se escribe 10 segundos después de un cambio y contiene solo los metadatos de cada sesión: `sessionid`, `id`, `expire`, `used`, `created`, `note` y `settings`. Los datos del usuario se quedan en memoria; tras un reinicio el almacén los carga con `session.ondata`.\n\nUn elemento de sesión tiene las propiedades `sessionid`, `id` (ID del usuario), `data`, `expire`, `used`, `created`, `note`, `settings` y `released`. Propiedades del almacén: `name` e `items` (un `Map` de elementos por ID de sesión).\n\nLas sesiones caducadas se eliminan cada 10 minutos. En un clúster, los cambios se envían a los demás procesos.\n\nExample: Crear un almacén\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nCarga los datos de una sesión que no está en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | El elemento de sesión: `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback con los datos. |\n\nLo llaman `get()`, `getcookie()` y `gettoken()` cuando el elemento no tiene datos: tras un reinicio o después de liberar los datos. `meta` es el elemento de sesión. Llama a `next(err, data)`. Las llamadas para el mismo ID de usuario esperan a una única carga. Sin `ondata`, `release()` y `release2()` no hacen nada.\n\nExample: Cargar el usuario\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nSe llama cuando una sesión se elimina o caduca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | El elemento de sesión. |\n\nTambién lo llaman `clear()` y `remove2()`. El delegado hermano `session.onrelease = function(item)` se llama cuando los datos de una sesión se liberan de la memoria.\n\nExample: Registrar las sesiones eliminadas\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nCrea una sesión y escribe su cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Dónde se escribe la cookie. |\n| `opt` | `Object` | yes |  | Opciones, consulta la tabla. |\n| `callback` | `Function(err, data, meta)` | no |  | Se llama después de crear la sesión. |\n\nLlama a `session.set()` y escribe una cookie cifrada (creada con `ENCRYPTREQ()`) con el ID de sesión y el ID del usuario. `res` puede ser un controlador, un `$` de esquema, el `$` de autorización o una respuesta.\n\n| Opción | Descripción |\n| --- | --- |\n| `name` | Nombre de la cookie. |\n| `sessionid` | ID de sesión. Por defecto `UID()`. |\n| `id` | ID del usuario. |\n| `data` | Datos de la sesión. |\n| `expire` | Caducidad, por ejemplo `'1 month'`. |\n| `key` (o `secret`) | Clave de cifrado. |\n| `strict` | Ligar también la cookie a la dirección IP. Por defecto `false`. |\n| `note` | Una nota, por ejemplo el user agent. |\n| `settings` | Una cadena con ajustes. |\n| `options` | Opciones de la cookie. Por defecto `{ httponly: true, security: 'lax' }`. |\n\nExample: Iniciar sesión\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nLee la sesión desde la cookie de una petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | El `$` de autorización, un controlador o una petición. |\n| `opt` | `Object` | yes |  | Opciones, consulta la tabla. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` son los datos de la sesión, `meta` el elemento, `init` es `true` cuando `ondata` cargó los datos. |\n| `param` | `Any` | no |  | Un valor que se pasa al callback. |\n\nDescifra la cookie con `DECRYPTREQ()` y llama a `session.get()`. `req` puede ser el `$` de autorización, un controlador o una petición. Los tokens de menos de 20 caracteres se ignoran. Una cookie inválida se elimina, y con `ddos` cada intento fallido se cuenta para la dirección IP.\n\n| Opción | Descripción |\n| --- | --- |\n| `name` | Nombre de la cookie. |\n| `expire` | Prolonga la sesión y la cookie este tiempo. |\n| `key` (o `secret`) | Clave de cifrado. |\n| `extendcookie` | Prolongar la cookie con `expire`. Por defecto `true`. |\n| `removecookie` | Eliminar una cookie inválida. Por defecto `true`. |\n| `options` | Opciones de la cookie. |\n| `ddos` | Intentos fallidos por dirección IP antes de que la cookie deje de comprobarse. |\n\nExample: En AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nCrea una sesión y devuelve un token en lugar de una cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | Un controlador, un `$` de esquema o una respuesta. |\n| `opt` | `Object` | yes |  | Opciones de `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Recibe el token. |\n\nAcepta las opciones de `setcookie()` excepto `name` y `options`, y pasa el token cifrado al callback. Envía el token al cliente, por ejemplo en JSON.\n\nExample: Inicio de sesión en una API\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nLee la sesión desde un token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | El `$` de autorización o una petición. |\n| `opt` | `Object` | yes |  | Opciones. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Se llama con la sesión. |\n| `param` | `Any` | no |  | Un valor que se pasa al callback. |\n\nComo `getcookie()`, con el token en `opt.token`. Opciones: `token`, `expire`, `key` (o `secret`) y `ddos`.\n\nExample: Cabecera de token\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nCrea o reemplaza una sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de sesión. |\n| `id` | `String` | no |  | ID del usuario. |\n| `data` | `Object` | yes |  | Datos de la sesión. |\n| `expire` | `String` | yes |  | Caducidad. |\n| `note` | `String` | no |  | Una nota. |\n| `settings` | `String` | no |  | Ajustes. |\n| `callback` | `Function(err, data, meta)` | no |  | Se llama después del cambio. |\n\n`id` es el ID del usuario; puede omitirse cuando `data` es un objeto. `expire` es obligatorio, por ejemplo `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` reemplaza los datos de todas las sesiones cargadas del usuario `id` y pasa el número de sesiones actualizadas.\n\nExample: Crear una sesión\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nLee una sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de sesión. |\n| `expire` | `String` | no |  | Prolonga la sesión este tiempo. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Se llama con la sesión. |\n\nDevuelve los datos a través del callback y actualiza `used`. Con `expire`, la sesión se prolonga. Una sesión caducada se elimina. Cuando los datos no están en memoria, `ondata` los carga e `init` es `true`. `session.get2(id, callback(err, items))` devuelve todos los elementos activos del usuario `id`.\n\nExample: Leer\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nCambia una sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de sesión. |\n| `data` | `Object` | yes |  | Nuevos datos. |\n| `expire` | `String` | no |  | Nueva caducidad a partir de ahora. |\n| `note` | `String` | no |  | Nueva nota. |\n| `settings` | `String` | no |  | Nuevos ajustes. |\n| `callback` | `Function` | no |  | Se llama después del cambio. |\n\nReemplaza los datos solo cuando están cargados; `note`, `settings` y `expire` cambian siempre. El callback recibe `(null, data, meta)`, o ningún argumento cuando la sesión falta o no está cargada. `session.update2(id, data, [expire], [note], [settings], [callback])` hace lo mismo para todas las sesiones del usuario `id` y pasa el número de sesiones actualizadas.\n\nExample: Actualizar todas las sesiones de un usuario\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nElimina una sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | ID de sesión o elemento. |\n| `callback` | `Function(err, item)` | no |  | Se llama después de la eliminación. |\n\n`sessionid` también puede ser un elemento de sesión. El callback recibe `(null, item)`. `session.remove2(id, [callback])` elimina todas las sesiones del usuario `id` y pasa el número, por ejemplo para cerrar la sesión de un usuario en todas partes.\n\nExample: Cerrar sesión\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Cerrar sesión en todas partes\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nLibera de la memoria los datos de una sesión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | ID de sesión o elemento. |\n| `expire` | `String` | no |  | Lo usa `release2()`. |\n| `callback` | `Function(err, count)` | no |  | Se llama con el número. |\n\nLa sesión sigue siendo válida; la siguiente lectura vuelve a cargar los datos con `ondata`. Sin `sessionid` (o con `null`), libera todas las sesiones y pasa el número. `session.release2(id, [expire], [callback])` libera todas las sesiones del usuario `id` y, con `expire`, define su nueva caducidad. `session.releaseunused(lastusage, [callback])` libera las sesiones sin usar durante `lastusage`, por ejemplo `'30 minutes'`; el framework la llama cada 10 minutos con `CONF.allow_sessions_unused` (por defecto `'-20 minutes'`). Sin `ondata`, `release()` y `release2()` no hacen nada.\n\nExample: Recargar un usuario tras un cambio\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nDevuelve una sesión solo cuando sus datos están en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de sesión. |\n| `callback` | `Function(err, data, meta)` | yes |  | Se llama con el resultado. |\n\nA diferencia de `get()`, nunca llama a `ondata`. El callback recibe `(null, data, meta)` o ningún argumento. `session.contains2(id, callback)` encuentra la primera sesión así del usuario `id`. `session.has(sessionid, callback(err, bool))` y `session.has2(id, callback(err, bool))` solo indican si existe una sesión.\n\nExample: ¿Está el usuario en línea?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nLista las sesiones activas de un usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID del usuario. |\n| `callback` | `Function(err, items)` | yes |  | Se llama con los elementos. |\n\nPasa un array de elementos de sesión del usuario `id` y elimina los elementos caducados. `session.listlive(callback)` lista todas las sesiones con datos cargados, de cualquier usuario.\n\nExample: Dispositivos de un usuario\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nCuenta las sesiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | ID del usuario. |\n| `callback` | `Function(err, stats)` | yes |  | Se llama con los recuentos. |\n\nPasa `{ used, free, count }`: las sesiones `used` tienen datos cargados, las `free` no. Con `id`, cuenta solo las sesiones de ese usuario. `session.usage()` devuelve directamente el mismo objeto para todas las sesiones.\n\nExample: Estadísticas\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nElimina sesiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Tiempo sin uso. |\n| `callback` | `Function(err, count)` | no |  | Se llama después de la eliminación. |\n\nCon `lastusage` (por ejemplo `'7 days'`), elimina las sesiones sin usar durante ese tiempo y pasa su número. Sin él, elimina todas las sesiones. `session.clean()` elimina solo las sesiones caducadas; el framework la llama cada 10 minutos. `session.load([callback])` vuelve a leer las sesiones guardadas del archivo; `SESSION()` la llama al crearse.\n\nExample: Eliminar sesiones antiguas\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nLibera los datos de los elementos de SESSION() sin usar durante este tiempo.\n\nReturns: `String`\n\nCada 10 minutos el framework llama a `releaseunused()` con este valor en cada almacén de sesiones. Por defecto `'-20 minutes'`. Las sesiones siguen siendo válidas; sus datos se vuelven a cargar con `ondata`.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Autorisation","summary":"AUTH(), flags de route, rôles, cookies et le store SESSION().","markdown":"---\ntitle: Autorisation\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorisation\n\n> AUTH(), flags de route, rôles, cookies et le store SESSION().\n\nTotal.js authentifie les requêtes avec le délégué `AUTH()`, limite les routes avec les flags `+` et `-`, et conserve les sessions avec la session par cookie intégrée ou le store `SESSION()`. Le guide [Autorisation](../../guides/authorization/) explique comment les utiliser avec des exemples ; cette page en est la référence exacte.\n\nLe chiffrement a sa propre page : [Chiffrement](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nEnregistre le délégué qui authentifie chaque requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | Le délégué. `$` est l'objet d'autorisation. |\n\nReturns: `undefined`\n\nLe délégué s'exécute pour chaque requête HTTP qui atteint le routage et pour chaque connexion WebSocket. Il reçoit un objet d'autorisation `$` (voir `$.success()`, `$.invalid()` et les propriétés de `$`). Il doit appeler exactement une des méthodes `$.success(user)`, `$.invalid()` ou `$.cancel()`. L'enregistrement d'un nouveau délégué remplace le précédent.\n\nPasser un objet au lieu d'une fonction démarre la session par cookie intégrée, voir `AUTH(options)`.\n\nExample: Authentification avec un en-tête de token\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nDémarre le mécanisme de session par cookie intégré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Options et délégués de la session, voir le tableau. |\n\nReturns: `undefined` Les méthodes sont ajoutées à `options`.\n\nAvec un objet, `AUTH()` enregistre son propre délégué. Il lit le token de session dans le cookie `options.cookie` (ou dans l'en-tête `options.header`), le déchiffre avec `options.secret` et garde les données de l'utilisateur en mémoire pendant `options.expire`. Quand les données ne sont pas en cache, il appelle `options.onread()`. Les requêtes qui attendent la même session partagent un seul appel à `onread()`.\n\n`AUTH()` ne renvoie rien, mais ajoute des méthodes à l'objet que tu passes : `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` et `auth()` (le délégué lui-même). Garde une référence à l'objet.\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `secret` | String | Clé de chiffrement du token. Définis-la toujours. |\n| `cookie` | String | Nom du cookie qui contient le token. |\n| `header` | String | Nom d'un en-tête de requête qui contient le token, utilisé quand le cookie est absent. Écris-le en minuscules. |\n| `expire` | String | Durée pendant laquelle les données de l'utilisateur restent en mémoire. Par défaut `'5 minutes'`. |\n| `strict` | Boolean | La session en cache ne fonctionne qu'avec le même user agent. Par défaut `true`. |\n| `ddos` | Number | Nombre de tentatives échouées par adresse IP avant que toutes les requêtes de cette IP soient invalides. Les compteurs sont remis à zéro à chaque nettoyage. |\n| `cleaner` | Number | Intervalle de nettoyage en minutes. Par défaut `5`. |\n| `options` | Object | Options du cookie utilisées quand le cookie est écrit ou supprimé. |\n| `onread` | Function(meta, next, $) | Charge les données de l'utilisateur, voir `options.onread`. |\n| `onsession` | Function(session, $, init) | Appelée quand une session est trouvée. Renvoie `true` pour arrêter le traitement ; réponds alors toi-même à `$`. `init` vaut `true` quand les données viennent d'être chargées. |\n| `onauthorize` | Function($) | Appelée en premier pour chaque requête. Renvoie `true` pour ignorer le traitement intégré ; réponds alors toi-même à `$`. |\n| `onlogout` | Function(session) | Appelée par `logout()`. |\n| `onfree` | Function(meta) | Appelée après le nettoyage avec `{ sessions: Array, users: Array }` : les ID de session supprimés et les ID des utilisateurs sans aucune session active. |\n| `onddos` | Function($) | Appelée quand une adresse IP bloquée fait une requête. |\n| `locale` | Function(data, req) | Renvoie la langue de la requête. `data` vaut `null` pour les visiteurs anonymes. |\n\nUn token invalide ou inconnu supprime le cookie.\n\nExample: Session intégrée\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Langue de l'utilisateur\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nCharge les données de l'utilisateur pour un token de session dans la session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback avec les données de l'utilisateur. |\n| `$` | `Object` | yes |  | L'objet d'autorisation. |\n\nAppelée quand un token valide n'a pas de données en cache. `meta` contient `sessionid`, `userid`, `ip` et `ua`. Appelle `next(err, data)` : avec des données, la session est mise en cache pendant `options.expire` et la requête est authentifiée ; sans données, le cookie est supprimé et la requête est anonyme. Vérifie dans ta base de données que la session existe toujours, pour qu'une session déconnectée ne puisse pas être réutilisée.\n\nExample: Lire l'utilisateur\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nÉcrit le cookie de session de la session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objet doté d'une méthode `cookie()`. |\n| `sessionid` | `String` | yes |  | Ton ID de session. |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n| `expiration` | `String|Date` | yes |  | Expiration du cookie, par exemple `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Options du cookie. |\n\nSigne `sessionid` et `userid` avec `options.sign()` et les écrit dans le cookie `options.cookie`. Appelle-la après avoir vérifié les identifiants et enregistré la session. `options.sign(sessionid, userid)` renvoie le même token sans écrire de cookie, pour les clients qui l'envoient dans l'en-tête `options.header`. `$` est n'importe quel objet doté d'une méthode `cookie()` : un contrôleur, un `$` de schéma ou le `$` d'autorisation.\n\nExample: Connexion\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nDéconnecte la session courante de la session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | Le contrôleur ou l'ID de session. |\n\nReturns: `Boolean` `true` quand une session a été supprimée.\n\n`$` est le contrôleur (ou un autre objet avec `sessionid`), ou une chaîne d'ID de session. Supprime la session de la mémoire, appelle `options.onlogout(session)` et supprime le cookie quand `$` possède une méthode `cookie()`. Renvoie `true` quand la session a été trouvée. Supprime la session de ta base de données dans `onlogout`, sinon `onread` peut la recharger.\n\nExample: Déconnexion\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nModifie les données en cache de toutes les sessions d'un utilisateur dans la session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n| `fn` | `Function(data, session)` | yes |  | Appelée pour chaque session. |\n\nReturns: `Number` Nombre de sessions.\n\nAppelle `fn(data, session)` pour chaque session en cache de `userid`, ce qui te permet de modifier l'objet utilisateur sur place.\n\nExample: Renommer l'utilisateur\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nSupprime les données en cache d'un utilisateur dans la session intégrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID de l'utilisateur. |\n| `exceptsessionid` | `String` | no |  | Un ID de session à conserver. |\n\nReturns: `Number` Nombre de sessions supprimées.\n\nSupprime les sessions de l'utilisateur de la mémoire, si bien que la requête suivante appelle de nouveau `onread`. Les cookies restent valides. Passe `exceptsessionid` pour conserver une session, par exemple la session courante.\n\nExample: Recharger après une modification\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nL'objet `$` que reçoit le délégué AUTH().\n\nPropriétés (en lecture seule) : `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (chemin en minuscules), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` et `$.websocket` (`true` pour une connexion WebSocket).\n\nMéthodes : `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` et `$.next(is, user)` (alias `$.callback()`). Seule la première réponse compte ; les appels suivants sont ignorés.\n\nDans une connexion WebSocket, `$.res` est le client WebSocket, tu ne peux donc pas écrire de cookies.\n\nExample: Règles différentes pour les WebSockets\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nAuthentifie la requête avec un objet utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | L'utilisateur connecté. |\n\nL'objet utilisateur devient `controller.user`, `$.user` dans les schémas et `client.user` dans les WebSockets. Les routes avec `+` correspondent ; les routes avec `-` non. `$.done([user])` renvoie un callback `function(is, user)` pour le code asynchrone : un `is` vrai (ou `null` avec un utilisateur) authentifie la requête, une `Error` la marque comme anonyme.\n\nExample: Connexion\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nMarque la requête comme non authentifiée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Données facultatives pour un visiteur anonyme. |\n\nLes routes avec `-` et les routes sans flag correspondent. Un objet utilisateur passé ici est tout de même défini comme `controller.user`, mais la requête compte comme anonyme.\n\nExample: Pas de token\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nArrête l'autorisation et le traitement de la requête.\n\nReturns: `AuthOptions` Le même objet.\n\nUtilise-la quand tu réponds toi-même à la requête dans le délégué, par exemple avec une redirection via `$.res`. Après `$.cancel()`, le framework ne route pas la requête.\n\nExample: Rediriger les anciens domaines\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLit ou écrit un cookie dans le délégué AUTH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du cookie. |\n| `value` | `String|null` | no |  | Nouvelle valeur ; `null` supprime le cookie. |\n| `expire` | `String|Date` | no |  | Expiration, par exemple `'1 month'`. |\n| `options` | `Object` | no |  | Options du cookie, voir `controller.cookie()`. |\n\nReturns: `String|AuthOptions` La valeur en lecture, sinon `$`.\n\nAvec seulement `name`, renvoie la valeur du cookie (une chaîne vide s'il est absent). Avec `value`, écrit le cookie. Avec `value` à `null`, le supprime. La même méthode existe sur les objets `$` des schémas et des opérations.\n\nExample: Supprimer un cookie invalide\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nLimite une route aux visiteurs connectés ou anonymes.\n\nUne URL qui commence par `+` (ou `🔒`) ne correspond qu'aux requêtes authentifiées avec `$.success()`. Une URL qui commence par `-` ne correspond qu'aux requêtes marquées avec `$.invalid()`. Une route sans flag correspond aux deux. Dans le tableau de flags, `'authorize'`, `'authorized'` et `'logged'` signifient `+` ; `'unauthorize'`, `'unauthorized'` et `'unlogged'` signifient `-`.\n\nLa même URL peut avoir une route `+` et une route `-`. Quand la seule route est destinée à l'autre état, la réponse est `401` ; sans aucune route, `404`. Les routes WebSocket utilisent les mêmes préfixes ; un WebSocket qui ne correspond pas est fermé avec le code `4001`.\n\nLes flags ne sont vérifiés que si `AUTH()` est enregistré.\n\nExample: Une URL, deux routes\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flags dans un tableau\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nAssocie des rôles à une route.\n\nUn flag qui commence par `@` est un rôle. Il est converti en minuscules et conservé dans `controller.route.flags`, et la route exige un utilisateur connecté (comme avec `+`), sauf si tu ajoutes `-`. Total.js ne compare pas les rôles avec l'utilisateur : vérifie-les dans l'action, par exemple avec `UNAUTHORIZED()`.\n\nExample: Vérifier le rôle de la route\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nVérifie les rôles de l'utilisateur connecté et répond 401 quand aucun ne correspond.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Un contrôleur ou un `$` de schéma/d'opération. |\n| `role` | `String` | yes |  | Un ou plusieurs rôles, en arguments séparés. |\n\nReturns: `Boolean` `true` quand la requête a été refusée.\n\nCompare les rôles avec `$.user.permissions` ou `$.user.roles` (un tableau, ou un objet dont les clés sont des rôles). Renvoie `false` quand l'utilisateur possède l'un des rôles ou quand `user.sa` ou `user.su` a une valeur vraie. Sinon, appelle `$.invalid(401)` et renvoie `true`, y compris quand il n'y a pas d'utilisateur.\n\nExample: Dans un schéma\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nCompte les tentatives d'une adresse IP et indique quand la bloquer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objet avec `ip`. |\n| `limit` | `Number` | no | `5` | Tentatives autorisées. |\n| `expiration` | `String` | no | `'15 minutes'` | Durée de vie du compteur. |\n\nReturns: `Boolean` `true` quand l'adresse IP est bloquée.\n\nUtilise-la pour freiner les tentatives de deviner un mot de passe. Chaque appel ajoute une tentative pour `$.ip`. Renvoie `true` quand le nombre dépasse `limit`. Avec `limit` à `-1` ou `null`, remet à zéro le compteur de cette adresse IP, par exemple après une connexion réussie.\n\nExample: Formulaire de connexion\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nL'objet utilisateur d'une requête authentifiée.\n\nReturns: `Object`\n\nDéfini par `$.success(user)`. Il vaut `undefined` pour les requêtes anonymes. Tu peux l'affecter. Dans les schémas et les opérations, lis `$.user` ; dans les WebSockets, `client.user`.\n\nExample: Utiliser l'utilisateur\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utilisateur connecté dans les schémas et les opérations.\n\nReturns: `Object`\n\nRenvoie `controller.user` de la requête, ou `null` quand l'opération s'exécute sans contrôleur.\n\nExample: Propriétaire d'un enregistrement\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nL'objet session et l'ID de session de la requête.\n\nReturns: `Object / String`\n\nLes deux lisent et écrivent `req.session` et `req.sessionid`. La fonction intégrée `AUTH(options)` leur affecte la session en cache (`{ sessionid, userid, data, ua, expire }`) et son ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` et `settoken()` définissent `sessionid`. Les mêmes propriétés existent sur les objets `$` des schémas et sur les clients WebSocket.\n\nExample: Déconnexion d'un store SESSION()\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLit ou écrit un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du cookie. |\n| `value` | `String` | no |  | Nouvelle valeur. |\n| `expires` | `String|Date|Object` | no |  | Expiration, ou les options. |\n| `options` | `Object` | no |  | Options du cookie. |\n\nReturns: `String|Controller` La valeur en lecture, sinon le contrôleur.\n\nAvec seulement `name`, renvoie la valeur décodée du cookie, ou une chaîne vide. Avec `value`, ajoute un en-tête `Set-Cookie` et renvoie le contrôleur. Pour supprimer un cookie, écris une valeur vide avec une expiration passée comme `'-1 day'`.\n\n`expires` est une `Date` ou une chaîne comme `'1 month'`. À la place de `expires`, tu peux passer l'objet d'options, qui peut alors contenir `expires`.\n\n| Option | Description |\n| --- | --- |\n| `domain` | Domaine du cookie. |\n| `path` | Chemin du cookie. Par défaut `/`. |\n| `secure` | `true` ajoute `Secure`. Par défaut `CONF.default_cookies_secure`. |\n| `httponly` | `true` ajoute `HttpOnly`. |\n| `samesite` ou `security` | `'Lax'`, `'Strict'` ou `'None'` (ou `1` pour Lax, `2` pour Strict). Par défaut `CONF.default_cookies_samesite`. |\n\nUn cookie n'est plus écrit une fois la réponse envoyée.\n\nExample: Écrire et lire\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Supprimer\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nÉcrit un cookie dans la réponse HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du cookie. |\n| `value` | `String` | yes |  | Valeur. |\n| `expires` | `String|Date|Object` | no |  | Expiration, ou les options. |\n| `options` | `Object` | no |  | Options du cookie. |\n\nReturns: `Response`\n\nLa méthode de bas niveau derrière `controller.cookie()`, avec les mêmes options. Utilise-la là où tu n'as que la réponse, par exemple `$.res` dans le délégué AUTH(). `req.cookie(name)` lit un cookie de la requête.\n\nExample: Depuis le délégué\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nAttribut SameSite par défaut des cookies.\n\nReturns: `String`\n\nUtilisé quand un cookie n'a pas d'option `samesite`/`security`. Par défaut `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nAjoute l'attribut Secure à chaque cookie.\n\nReturns: `Boolean`\n\nUtilisé quand un cookie n'a pas d'option `secure`. Par défaut `false`. Active-le quand l'application fonctionne uniquement en HTTPS.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nRenvoie un store de sessions nommé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Nom du store. |\n\nReturns: `Session` Le store.\n\nLe premier appel crée le store et charge ses sessions enregistrées ; les appels suivants renvoient la même instance. Le nom par défaut est `default`, enregistré dans `databases/sessions.txt` ; les autres noms utilisent `databases/sessions_NAME.txt`. Le fichier est écrit 10 secondes après une modification et ne contient que les métadonnées de chaque session : `sessionid`, `id`, `expire`, `used`, `created`, `note` et `settings`. Les données de l'utilisateur restent en mémoire ; après un redémarrage, le store les charge avec `session.ondata`.\n\nUn élément de session possède les propriétés `sessionid`, `id` (ID de l'utilisateur), `data`, `expire`, `used`, `created`, `note`, `settings` et `released`. Propriétés du store : `name` et `items` (une `Map` des éléments par ID de session).\n\nLes sessions expirées sont supprimées toutes les 10 minutes. Dans un cluster, les modifications sont envoyées aux autres processus.\n\nExample: Créer un store\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nCharge les données d'une session qui n'est pas en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | L'élément de session : `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback avec les données. |\n\nAppelée par `get()`, `getcookie()` et `gettoken()` quand l'élément n'a pas de données : après un redémarrage ou après la libération des données. `meta` est l'élément de session. Appelle `next(err, data)`. Les appels pour un même ID d'utilisateur attendent un seul chargement. Sans `ondata`, `release()` et `release2()` ne font rien.\n\nExample: Charger l'utilisateur\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nAppelée quand une session est supprimée ou expire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | L'élément de session. |\n\nÉgalement appelée par `clear()` et `remove2()`. Le délégué voisin `session.onrelease = function(item)` est appelé quand les données d'une session sont libérées de la mémoire.\n\nExample: Journaliser les sessions supprimées\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nCrée une session et écrit son cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Où le cookie est écrit. |\n| `opt` | `Object` | yes |  | Options, voir le tableau. |\n| `callback` | `Function(err, data, meta)` | no |  | Appelée après la création de la session. |\n\nAppelle `session.set()` et écrit un cookie chiffré (créé avec `ENCRYPTREQ()`) contenant l'ID de session et l'ID de l'utilisateur. `res` peut être un contrôleur, un `$` de schéma, le `$` d'autorisation ou une réponse.\n\n| Option | Description |\n| --- | --- |\n| `name` | Nom du cookie. |\n| `sessionid` | ID de session. Par défaut `UID()`. |\n| `id` | ID de l'utilisateur. |\n| `data` | Données de la session. |\n| `expire` | Expiration, par exemple `'1 month'`. |\n| `key` (ou `secret`) | Clé de chiffrement. |\n| `strict` | Lier aussi le cookie à l'adresse IP. Par défaut `false`. |\n| `note` | Une note, par exemple le user agent. |\n| `settings` | Une chaîne avec des paramètres. |\n| `options` | Options du cookie. Par défaut `{ httponly: true, security: 'lax' }`. |\n\nExample: Connexion\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nLit la session depuis le cookie d'une requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Le `$` d'autorisation, un contrôleur ou une requête. |\n| `opt` | `Object` | yes |  | Options, voir le tableau. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` contient les données de la session, `meta` l'élément, `init` vaut `true` quand `ondata` a chargé les données. |\n| `param` | `Any` | no |  | Une valeur passée au callback. |\n\nDéchiffre le cookie avec `DECRYPTREQ()` et appelle `session.get()`. `req` peut être le `$` d'autorisation, un contrôleur ou une requête. Les tokens de moins de 20 caractères sont ignorés. Un cookie invalide est supprimé et, avec `ddos`, chaque tentative échouée est comptée pour l'adresse IP.\n\n| Option | Description |\n| --- | --- |\n| `name` | Nom du cookie. |\n| `expire` | Prolonge la session et le cookie de cette durée. |\n| `key` (ou `secret`) | Clé de chiffrement. |\n| `extendcookie` | Prolonger le cookie avec `expire`. Par défaut `true`. |\n| `removecookie` | Supprimer un cookie invalide. Par défaut `true`. |\n| `options` | Options du cookie. |\n| `ddos` | Nombre de tentatives échouées par adresse IP avant que le cookie ne soit plus vérifié. |\n\nExample: Dans AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nCrée une session et renvoie un token au lieu d'un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | Un contrôleur, un `$` de schéma ou une réponse. |\n| `opt` | `Object` | yes |  | Options de `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Reçoit le token. |\n\nAccepte les options de `setcookie()` sauf `name` et `options`, et passe le token chiffré au callback. Envoie le token au client, par exemple en JSON.\n\nExample: Connexion via l'API\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nLit la session depuis un token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Le `$` d'autorisation ou une requête. |\n| `opt` | `Object` | yes |  | Options. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Appelée avec la session. |\n| `param` | `Any` | no |  | Une valeur passée au callback. |\n\nComme `getcookie()`, avec le token dans `opt.token`. Options : `token`, `expire`, `key` (ou `secret`) et `ddos`.\n\nExample: En-tête de token\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nCrée ou remplace une session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de session. |\n| `id` | `String` | no |  | ID de l'utilisateur. |\n| `data` | `Object` | yes |  | Données de la session. |\n| `expire` | `String` | yes |  | Expiration. |\n| `note` | `String` | no |  | Une note. |\n| `settings` | `String` | no |  | Paramètres. |\n| `callback` | `Function(err, data, meta)` | no |  | Appelée après la modification. |\n\n`id` est l'ID de l'utilisateur ; il peut être omis quand `data` est un objet. `expire` est obligatoire, par exemple `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` remplace les données de toutes les sessions chargées de l'utilisateur `id` et passe le nombre de sessions mises à jour.\n\nExample: Créer une session\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nLit une session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de session. |\n| `expire` | `String` | no |  | Prolonge la session de cette durée. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Appelée avec la session. |\n\nRenvoie les données via le callback et met à jour `used`. Avec `expire`, la session est prolongée. Une session expirée est supprimée. Quand les données ne sont pas en mémoire, `ondata` les charge et `init` vaut `true`. `session.get2(id, callback(err, items))` renvoie tous les éléments actifs de l'utilisateur `id`.\n\nExample: Lire\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nModifie une session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de session. |\n| `data` | `Object` | yes |  | Nouvelles données. |\n| `expire` | `String` | no |  | Nouvelle expiration à partir de maintenant. |\n| `note` | `String` | no |  | Nouvelle note. |\n| `settings` | `String` | no |  | Nouveaux paramètres. |\n| `callback` | `Function` | no |  | Appelée après la modification. |\n\nRemplace les données uniquement lorsqu'elles sont chargées ; `note`, `settings` et `expire` changent toujours. Le callback reçoit `(null, data, meta)`, ou aucun argument quand la session est absente ou non chargée. `session.update2(id, data, [expire], [note], [settings], [callback])` fait de même pour toutes les sessions de l'utilisateur `id` et passe le nombre de sessions mises à jour.\n\nExample: Mettre à jour toutes les sessions d'un utilisateur\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nSupprime une session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | ID de session ou élément. |\n| `callback` | `Function(err, item)` | no |  | Appelée après la suppression. |\n\n`sessionid` peut aussi être un élément de session. Le callback reçoit `(null, item)`. `session.remove2(id, [callback])` supprime toutes les sessions de l'utilisateur `id` et passe leur nombre, par exemple pour déconnecter un utilisateur partout.\n\nExample: Déconnexion\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Déconnexion partout\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nLibère de la mémoire les données d'une session.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | ID de session ou élément. |\n| `expire` | `String` | no |  | Utilisé par `release2()`. |\n| `callback` | `Function(err, count)` | no |  | Appelée avec le nombre. |\n\nLa session reste valide ; la lecture suivante recharge les données avec `ondata`. Sans `sessionid` (ou avec `null`), libère toutes les sessions et passe leur nombre. `session.release2(id, [expire], [callback])` libère toutes les sessions de l'utilisateur `id` et, avec `expire`, définit leur nouvelle expiration. `session.releaseunused(lastusage, [callback])` libère les sessions inutilisées depuis `lastusage`, par exemple `'30 minutes'` ; le framework l'appelle toutes les 10 minutes avec `CONF.allow_sessions_unused` (par défaut `'-20 minutes'`). Sans `ondata`, `release()` et `release2()` ne font rien.\n\nExample: Recharger un utilisateur après une modification\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nRenvoie une session uniquement si ses données sont en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID de session. |\n| `callback` | `Function(err, data, meta)` | yes |  | Appelée avec le résultat. |\n\nContrairement à `get()`, elle n'appelle jamais `ondata`. Le callback reçoit `(null, data, meta)` ou aucun argument. `session.contains2(id, callback)` trouve la première session de ce type pour l'utilisateur `id`. `session.has(sessionid, callback(err, bool))` et `session.has2(id, callback(err, bool))` indiquent seulement si une session existe.\n\nExample: L'utilisateur est-il en ligne ?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nListe les sessions actives d'un utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID de l'utilisateur. |\n| `callback` | `Function(err, items)` | yes |  | Appelée avec les éléments. |\n\nPasse un tableau des éléments de session de l'utilisateur `id` et supprime les éléments expirés. `session.listlive(callback)` liste toutes les sessions dont les données sont chargées, pour tous les utilisateurs.\n\nExample: Appareils d'un utilisateur\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nCompte les sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | ID de l'utilisateur. |\n| `callback` | `Function(err, stats)` | yes |  | Appelée avec les comptes. |\n\nPasse `{ used, free, count }` : les sessions `used` ont des données chargées, les sessions `free` non. Avec `id`, ne compte que les sessions de cet utilisateur. `session.usage()` renvoie directement le même objet pour toutes les sessions.\n\nExample: Statistiques\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nSupprime des sessions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Durée d'inutilisation. |\n| `callback` | `Function(err, count)` | no |  | Appelée après la suppression. |\n\nAvec `lastusage` (par exemple `'7 days'`), supprime les sessions inutilisées depuis cette durée et passe leur nombre. Sans lui, supprime toutes les sessions. `session.clean()` ne supprime que les sessions expirées ; le framework l'appelle toutes les 10 minutes. `session.load([callback])` relit les sessions enregistrées depuis le fichier ; `SESSION()` l'appelle à la création.\n\nExample: Supprimer les anciennes sessions\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nLibère les données des éléments SESSION() inutilisés depuis cette durée.\n\nReturns: `String`\n\nToutes les 10 minutes, le framework appelle `releaseunused()` avec cette valeur sur chaque store de sessions. Par défaut `'-20 minutes'`. Les sessions restent valides ; leurs données sont rechargées avec `ondata`.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Autorizzazione","summary":"AUTH(), flag delle route, ruoli, cookie e lo store SESSION().","markdown":"---\ntitle: Autorizzazione\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorizzazione\n\n> AUTH(), flag delle route, ruoli, cookie e lo store SESSION().\n\nTotal.js autentica le richieste con il delegato `AUTH()`, limita le route con i flag `+` e `-` e conserva le sessioni con la sessione a cookie integrata o con lo store `SESSION()`. La guida [Autorizzazione](../../guides/authorization/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\nLa cifratura ha una pagina propria: [Cifratura](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nRegistra il delegato che autentica ogni richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | Il delegato. `$` è l'oggetto di autorizzazione. |\n\nReturns: `undefined`\n\nIl delegato viene eseguito per ogni richiesta HTTP che raggiunge il routing e per ogni connessione WebSocket. Riceve un oggetto di autorizzazione `$` (vedi `$.success()`, `$.invalid()` e le proprietà di `$`). Deve chiamare esattamente uno tra `$.success(user)`, `$.invalid()` o `$.cancel()`. Registrare un nuovo delegato sostituisce quello precedente.\n\nPassare un oggetto invece di una funzione avvia la sessione a cookie integrata, vedi `AUTH(options)`.\n\nExample: Accesso con un header contenente il token\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nAvvia il meccanismo integrato di sessione a cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Opzioni e delegati della sessione, vedi la tabella. |\n\nReturns: `undefined` I metodi vengono aggiunti a `options`.\n\nCon un oggetto, `AUTH()` registra un proprio delegato. Legge il token di sessione dal cookie `options.cookie` (o dall'header `options.header`), lo decifra con `options.secret` e tiene i dati dell'utente in memoria per `options.expire`. Quando i dati non sono in cache, chiama `options.onread()`. Le richieste in attesa della stessa sessione condividono una sola chiamata a `onread()`.\n\n`AUTH()` non restituisce nulla, ma aggiunge metodi all'oggetto che passi: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` e `auth()` (il delegato stesso). Tieni un riferimento all'oggetto.\n\n| Opzione | Tipo | Descrizione |\n| --- | --- | --- |\n| `secret` | String | Chiave per cifrare il token. Impostala sempre. |\n| `cookie` | String | Nome del cookie con il token. |\n| `header` | String | Nome di un header della richiesta con il token, usato quando il cookie manca. Scrivilo in minuscolo. |\n| `expire` | String | Per quanto tempo i dati dell'utente restano in memoria. Predefinito `'5 minutes'`. |\n| `strict` | Boolean | La sessione in cache funziona solo con lo stesso user agent. Predefinito `true`. |\n| `ddos` | Number | Tentativi falliti per indirizzo IP prima che ogni richiesta di quell'IP sia non valida. I contatori si azzerano a ogni pulizia. |\n| `cleaner` | Number | Intervallo di pulizia in minuti. Predefinito `5`. |\n| `options` | Object | Opzioni del cookie usate quando il cookie viene scritto o rimosso. |\n| `onread` | Function(meta, next, $) | Carica i dati dell'utente, vedi `options.onread`. |\n| `onsession` | Function(session, $, init) | Chiamato quando viene trovata una sessione. Restituisci `true` per interrompere l'elaborazione; poi rispondi tu stesso a `$`. `init` è `true` quando i dati sono appena stati caricati. |\n| `onauthorize` | Function($) | Chiamato per primo per ogni richiesta. Restituisci `true` per saltare l'elaborazione integrata; poi rispondi tu stesso a `$`. |\n| `onlogout` | Function(session) | Chiamato da `logout()`. |\n| `onfree` | Function(meta) | Chiamato dopo la pulizia con `{ sessions: Array, users: Array }`: gli ID delle sessioni rimosse e gli ID degli utenti senza alcuna sessione attiva. |\n| `onddos` | Function($) | Chiamato quando un indirizzo IP bloccato fa una richiesta. |\n| `locale` | Function(data, req) | Restituisce la lingua della richiesta. `data` è `null` per i visitatori anonimi. |\n\nUn token non valido o sconosciuto rimuove il cookie.\n\nExample: Sessione integrata\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Lingua dell'utente\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nCarica i dati dell'utente per un token di sessione nella sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback con i dati dell'utente. |\n| `$` | `Object` | yes |  | L'oggetto di autorizzazione. |\n\nChiamato quando un token valido non ha dati in cache. `meta` contiene `sessionid`, `userid`, `ip` e `ua`. Chiama `next(err, data)`: con i dati, la sessione viene messa in cache per `options.expire` e la richiesta risulta autenticata; senza dati, il cookie viene rimosso e la richiesta è anonima. Controlla nel tuo database che la sessione esista ancora, così una sessione chiusa non può essere riutilizzata.\n\nExample: Leggere l'utente\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nScrive il cookie di sessione della sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Oggetto con un metodo `cookie()`. |\n| `sessionid` | `String` | yes |  | Il tuo ID di sessione. |\n| `userid` | `String` | yes |  | L'ID dell'utente. |\n| `expiration` | `String|Date` | yes |  | Scadenza del cookie, per esempio `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Opzioni del cookie. |\n\nFirma `sessionid` e `userid` con `options.sign()` e li scrive nel cookie `options.cookie`. Chiamalo dopo aver controllato le credenziali e salvato la sessione. `options.sign(sessionid, userid)` restituisce lo stesso token senza scrivere un cookie, per i client che lo inviano nell'header `options.header`. `$` è qualsiasi cosa con un metodo `cookie()`: un controller, un `$` di schema o il `$` di autorizzazione.\n\nExample: Accesso\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nChiude la sessione corrente della sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | Il controller o l'ID di sessione. |\n\nReturns: `Boolean` `true` quando una sessione è stata rimossa.\n\n`$` è il controller (o un altro oggetto con `sessionid`), oppure una stringa con l'ID di sessione. Rimuove la sessione dalla memoria, chiama `options.onlogout(session)` e rimuove il cookie quando `$` ha un metodo `cookie()`. Restituisce `true` quando la sessione è stata trovata. Elimina la sessione dal tuo database in `onlogout`, altrimenti `onread` può caricarla di nuovo.\n\nExample: Uscita\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nModifica i dati in cache di tutte le sessioni di un utente nella sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID dell'utente. |\n| `fn` | `Function(data, session)` | yes |  | Chiamata per ogni sessione. |\n\nReturns: `Number` Numero di sessioni.\n\nChiama `fn(data, session)` per ogni sessione in cache di `userid`, così puoi modificare direttamente l'oggetto utente.\n\nExample: Rinominare l'utente\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nScarta i dati in cache di un utente nella sessione integrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | L'ID dell'utente. |\n| `exceptsessionid` | `String` | no |  | Un ID di sessione da mantenere. |\n\nReturns: `Number` Numero di sessioni rimosse.\n\nRimuove le sessioni dell'utente dalla memoria, così la richiesta successiva chiama di nuovo `onread`. I cookie restano validi. Passa `exceptsessionid` per mantenere una sessione, per esempio quella corrente.\n\nExample: Ricaricare dopo una modifica\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nL'oggetto `$` che riceve il delegato AUTH().\n\nProprietà (sola lettura): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (percorso in minuscolo), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` e `$.websocket` (`true` per una connessione WebSocket).\n\nMetodi: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` e `$.next(is, user)` (alias `$.callback()`). Conta solo la prima risposta; le chiamate successive vengono ignorate.\n\nIn una connessione WebSocket `$.res` è il client WebSocket, quindi non puoi scrivere cookie.\n\nExample: Regole diverse per i WebSocket\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nAutentica la richiesta con un oggetto utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | L'utente autenticato. |\n\nL'oggetto utente diventa `controller.user`, `$.user` negli schemi e `client.user` nei WebSocket. Le route con `+` corrispondono; quelle con `-` no. `$.done([user])` restituisce una callback `function(is, user)` per il codice asincrono: un `is` truthy (o `null` con un utente) autentica la richiesta, un `Error` la marca come anonima.\n\nExample: Accesso\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nMarca la richiesta come non autenticata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Dati facoltativi per un visitatore anonimo. |\n\nCorrispondono le route con `-` e quelle senza flag. Un oggetto utente passato qui viene comunque impostato come `controller.user`, ma la richiesta conta come anonima.\n\nExample: Nessun token\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nInterrompe l'autorizzazione e l'elaborazione della richiesta.\n\nReturns: `AuthOptions` Lo stesso oggetto.\n\nUsalo quando rispondi tu stesso alla richiesta nel delegato, per esempio con un redirect tramite `$.res`. Dopo `$.cancel()` il framework non instrada la richiesta.\n\nExample: Reindirizzare i vecchi domini\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLegge o scrive un cookie all'interno del delegato AUTH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del cookie. |\n| `value` | `String|null` | no |  | Nuovo valore; `null` rimuove il cookie. |\n| `expire` | `String|Date` | no |  | Scadenza, per esempio `'1 month'`. |\n| `options` | `Object` | no |  | Opzioni del cookie, vedi `controller.cookie()`. |\n\nReturns: `String|AuthOptions` Il valore in lettura, altrimenti `$`.\n\nCon il solo `name`, restituisce il valore del cookie (una stringa vuota quando manca). Con `value`, scrive il cookie. Con `value` impostato a `null`, lo rimuove. Lo stesso metodo esiste negli oggetti `$` di schemi e operazioni.\n\nExample: Rimuovere un cookie non valido\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nLimita una route ai visitatori autenticati o anonimi.\n\nUn URL che inizia con `+` (o `🔒`) corrisponde solo alle richieste autenticate con `$.success()`. Un URL che inizia con `-` corrisponde solo alle richieste marcate con `$.invalid()`. Una route senza flag corrisponde a entrambe. Nell'array dei flag, `'authorize'`, `'authorized'` e `'logged'` significano `+`; `'unauthorize'`, `'unauthorized'` e `'unlogged'` significano `-`.\n\nLo stesso URL può avere una route `+` e una `-`. Quando l'unica route è per l'altro stato, la risposta è `401`; senza nessuna route, `404`. Le route WebSocket usano gli stessi prefissi; un WebSocket che non corrisponde viene chiuso con il codice `4001`.\n\nI flag vengono controllati solo quando `AUTH()` è registrato.\n\nExample: Un URL, due route\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flag in un array\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nMarca una route con dei ruoli.\n\nUn flag che inizia con `@` è un ruolo. Viene convertito in minuscolo e conservato in `controller.route.flags`, e la route richiede un utente autenticato (come con `+`) a meno che tu non aggiunga `-`. Total.js non confronta i ruoli con l'utente: controllali nell'azione, per esempio con `UNAUTHORIZED()`.\n\nExample: Controllare il ruolo della route\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nControlla i ruoli dell'utente autenticato e risponde 401 quando nessuno corrisponde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Un controller o un `$` di schema/operazione. |\n| `role` | `String` | yes |  | Uno o più ruoli come argomenti separati. |\n\nReturns: `Boolean` `true` quando la richiesta è stata rifiutata.\n\nConfronta i ruoli con `$.user.permissions` o `$.user.roles` (un array, o un oggetto le cui chiavi sono i ruoli). Restituisce `false` quando l'utente ha uno dei ruoli o quando `user.sa` o `user.su` è truthy. Altrimenti chiama `$.invalid(401)` e restituisce `true`, anche quando non c'è nessun utente.\n\nExample: In uno schema\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nConta i tentativi da un indirizzo IP e indica quando bloccarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Oggetto con `ip`. |\n| `limit` | `Number` | no | `5` | Tentativi consentiti. |\n| `expiration` | `String` | no | `'15 minutes'` | Durata del contatore. |\n\nReturns: `Boolean` `true` quando l'indirizzo IP è bloccato.\n\nUsalo per rallentare i tentativi di indovinare le password. Ogni chiamata aggiunge un tentativo per `$.ip`. Restituisce `true` quando il conteggio supera `limit`. Con `limit` impostato a `-1` o `null`, azzera il contatore di quell'indirizzo IP, per esempio dopo un accesso riuscito.\n\nExample: Form di accesso\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nL'oggetto utente di una richiesta autenticata.\n\nReturns: `Object`\n\nImpostato da `$.success(user)`. È `undefined` per le richieste anonime. Puoi assegnarlo. In schemi e operazioni leggi `$.user`; nei WebSocket `client.user`.\n\nExample: Usare l'utente\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nL'utente autenticato all'interno di schemi e operazioni.\n\nReturns: `Object`\n\nRestituisce `controller.user` della richiesta, oppure `null` quando l'operazione viene eseguita senza un controller.\n\nExample: Proprietario di un record\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nL'oggetto sessione e l'ID di sessione della richiesta.\n\nReturns: `Object / String`\n\nEntrambi leggono e scrivono `req.session` e `req.sessionid`. L'integrato `AUTH(options)` li imposta alla sessione in cache (`{ sessionid, userid, data, ua, expire }`) e al suo ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` e `settoken()` impostano `sessionid`. Le stesse proprietà esistono negli oggetti `$` degli schemi e nei client WebSocket.\n\nExample: Uscire da uno store SESSION()\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nLegge o scrive un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del cookie. |\n| `value` | `String` | no |  | Nuovo valore. |\n| `expires` | `String|Date|Object` | no |  | Scadenza, oppure le opzioni. |\n| `options` | `Object` | no |  | Opzioni del cookie. |\n\nReturns: `String|Controller` Il valore in lettura, altrimenti il controller.\n\nCon il solo `name`, restituisce il valore decodificato del cookie, oppure una stringa vuota. Con `value`, aggiunge un header `Set-Cookie` e restituisce il controller. Per rimuovere un cookie, scrivi un valore vuoto con una scadenza passata come `'-1 day'`.\n\n`expires` è una `Date` o una stringa come `'1 month'`. Al posto di `expires` puoi passare l'oggetto delle opzioni, che allora può contenere `expires`.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `domain` | Dominio del cookie. |\n| `path` | Percorso del cookie. Predefinito `/`. |\n| `secure` | `true` aggiunge `Secure`. Predefinito `CONF.default_cookies_secure`. |\n| `httponly` | `true` aggiunge `HttpOnly`. |\n| `samesite` o `security` | `'Lax'`, `'Strict'` o `'None'` (oppure `1` per Lax, `2` per Strict). Predefinito `CONF.default_cookies_samesite`. |\n\nUn cookie non viene scritto una volta che la risposta è stata inviata.\n\nExample: Scrivere e leggere\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Rimuovere\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nScrive un cookie nella risposta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del cookie. |\n| `value` | `String` | yes |  | Valore. |\n| `expires` | `String|Date|Object` | no |  | Scadenza, oppure le opzioni. |\n| `options` | `Object` | no |  | Opzioni del cookie. |\n\nReturns: `Response`\n\nIl metodo di basso livello dietro `controller.cookie()`, con le stesse opzioni. Usalo dove hai solo la risposta, per esempio `$.res` nel delegato AUTH(). `req.cookie(name)` legge un cookie dalla richiesta.\n\nExample: Dal delegato\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nAttributo SameSite predefinito dei cookie.\n\nReturns: `String`\n\nUsato quando un cookie non ha l'opzione `samesite`/`security`. Predefinito `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nAggiunge l'attributo Secure a ogni cookie.\n\nReturns: `Boolean`\n\nUsato quando un cookie non ha l'opzione `secure`. Predefinito `false`. Attivalo quando l'app gira solo su HTTPS.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nRestituisce uno store di sessioni con nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Nome dello store. |\n\nReturns: `Session` Lo store.\n\nLa prima chiamata crea lo store e carica le sue sessioni salvate; le chiamate successive restituiscono la stessa istanza. Il nome predefinito è `default`, salvato in `databases/sessions.txt`; gli altri nomi usano `databases/sessions_NAME.txt`. Il file viene scritto 10 secondi dopo una modifica e contiene solo i metadati di ogni sessione: `sessionid`, `id`, `expire`, `used`, `created`, `note` e `settings`. I dati dell'utente restano in memoria; dopo un riavvio lo store li carica con `session.ondata`.\n\nUn elemento di sessione ha le proprietà `sessionid`, `id` (ID utente), `data`, `expire`, `used`, `created`, `note`, `settings` e `released`. Proprietà dello store: `name` e `items` (una `Map` degli elementi per ID di sessione).\n\nLe sessioni scadute vengono rimosse ogni 10 minuti. In un cluster, le modifiche vengono inviate agli altri processi.\n\nExample: Creare uno store\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nCarica i dati di una sessione che non è in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | L'elemento di sessione: `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback con i dati. |\n\nChiamato da `get()`, `getcookie()` e `gettoken()` quando l'elemento non ha dati: dopo un riavvio o dopo che i dati sono stati rilasciati. `meta` è l'elemento di sessione. Chiama `next(err, data)`. Le chiamate per lo stesso ID utente attendono un unico caricamento. Senza `ondata`, `release()` e `release2()` non fanno nulla.\n\nExample: Caricare l'utente\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nChiamato quando una sessione viene rimossa o scade.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | L'elemento di sessione. |\n\nChiamato anche da `clear()` e `remove2()`. Il delegato gemello `session.onrelease = function(item)` viene chiamato quando i dati di una sessione vengono rilasciati dalla memoria.\n\nExample: Registrare nel log le sessioni rimosse\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nCrea una sessione e scrive il suo cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Dove viene scritto il cookie. |\n| `opt` | `Object` | yes |  | Opzioni, vedi la tabella. |\n| `callback` | `Function(err, data, meta)` | no |  | Chiamata dopo la creazione della sessione. |\n\nChiama `session.set()` e scrive un cookie cifrato (creato con `ENCRYPTREQ()`) con l'ID di sessione e l'ID utente. `res` può essere un controller, un `$` di schema, il `$` di autorizzazione o una risposta.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `name` | Nome del cookie. |\n| `sessionid` | ID di sessione. Predefinito `UID()`. |\n| `id` | ID utente. |\n| `data` | Dati della sessione. |\n| `expire` | Scadenza, per esempio `'1 month'`. |\n| `key` (o `secret`) | Chiave di cifratura. |\n| `strict` | Lega il cookie anche all'indirizzo IP. Predefinito `false`. |\n| `note` | Una nota, per esempio lo user agent. |\n| `settings` | Una stringa con le impostazioni. |\n| `options` | Opzioni del cookie. Predefinito `{ httponly: true, security: 'lax' }`. |\n\nExample: Accesso\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nLegge la sessione dal cookie di una richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Il `$` di autorizzazione, un controller o una richiesta. |\n| `opt` | `Object` | yes |  | Opzioni, vedi la tabella. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` sono i dati della sessione, `meta` l'elemento, `init` è `true` quando `ondata` ha caricato i dati. |\n| `param` | `Any` | no |  | Un valore passato alla callback. |\n\nDecifra il cookie con `DECRYPTREQ()` e chiama `session.get()`. `req` può essere il `$` di autorizzazione, un controller o una richiesta. I token più corti di 20 caratteri vengono ignorati. Un cookie non valido viene rimosso e, con `ddos`, ogni tentativo fallito viene contato per l'indirizzo IP.\n\n| Opzione | Descrizione |\n| --- | --- |\n| `name` | Nome del cookie. |\n| `expire` | Estende la sessione e il cookie di questo tempo. |\n| `key` (o `secret`) | Chiave di cifratura. |\n| `extendcookie` | Estende il cookie con `expire`. Predefinito `true`. |\n| `removecookie` | Rimuove un cookie non valido. Predefinito `true`. |\n| `options` | Opzioni del cookie. |\n| `ddos` | Tentativi falliti per indirizzo IP prima che il cookie non venga più controllato. |\n\nExample: In AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nCrea una sessione e restituisce un token invece di un cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | Un controller, un `$` di schema o una risposta. |\n| `opt` | `Object` | yes |  | Opzioni di `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Riceve il token. |\n\nAccetta le opzioni di `setcookie()` tranne `name` e `options`, e passa il token cifrato alla callback. Invia il token al client, per esempio in JSON.\n\nExample: Accesso tramite API\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nLegge la sessione da un token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Il `$` di autorizzazione o una richiesta. |\n| `opt` | `Object` | yes |  | Opzioni. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Chiamata con la sessione. |\n| `param` | `Any` | no |  | Un valore passato alla callback. |\n\nCome `getcookie()`, con il token in `opt.token`. Opzioni: `token`, `expire`, `key` (o `secret`) e `ddos`.\n\nExample: Header con il token\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nCrea o sostituisce una sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID di sessione. |\n| `id` | `String` | no |  | ID utente. |\n| `data` | `Object` | yes |  | Dati della sessione. |\n| `expire` | `String` | yes |  | Scadenza. |\n| `note` | `String` | no |  | Una nota. |\n| `settings` | `String` | no |  | Impostazioni. |\n| `callback` | `Function(err, data, meta)` | no |  | Chiamata dopo la modifica. |\n\n`id` è l'ID utente; può essere omesso quando `data` è un oggetto. `expire` è obbligatorio, per esempio `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` sostituisce i dati di tutte le sessioni caricate dell'utente `id` e passa il numero di sessioni aggiornate.\n\nExample: Creare una sessione\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nLegge una sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID di sessione. |\n| `expire` | `String` | no |  | Estende la sessione di questo tempo. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Chiamata con la sessione. |\n\nRestituisce i dati tramite la callback e aggiorna `used`. Con `expire`, la sessione viene estesa. Una sessione scaduta viene rimossa. Quando i dati non sono in memoria, `ondata` li carica e `init` è `true`. `session.get2(id, callback(err, items))` restituisce tutti gli elementi attivi dell'utente `id`.\n\nExample: Leggere\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nModifica una sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID di sessione. |\n| `data` | `Object` | yes |  | Nuovi dati. |\n| `expire` | `String` | no |  | Nuova scadenza a partire da ora. |\n| `note` | `String` | no |  | Nuova nota. |\n| `settings` | `String` | no |  | Nuove impostazioni. |\n| `callback` | `Function` | no |  | Chiamata dopo la modifica. |\n\nSostituisce i dati solo quando sono caricati; `note`, `settings` e `expire` cambiano sempre. La callback riceve `(null, data, meta)`, oppure nessun argomento quando la sessione manca o non è caricata. `session.update2(id, data, [expire], [note], [settings], [callback])` fa lo stesso per tutte le sessioni dell'utente `id` e passa il numero di sessioni aggiornate.\n\nExample: Aggiornare tutte le sessioni di un utente\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nRimuove una sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | ID di sessione o elemento. |\n| `callback` | `Function(err, item)` | no |  | Chiamata dopo la rimozione. |\n\n`sessionid` può anche essere un elemento di sessione. La callback riceve `(null, item)`. `session.remove2(id, [callback])` rimuove tutte le sessioni dell'utente `id` e passa il numero, per esempio per far uscire un utente ovunque.\n\nExample: Uscita\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Uscita ovunque\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nLibera dalla memoria i dati di una sessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | ID di sessione o elemento. |\n| `expire` | `String` | no |  | Usato da `release2()`. |\n| `callback` | `Function(err, count)` | no |  | Chiamata con il numero. |\n\nLa sessione resta valida; la lettura successiva carica di nuovo i dati con `ondata`. Senza `sessionid` (o con `null`), rilascia ogni sessione e passa il numero. `session.release2(id, [expire], [callback])` rilascia tutte le sessioni dell'utente `id` e, con `expire`, imposta la loro nuova scadenza. `session.releaseunused(lastusage, [callback])` rilascia le sessioni non usate da `lastusage`, per esempio `'30 minutes'`; il framework lo chiama ogni 10 minuti con `CONF.allow_sessions_unused` (predefinito `'-20 minutes'`). Senza `ondata`, `release()` e `release2()` non fanno nulla.\n\nExample: Ricaricare un utente dopo una modifica\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nRestituisce una sessione solo quando i suoi dati sono in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID di sessione. |\n| `callback` | `Function(err, data, meta)` | yes |  | Chiamata con il risultato. |\n\nA differenza di `get()`, non chiama mai `ondata`. La callback riceve `(null, data, meta)` oppure nessun argomento. `session.contains2(id, callback)` trova la prima sessione di questo tipo dell'utente `id`. `session.has(sessionid, callback(err, bool))` e `session.has2(id, callback(err, bool))` indicano solo se una sessione esiste.\n\nExample: L'utente è online?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nElenca le sessioni attive di un utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID utente. |\n| `callback` | `Function(err, items)` | yes |  | Chiamata con gli elementi. |\n\nPassa un array di elementi di sessione dell'utente `id` e rimuove gli elementi scaduti. `session.listlive(callback)` elenca tutte le sessioni con dati caricati, per qualsiasi utente.\n\nExample: Dispositivi di un utente\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nConta le sessioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | ID utente. |\n| `callback` | `Function(err, stats)` | yes |  | Chiamata con i conteggi. |\n\nPassa `{ used, free, count }`: le sessioni `used` hanno dati caricati, quelle `free` no. Con `id`, conta solo le sessioni di quell'utente. `session.usage()` restituisce direttamente lo stesso oggetto per tutte le sessioni.\n\nExample: Statistiche\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nRimuove le sessioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Tempo di inutilizzo. |\n| `callback` | `Function(err, count)` | no |  | Chiamata dopo la rimozione. |\n\nCon `lastusage` (per esempio `'7 days'`), rimuove le sessioni non usate per quel tempo e passa il loro numero. Senza, rimuove ogni sessione. `session.clean()` rimuove solo le sessioni scadute; il framework lo chiama ogni 10 minuti. `session.load([callback])` legge di nuovo dal file le sessioni salvate; `SESSION()` lo chiama alla creazione.\n\nExample: Rimuovere le sessioni vecchie\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nRilascia i dati degli elementi di SESSION() non usati per questo tempo.\n\nReturns: `String`\n\nOgni 10 minuti il framework chiama `releaseunused()` con questo valore su ogni store di sessioni. Predefinito `'-20 minutes'`. Le sessioni restano valide; i loro dati vengono caricati di nuovo con `ondata`.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabX1t4Qh61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/authorization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Autorizácia","summary":"AUTH(), flagy trás, roly, cookies a úložisko SESSION().","markdown":"---\ntitle: \"Autorizácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/authorization/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# Autorizácia\n\n> AUTH(), flagy trás, roly, cookies a úložisko SESSION().\n\nTotal.js prihlasuje požiadavky delegátom `AUTH()`, obmedzuje trasy flagmi `+` a `-` a uchováva relácie vo vstavanej relácii v cookie alebo v úložisku `SESSION()`. Príručka [Autorizácia](../../guides/authorization/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\nŠifrovanie má vlastnú stránku: [Šifrovanie](../encryption/).\n\n## API\n\n### AUTH(fn)\n\nType: `method`\n\nZaregistruje delegáta, ktorý prihlasuje každú požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function($)` | yes |  | Delegát. `$` je autorizačný objekt. |\n\nReturns: `undefined`\n\nDelegát sa spustí pri každej HTTP požiadavke, ktorá sa dostane k smerovaniu, a pri každom WebSocket spojení. Dostane autorizačný objekt `$` (pozri `$.success()`, `$.invalid()` a vlastnosti objektu `$`). Musí zavolať práve jednu z metód `$.success(user)`, `$.invalid()` alebo `$.cancel()`. Registrácia nového delegáta nahradí predchádzajúceho.\n\nAk namiesto funkcie odovzdáš objekt, spustí sa vstavaná relácia v cookie, pozri `AUTH(options)`.\n\nExample: Prihlásenie tokenom v hlavičke\n```js\nAUTH(function($) {\n\tvar token = $.headers['x-token'];\n\tif (token && token === CONF.apitoken)\n\t\t$.success({ id: 'api', name: 'API' });\n\telse\n\t\t$.invalid();\n});\n```\n\n### AUTH(options)\n\nType: `method`\n\nSpustí vstavaný mechanizmus relácií v cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Možnosti a delegáti relácie, pozri tabuľku. |\n\nReturns: `undefined` Metódy sa pridajú do `options`.\n\nS objektom `AUTH()` zaregistruje vlastného delegáta. Ten prečíta token relácie z cookie `options.cookie` (alebo z hlavičky `options.header`), dešifruje ho pomocou `options.secret` a drží údaje používateľa v pamäti počas `options.expire`. Keď údaje nie sú v cache, zavolá `options.onread()`. Požiadavky, ktoré čakajú na tú istú reláciu, zdieľajú jedno volanie `onread()`.\n\n`AUTH()` nič nevracia, ale do odovzdaného objektu pridá metódy: `logout()`, `update()`, `refresh()`, `sign()`, `authcookie()` a `auth()` (samotný delegát). Drž si na objekt referenciu.\n\n| Možnosť | Typ | Popis |\n| --- | --- | --- |\n| `secret` | String | Kľúč na šifrovanie tokenu. Vždy ho nastav. |\n| `cookie` | String | Názov cookie s tokenom. |\n| `header` | String | Názov hlavičky požiadavky s tokenom, použije sa, keď cookie chýba. Píš ho malými písmenami. |\n| `expire` | String | Ako dlho zostávajú údaje používateľa v pamäti. Predvolene `'5 minutes'`. |\n| `strict` | Boolean | Relácia v cache funguje len s rovnakým user agentom. Predvolene `true`. |\n| `ddos` | Number | Počet neúspešných pokusov z jednej IP adresy, po ktorom je každá požiadavka z tejto IP neplatná. Počítadlá sa vynulujú pri každom čistení. |\n| `cleaner` | Number | Interval čistenia v minútach. Predvolene `5`. |\n| `options` | Object | Možnosti cookie použité pri zápise alebo odstránení cookie. |\n| `onread` | Function(meta, next, $) | Načíta údaje používateľa, pozri `options.onread`. |\n| `onsession` | Function(session, $, init) | Volá sa, keď sa nájde relácia. Vráť `true`, ak chceš zastaviť spracovanie; potom na `$` odpovedz sám. `init` je `true`, keď sa údaje práve načítali. |\n| `onauthorize` | Function($) | Volá sa ako prvý pri každej požiadavke. Vráť `true`, ak chceš preskočiť vstavané spracovanie; potom na `$` odpovedz sám. |\n| `onlogout` | Function(session) | Volá ho `logout()`. |\n| `onfree` | Function(meta) | Volá sa po čistení s `{ sessions: Array, users: Array }`: odstránené ID relácií a ID používateľov bez živej relácie. |\n| `onddos` | Function($) | Volá sa, keď zablokovaná IP adresa pošle požiadavku. |\n| `locale` | Function(data, req) | Vráti jazyk požiadavky. `data` je `null` pre anonymných návštevníkov. |\n\nNeplatný alebo neznámy token cookie odstráni.\n\nExample: Vstavaná relácia\n```js\nvar opt = {};\nopt.secret = 'a-long-random-key';\nopt.cookie = 'session';\nopt.expire = '10 minutes';\nopt.onread = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.userid).callback(next);\n};\nAUTH(opt);\nMAIN.auth = opt;\n```\n\nExample: Jazyk používateľa\n```js\nopt.locale = function(data, req) {\n\treturn data ? data.language : '';\n};\n```\n\n### options.onread = function(meta, next, $)\n\nType: `delegate`\n\nNačíta údaje používateľa pre token relácie vo vstavanej relácii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ sessionid, userid, ip, ua }`. |\n| `next` | `Function(err, data)` | yes |  | Callback s údajmi používateľa. |\n| `$` | `Object` | yes |  | Autorizačný objekt. |\n\nVolá sa, keď platný token nemá údaje v cache. `meta` obsahuje `sessionid`, `userid`, `ip` a `ua`. Zavolaj `next(err, data)`: s údajmi sa relácia uloží do cache na `options.expire` a požiadavka je prihlásená; bez údajov sa cookie odstráni a požiadavka je anonymná. V databáze over, že relácia stále existuje, aby sa odhlásená relácia nedala znova použiť.\n\nExample: Načítanie používateľa\n```js\nopt.onread = function(meta, next) {\n\tNOSQL('sessions').one().where('id', meta.sessionid).callback(function(err, session) {\n\t\tif (session)\n\t\t\tNOSQL('users').one().where('id', meta.userid).callback(next);\n\t\telse\n\t\t\tnext();\n\t});\n};\n```\n\n### options.authcookie($, sessionid, userid, expiration, [cookieoptions])\n\nType: `method`\n\nZapíše cookie relácie vstavanej relácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objekt s metódou `cookie()`. |\n| `sessionid` | `String` | yes |  | Tvoje ID relácie. |\n| `userid` | `String` | yes |  | ID používateľa. |\n| `expiration` | `String|Date` | yes |  | Expirácia cookie, napríklad `'1 month'`. |\n| `cookieoptions` | `Object` | no | `options.options` | Možnosti cookie. |\n\nPodpíše `sessionid` a `userid` pomocou `options.sign()` a zapíše ich do cookie `options.cookie`. Zavolaj ju po overení prihlasovacích údajov a uložení relácie. `options.sign(sessionid, userid)` vráti ten istý token bez zápisu cookie, pre klientov, ktorí ho posielajú v hlavičke `options.header`. `$` je čokoľvek s metódou `cookie()`: kontrolér, `$` schémy alebo autorizačný `$`.\n\nExample: Prihlásenie\n```js\nvar sessionid = UID();\nNOSQL('sessions').insert({ id: sessionid, userid: user.id });\nMAIN.auth.authcookie(self, sessionid, user.id, '1 month');\nself.redirect('/');\n```\n\n### options.logout($)\n\nType: `method`\n\nOdhlási aktuálnu reláciu vstavanej relácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|String` | yes |  | Kontrolér alebo ID relácie. |\n\nReturns: `Boolean` `true`, keď sa relácia odstránila.\n\n`$` je kontrolér (alebo iný objekt so `sessionid`) alebo reťazec s ID relácie. Odstráni reláciu z pamäte, zavolá `options.onlogout(session)` a odstráni cookie, keď má `$` metódu `cookie()`. Vráti `true`, keď sa relácia našla. V `onlogout` vymaž reláciu z databázy, inak ju `onread` môže znova načítať.\n\nExample: Odhlásenie\n```js\nfunction logout() {\n\tvar self = this;\n\tMAIN.auth.logout(self);\n\tself.redirect('/');\n}\n```\n\n### options.update(userid, fn)\n\nType: `method` · Since: `0.0.56`\n\nZmení údaje v cache všetkých relácií používateľa vo vstavanej relácii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | ID používateľa. |\n| `fn` | `Function(data, session)` | yes |  | Volá sa pre každú reláciu. |\n\nReturns: `Number` Počet relácií.\n\nZavolá `fn(data, session)` pre každú reláciu `userid` v cache, takže objekt používateľa môžeš zmeniť priamo.\n\nExample: Premenovanie používateľa\n```js\nMAIN.auth.update(user.id, function(data) {\n\tdata.name = model.name;\n});\n```\n\n### options.refresh(userid, [exceptsessionid])\n\nType: `method` · Since: `0.0.56`\n\nZahodí údaje používateľa v cache vstavanej relácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `userid` | `String` | yes |  | ID používateľa. |\n| `exceptsessionid` | `String` | no |  | ID relácie, ktorá sa ponechá. |\n\nReturns: `Number` Počet odstránených relácií.\n\nOdstráni relácie používateľa z pamäte, takže ďalšia požiadavka znova zavolá `onread`. Cookies zostanú platné. Odovzdaj `exceptsessionid`, ak chceš jednu reláciu ponechať, napríklad aktuálnu.\n\nExample: Opätovné načítanie po zmene\n```js\nMAIN.auth.refresh(user.id, self.sessionid);\n```\n\n### $\n\nType: `class`\n\nObjekt `$`, ktorý dostane delegát AUTH().\n\nVlastnosti (len na čítanie): `$.req`, `$.res`, `$.ip`, `$.ua`, `$.url` (cesta malými písmenami), `$.uri`, `$.path`, `$.split`, `$.language`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.mobile` a `$.websocket` (`true` pre WebSocket spojenie).\n\nMetódy: `$.success(user)`, `$.invalid()`, `$.cancel()`, `$.cookie()`, `$.done()`, `$.audit(message, [type])` a `$.next(is, user)` (alias `$.callback()`). Počíta sa len prvá odpoveď; ďalšie volania sa ignorujú.\n\nVo WebSocket spojení je `$.res` WebSocket klient, takže cookies zapisovať nemôžeš.\n\nExample: Iné pravidlá pre WebSockety\n```js\nAUTH(function($) {\n\tvar token = $.websocket ? $.query.token : $.cookie('token');\n\tvar id = DECRYPTREQ($.req, token, 'auth');\n\tif (id)\n\t\t$.success({ id: id });\n\telse\n\t\t$.invalid();\n});\n```\n\n### $.success(user)\n\nType: `method`\n\nPrihlási požiadavku s objektom používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Prihlásený používateľ. |\n\nObjekt používateľa sa stane `controller.user`, `$.user` v schémach a `client.user` vo WebSocketoch. Trasy s `+` sa zhodujú; trasy s `-` nie. `$.done([user])` vráti callback `function(is, user)` pre asynchrónny kód: pravdivé `is` (alebo `null` s používateľom) požiadavku prihlási, `Error` ju označí ako anonymnú.\n\nExample: Prihlásenie\n```js\n$.success({ id: user.id, name: user.name, roles: user.roles });\n```\n\n### $.invalid([user])\n\nType: `method`\n\nOznačí požiadavku ako neprihlásenú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | no |  | Voliteľné údaje pre anonymného návštevníka. |\n\nZhodujú sa trasy s `-` a trasy bez flagu. Objekt používateľa odovzdaný sem sa stále nastaví ako `controller.user`, ale požiadavka sa počíta ako anonymná.\n\nExample: Bez tokenu\n```js\nif (!token) {\n\t$.invalid();\n\treturn;\n}\n```\n\n### $.cancel()\n\nType: `method` · Since: `0.0.89`\n\nZastaví autorizáciu a spracovanie požiadavky.\n\nReturns: `AuthOptions` Ten istý objekt.\n\nPouži ju, keď na požiadavku odpovedáš v delegátovi sám, napríklad presmerovaním cez `$.res`. Po `$.cancel()` framework požiadavku nesmeruje.\n\nExample: Presmerovanie starých domén\n```js\nAUTH(function($) {\n\tif ($.headers.host === 'old.example.com') {\n\t\t$.cancel();\n\t\t$.res.redirect('https://www.example.com' + $.url);\n\t\treturn;\n\t}\n\t$.invalid();\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nPrečíta alebo zapíše cookie v delegátovi AUTH().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String|null` | no |  | Nová hodnota; `null` cookie odstráni. |\n| `expire` | `String|Date` | no |  | Expirácia, napríklad `'1 month'`. |\n| `options` | `Object` | no |  | Možnosti cookie, pozri `controller.cookie()`. |\n\nReturns: `String|AuthOptions` Hodnota pri čítaní, inak `$`.\n\nLen s `name` vráti hodnotu cookie (prázdny reťazec, keď chýba). S `value` cookie zapíše. S `value` nastaveným na `null` ju odstráni. Rovnaká metóda existuje na objektoch `$` schém a operácií.\n\nExample: Odstránenie neplatnej cookie\n```js\nvar token = $.cookie('token');\nif (token && !DECRYPTREQ($.req, token, 'auth')) {\n\t$.cookie('token', null);\n\t$.invalid();\n\treturn;\n}\n```\n\n### ROUTE('+GET /url/') / ROUTE('-GET /url/')\n\nType: `config`\n\nObmedzí trasu na prihlásených alebo anonymných návštevníkov.\n\nURL, ktorá začína znakom `+` (alebo `🔒`), sa zhoduje len s požiadavkami prihlásenými cez `$.success()`. URL, ktorá začína znakom `-`, sa zhoduje len s požiadavkami označenými cez `$.invalid()`. Trasa bez flagu sa zhoduje s oboma. V poli flagov znamenajú `'authorize'`, `'authorized'` a `'logged'` to isté ako `+`; `'unauthorize'`, `'unauthorized'` a `'unlogged'` to isté ako `-`.\n\nTá istá URL môže mať trasu s `+` aj s `-`. Keď jediná trasa patrí opačnému stavu, odpoveď je `401`; keď neexistuje žiadna trasa, `404`. WebSocket trasy používajú rovnaké prefixy; WebSocket, ktorý sa nezhoduje, sa zatvorí s kódom `4001`.\n\nFlagy sa kontrolujú len vtedy, keď je zaregistrované `AUTH()`.\n\nExample: Jedna URL, dve trasy\n```js\nexports.install = function() {\n\tROUTE('+GET /', 'dashboard');\n\tROUTE('-GET /', 'login');\n\tROUTE('+SOCKET /live/', live);\n};\n```\n\nExample: Flagy v poli\n```js\nROUTE('GET /account/', account, ['authorize']);\n```\n\n### ROUTE('GET /url/', action, ['@role'])\n\nType: `config`\n\nOznačí trasu rolami.\n\nFlag, ktorý začína znakom `@`, je rola. Prevedie sa na malé písmená a uloží do `controller.route.flags` a trasa potrebuje prihláseného používateľa (ako pri `+`), pokiaľ nepridáš `-`. Total.js roly s používateľom neporovnáva: over ich v akcii, napríklad pomocou `UNAUTHORIZED()`.\n\nExample: Kontrola roly trasy\n```js\nROUTE('GET /admin/', admin, ['@admin']);\n\nfunction admin() {\n\tvar self = this;\n\tif (UNAUTHORIZED(self, 'admin'))\n\t\treturn;\n\tself.view('admin');\n}\n```\n\n### UNAUTHORIZED($, role, [role2], ...)\n\nType: `method`\n\nOverí roly prihláseného používateľa a odpovie 401, keď sa žiadna nezhoduje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Kontrolér alebo `$` schémy či operácie. |\n| `role` | `String` | yes |  | Jedna alebo viac rolí ako samostatné argumenty. |\n\nReturns: `Boolean` `true`, keď bola požiadavka odmietnutá.\n\nPorovná roly s `$.user.permissions` alebo `$.user.roles` (pole alebo objekt, ktorého kľúče sú roly). Vráti `false`, keď má používateľ niektorú z rolí alebo keď je `user.sa` či `user.su` pravdivé. Inak zavolá `$.invalid(401)` a vráti `true`, aj keď žiadny používateľ nie je.\n\nExample: V schéme\n```js\nschema.setRemove(function($) {\n\tif (UNAUTHORIZED($, 'admin', 'editor'))\n\t\treturn;\n\tNOSQL('articles').remove().where('id', $.id).callback($.done());\n});\n```\n\n### BLOCKED($, [limit], [expiration])\n\nType: `method`\n\nPočíta pokusy z IP adresy a určí, kedy ju zablokovať.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Controller|Object` | yes |  | Objekt s `ip`. |\n| `limit` | `Number` | no | `5` | Povolený počet pokusov. |\n| `expiration` | `String` | no | `'15 minutes'` | Ako dlho počítadlo žije. |\n\nReturns: `Boolean` `true`, keď je IP adresa zablokovaná.\n\nPouži ho na spomalenie hádania hesiel. Každé volanie pridá jeden pokus pre `$.ip`. Vráti `true`, keď je počet vyšší ako `limit`. S `limit` nastaveným na `-1` alebo `null` vynuluje počítadlo tejto IP adresy, napríklad po úspešnom prihlásení.\n\nExample: Prihlasovací formulár\n```js\nfunction login() {\n\tvar self = this;\n\tif (BLOCKED(self, 10)) {\n\t\tself.invalid('error-blocked');\n\t\treturn;\n\t}\n\t// ... on success:\n\tBLOCKED(self, -1);\n}\n```\n\n### controller.user\n\nType: `property`\n\nObjekt používateľa prihlásenej požiadavky.\n\nReturns: `Object`\n\nNastavuje ho `$.success(user)`. Pri anonymných požiadavkách je `undefined`. Môžeš ho priradiť. V schémach a operáciách čítaj `$.user`; vo WebSocketoch `client.user`.\n\nExample: Použitie používateľa\n```js\nfunction account() {\n\tvar self = this;\n\tself.view('account', { name: self.user.name });\n}\n```\n\n### $.user\n\nType: `property`\n\nPrihlásený používateľ v schémach a operáciách.\n\nReturns: `Object`\n\nVráti `controller.user` požiadavky alebo `null`, keď operácia beží bez kontroléra.\n\nExample: Vlastník záznamu\n```js\nschema.setInsert(function($, model) {\n\tmodel.userid = $.user.id;\n\tNOSQL('notes').insert(model).callback($.done());\n});\n```\n\n### controller.session / controller.sessionid\n\nType: `property`\n\nObjekt relácie a ID relácie požiadavky.\n\nReturns: `Object / String`\n\nObe čítajú a zapisujú `req.session` a `req.sessionid`. Vstavané `AUTH(options)` ich nastaví na reláciu v cache (`{ sessionid, userid, data, ua, expire }`) a jej ID. `SESSION().getcookie()`, `gettoken()`, `setcookie()` a `settoken()` nastavujú `sessionid`. Rovnaké vlastnosti existujú na objektoch `$` schém a na WebSocket klientoch.\n\nExample: Odhlásenie z úložiska SESSION()\n```js\nsession.remove(self.sessionid);\n```\n\n### controller.cookie(name, [value], [expires], [options])\n\nType: `method`\n\nPrečíta alebo zapíše cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String` | no |  | Nová hodnota. |\n| `expires` | `String|Date|Object` | no |  | Expirácia alebo možnosti. |\n| `options` | `Object` | no |  | Možnosti cookie. |\n\nReturns: `String|Controller` Hodnota pri čítaní, inak kontrolér.\n\nLen s `name` vráti dekódovanú hodnotu cookie alebo prázdny reťazec. S `value` pridá hlavičku `Set-Cookie` a vráti kontrolér. Ak chceš cookie odstrániť, zapíš prázdnu hodnotu s expiráciou v minulosti, napríklad `'-1 day'`.\n\n`expires` je `Date` alebo reťazec ako `'1 month'`. Namiesto `expires` môžeš odovzdať objekt možností, ktorý potom môže obsahovať `expires`.\n\n| Možnosť | Popis |\n| --- | --- |\n| `domain` | Doména cookie. |\n| `path` | Cesta cookie. Predvolene `/`. |\n| `secure` | `true` pridá `Secure`. Predvolene `CONF.default_cookies_secure`. |\n| `httponly` | `true` pridá `HttpOnly`. |\n| `samesite` alebo `security` | `'Lax'`, `'Strict'` alebo `'None'` (alebo `1` pre Lax, `2` pre Strict). Predvolene `CONF.default_cookies_samesite`. |\n\nPo odoslaní odpovede sa cookie už nezapíše.\n\nExample: Zápis a čítanie\n```js\nself.cookie('theme', 'dark', '1 year', { httponly: true });\nvar theme = self.cookie('theme');\n```\n\nExample: Odstránenie\n```js\nself.cookie('token', '', '-1 day');\n```\n\n### res.cookie(name, value, [expires], [options])\n\nType: `method`\n\nZapíše cookie do HTTP odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String` | yes |  | Hodnota. |\n| `expires` | `String|Date|Object` | no |  | Expirácia alebo možnosti. |\n| `options` | `Object` | no |  | Možnosti cookie. |\n\nReturns: `Response`\n\nNízkoúrovňová metóda, na ktorej stojí `controller.cookie()`, s rovnakými možnosťami. Použi ju tam, kde máš len odpoveď, napríklad `$.res` v delegátovi AUTH(). `req.cookie(name)` prečíta cookie z požiadavky.\n\nExample: Z delegáta\n```js\n$.res.cookie('visited', '1', '1 day');\nvar old = $.req.cookie('visited');\n```\n\n### default_cookies_samesite : Lax\n\nType: `config`\n\nPredvolený atribút SameSite pre cookies.\n\nReturns: `String`\n\nPoužije sa, keď cookie nemá možnosť `samesite`/`security`. Predvolene `'Lax'`.\n\nExample: config\n```js\n// /config\ndefault_cookies_samesite : Strict\n```\n\n### default_cookies_secure : false\n\nType: `config`\n\nPridá atribút Secure ku každej cookie.\n\nReturns: `Boolean`\n\nPoužije sa, keď cookie nemá možnosť `secure`. Predvolene `false`. Zapni ho, keď aplikácia beží len na HTTPS.\n\nExample: config\n```js\n// /config\ndefault_cookies_secure : true\n```\n\n### SESSION([name])\n\nType: `method`\n\nVráti pomenované úložisko relácií.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Názov úložiska. |\n\nReturns: `Session` Úložisko.\n\nPrvé volanie vytvorí úložisko a načíta jeho uložené relácie; ďalšie volania vrátia tú istú inštanciu. Predvolený názov je `default`, ukladá sa do `databases/sessions.txt`; iné názvy používajú `databases/sessions_NAME.txt`. Súbor sa zapíše 10 sekúnd po zmene a obsahuje len metadáta každej relácie: `sessionid`, `id`, `expire`, `used`, `created`, `note` a `settings`. Údaje používateľa zostávajú v pamäti; po reštarte ich úložisko načíta cez `session.ondata`.\n\nPoložka relácie má vlastnosti `sessionid`, `id` (ID používateľa), `data`, `expire`, `used`, `created`, `note`, `settings` a `released`. Vlastnosti úložiska: `name` a `items` (`Map` položiek podľa ID relácie).\n\nExpirované relácie sa odstraňujú každých 10 minút. V klastri sa zmeny posielajú ostatným procesom.\n\nExample: Vytvorenie úložiska\n```js\nvar session = SESSION();\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.ondata = function(meta, next)\n\nType: `delegate`\n\nNačíta údaje relácie, ktorá nie je v pamäti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Položka relácie: `sessionid`, `id`, `note`, `settings`... |\n| `next` | `Function(err, data)` | yes |  | Callback s údajmi. |\n\nVolajú ho `get()`, `getcookie()` a `gettoken()`, keď položka nemá údaje: po reštarte alebo po uvoľnení údajov. `meta` je položka relácie. Zavolaj `next(err, data)`. Volania pre to isté ID používateľa čakajú na jedno načítanie. Bez `ondata` nerobia `release()`, `release2()` nič.\n\nExample: Načítanie používateľa\n```js\nsession.ondata = function(meta, next) {\n\tNOSQL('users').one().where('id', meta.id).callback(next);\n};\n```\n\n### session.onremove = function(item)\n\nType: `event`\n\nVolá sa, keď sa relácia odstráni alebo vyprší.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Položka relácie. |\n\nVolajú ho aj `clear()` a `remove2()`. Súrodenecký delegát `session.onrelease = function(item)` sa volá, keď sa údaje relácie uvoľnia z pamäte.\n\nExample: Logovanie odstránených relácií\n```js\nsession.onremove = function(item) {\n\titem && console.log('Session ended:', item.sessionid);\n};\n```\n\n### session.setcookie(res, opt, [callback])\n\nType: `method`\n\nVytvorí reláciu a zapíše jej cookie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Controller|Object` | yes |  | Kam sa cookie zapíše. |\n| `opt` | `Object` | yes |  | Možnosti, pozri tabuľku. |\n| `callback` | `Function(err, data, meta)` | no |  | Volá sa po vytvorení relácie. |\n\nZavolá `session.set()` a zapíše zašifrovanú cookie (vytvorenú pomocou `ENCRYPTREQ()`) s ID relácie a ID používateľa. `res` môže byť kontrolér, `$` schémy, autorizačný `$` alebo odpoveď.\n\n| Možnosť | Popis |\n| --- | --- |\n| `name` | Názov cookie. |\n| `sessionid` | ID relácie. Predvolene `UID()`. |\n| `id` | ID používateľa. |\n| `data` | Údaje relácie. |\n| `expire` | Expirácia, napríklad `'1 month'`. |\n| `key` (alebo `secret`) | Šifrovací kľúč. |\n| `strict` | Viazať cookie aj na IP adresu. Predvolene `false`. |\n| `note` | Poznámka, napríklad user agent. |\n| `settings` | Reťazec s nastaveniami. |\n| `options` | Možnosti cookie. Predvolene `{ httponly: true, security: 'lax' }`. |\n\nExample: Prihlásenie\n```js\nsession.setcookie(self, { name: 'sid', id: user.id, data: user, expire: '1 month', key: 'session-key' }, function() {\n\tself.redirect('/');\n});\n```\n\n### session.getcookie(req, opt, callback, [param])\n\nType: `method`\n\nPrečíta reláciu z cookie požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Autorizačný `$`, kontrolér alebo požiadavka. |\n| `opt` | `Object` | yes |  | Možnosti, pozri tabuľku. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | `data` sú údaje relácie, `meta` položka, `init` je `true`, keď údaje načítalo `ondata`. |\n| `param` | `Any` | no |  | Hodnota odovzdaná do callbacku. |\n\nDešifruje cookie pomocou `DECRYPTREQ()` a zavolá `session.get()`. `req` môže byť autorizačný `$`, kontrolér alebo požiadavka. Tokeny kratšie ako 20 znakov sa ignorujú. Neplatná cookie sa odstráni a s `ddos` sa každý neúspešný pokus započíta IP adrese.\n\n| Možnosť | Popis |\n| --- | --- |\n| `name` | Názov cookie. |\n| `expire` | Predĺži reláciu a cookie o tento čas. |\n| `key` (alebo `secret`) | Šifrovací kľúč. |\n| `extendcookie` | Predĺžiť cookie o `expire`. Predvolene `true`. |\n| `removecookie` | Odstrániť neplatnú cookie. Predvolene `true`. |\n| `options` | Možnosti cookie. |\n| `ddos` | Počet neúspešných pokusov z IP adresy, po ktorom sa cookie už nekontroluje. |\n\nExample: V AUTH()\n```js\nAUTH(function($) {\n\tsession.getcookie($, { name: 'sid', expire: '1 month', key: 'session-key', ddos: 5 }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.settoken(res, opt, [callback])\n\nType: `method`\n\nVytvorí reláciu a namiesto cookie vráti token.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Object` | yes |  | Kontrolér, `$` schémy alebo odpoveď. |\n| `opt` | `Object` | yes |  | Možnosti `setcookie()`. |\n| `callback` | `Function(err, token, data, meta)` | no |  | Dostane token. |\n\nBerie možnosti `setcookie()` okrem `name` a `options` a zašifrovaný token odovzdá do callbacku. Token pošli klientovi, napríklad v JSON.\n\nExample: Prihlásenie cez API\n```js\nsession.settoken(self, { id: user.id, data: user, expire: '7 days', key: 'session-key' }, function(err, token) {\n\tself.json({ token: token });\n});\n```\n\n### session.gettoken(req, opt, callback, [param])\n\nType: `method`\n\nPrečíta reláciu z tokenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Object` | yes |  | Autorizačný `$` alebo požiadavka. |\n| `opt` | `Object` | yes |  | Možnosti. |\n| `callback` | `Function(err, data, meta, init, param)` | yes |  | Volá sa s reláciou. |\n| `param` | `Any` | no |  | Hodnota odovzdaná do callbacku. |\n\nAko `getcookie()`, s tokenom v `opt.token`. Možnosti: `token`, `expire`, `key` (alebo `secret`) a `ddos`.\n\nExample: Token v hlavičke\n```js\nAUTH(function($) {\n\tsession.gettoken($, { token: $.headers['x-token'], key: 'session-key' }, function(err, data) {\n\t\tif (data)\n\t\t\t$.success(data);\n\t\telse\n\t\t\t$.invalid();\n\t});\n});\n```\n\n### session.set(sessionid, [id], data, expire, [note], [settings], [callback])\n\nType: `method`\n\nVytvorí alebo nahradí reláciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID relácie. |\n| `id` | `String` | no |  | ID používateľa. |\n| `data` | `Object` | yes |  | Údaje relácie. |\n| `expire` | `String` | yes |  | Expirácia. |\n| `note` | `String` | no |  | Poznámka. |\n| `settings` | `String` | no |  | Nastavenia. |\n| `callback` | `Function(err, data, meta)` | no |  | Volá sa po zmene. |\n\n`id` je ID používateľa; môžeš ho vynechať, keď je `data` objekt. `expire` je povinné, napríklad `'1 month'`. `session.set2(id, data, [expire], [note], [settings], [callback])` nahradí údaje všetkých načítaných relácií používateľa `id` a odovzdá počet aktualizovaných relácií.\n\nExample: Vytvorenie relácie\n```js\nsession.set(UID(), user.id, user, '1 month', $.ua);\n```\n\n### session.get(sessionid, [expire], callback)\n\nType: `method`\n\nPrečíta reláciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID relácie. |\n| `expire` | `String` | no |  | Predĺži reláciu o tento čas. |\n| `callback` | `Function(err, data, meta, init)` | yes |  | Volá sa s reláciou. |\n\nVráti údaje cez callback a aktualizuje `used`. S `expire` sa relácia predĺži. Expirovaná relácia sa odstráni. Keď údaje nie sú v pamäti, načíta ich `ondata` a `init` je `true`. `session.get2(id, callback(err, items))` vráti všetky živé položky používateľa `id`.\n\nExample: Čítanie\n```js\nsession.get(self.sessionid, function(err, data, meta) {\n\tself.json(data);\n});\n```\n\n### session.update(sessionid, data, [expire], [note], [settings], [callback])\n\nType: `method`\n\nZmení reláciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID relácie. |\n| `data` | `Object` | yes |  | Nové údaje. |\n| `expire` | `String` | no |  | Nová expirácia od teraz. |\n| `note` | `String` | no |  | Nová poznámka. |\n| `settings` | `String` | no |  | Nové nastavenia. |\n| `callback` | `Function` | no |  | Volá sa po zmene. |\n\nÚdaje nahradí len vtedy, keď sú načítané; `note`, `settings` a `expire` sa menia vždy. Callback dostane `(null, data, meta)`, alebo žiadne argumenty, keď relácia chýba alebo nie je načítaná. `session.update2(id, data, [expire], [note], [settings], [callback])` urobí to isté pre všetky relácie používateľa `id` a odovzdá počet aktualizovaných relácií.\n\nExample: Aktualizácia všetkých relácií používateľa\n```js\nsession.update2(user.id, user, function(err, count) {\n\tconsole.log('Updated', count);\n});\n```\n\n### session.remove(sessionid, [callback])\n\nType: `method`\n\nOdstráni reláciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | yes |  | ID relácie alebo položka. |\n| `callback` | `Function(err, item)` | no |  | Volá sa po odstránení. |\n\n`sessionid` môže byť aj položka relácie. Callback dostane `(null, item)`. `session.remove2(id, [callback])` odstráni všetky relácie používateľa `id` a odovzdá ich počet, napríklad na odhlásenie používateľa všade.\n\nExample: Odhlásenie\n```js\nsession.remove(self.sessionid);\nself.cookie('sid', '', '-1 day');\n```\n\nExample: Odhlásenie všade\n```js\nsession.remove2(user.id);\n```\n\n### session.release([sessionid], [expire], [callback])\n\nType: `method`\n\nUvoľní údaje relácie z pamäte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String|Object` | no |  | ID relácie alebo položka. |\n| `expire` | `String` | no |  | Používa ho `release2()`. |\n| `callback` | `Function(err, count)` | no |  | Volá sa s počtom. |\n\nRelácia zostane platná; ďalšie čítanie načíta údaje znova cez `ondata`. Bez `sessionid` (alebo s `null`) uvoľní všetky relácie a odovzdá ich počet. `session.release2(id, [expire], [callback])` uvoľní všetky relácie používateľa `id` a s `expire` nastaví ich novú expiráciu. `session.releaseunused(lastusage, [callback])` uvoľní relácie nepoužité počas `lastusage`, napríklad `'30 minutes'`; framework ju volá každých 10 minút s `CONF.allow_sessions_unused` (predvolene `'-20 minutes'`). Bez `ondata` nerobia `release()` a `release2()` nič.\n\nExample: Opätovné načítanie používateľa po zmene\n```js\nsession.release2(user.id);\n```\n\n### session.contains(sessionid, callback)\n\nType: `method`\n\nVráti reláciu len vtedy, keď sú jej údaje v pamäti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sessionid` | `String` | yes |  | ID relácie. |\n| `callback` | `Function(err, data, meta)` | yes |  | Volá sa s výsledkom. |\n\nNa rozdiel od `get()` nikdy nevolá `ondata`. Callback dostane `(null, data, meta)` alebo žiadne argumenty. `session.contains2(id, callback)` nájde prvú takú reláciu používateľa `id`. `session.has(sessionid, callback(err, bool))` a `session.has2(id, callback(err, bool))` len povedia, či relácia existuje.\n\nExample: Je používateľ online?\n```js\nsession.has2(user.id, function(err, is) {\n\tconsole.log(is ? 'online' : 'offline');\n});\n```\n\n### session.list(id, callback)\n\nType: `method`\n\nVypíše živé relácie používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID používateľa. |\n| `callback` | `Function(err, items)` | yes |  | Volá sa s položkami. |\n\nOdovzdá pole položiek relácií používateľa `id` a odstráni expirované položky. `session.listlive(callback)` vypíše všetky relácie s načítanými údajmi, pre ľubovoľného používateľa.\n\nExample: Zariadenia používateľa\n```js\nsession.list(self.user.id, function(err, items) {\n\tself.json(items.map(function(item) {\n\t\treturn { id: item.sessionid, note: item.note, used: item.used };\n\t}));\n});\n```\n\n### session.count([id], callback)\n\nType: `method`\n\nSpočíta relácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | ID používateľa. |\n| `callback` | `Function(err, stats)` | yes |  | Volá sa s počtami. |\n\nOdovzdá `{ used, free, count }`: relácie `used` majú načítané údaje, `free` nie. S `id` spočíta len relácie daného používateľa. `session.usage()` vráti ten istý objekt pre všetky relácie priamo.\n\nExample: Štatistiky\n```js\nsession.count(function(err, stats) {\n\tconsole.log(stats.count, 'sessions');\n});\nconsole.log(session.usage());\n```\n\n### session.clear([lastusage], [callback])\n\nType: `method`\n\nOdstráni relácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lastusage` | `String` | no |  | Čas nepoužívania. |\n| `callback` | `Function(err, count)` | no |  | Volá sa po odstránení. |\n\nS `lastusage` (napríklad `'7 days'`) odstráni relácie nepoužité počas tohto času a odovzdá ich počet. Bez neho odstráni všetky relácie. `session.clean()` odstráni len expirované relácie; framework ju volá každých 10 minút. `session.load([callback])` znova načíta uložené relácie zo súboru; `SESSION()` ju volá pri vytvorení.\n\nExample: Odstránenie starých relácií\n```js\nsession.clear('30 days');\n```\n\n### allow_sessions_unused : -20 minutes\n\nType: `config`\n\nUvoľní údaje položiek SESSION() nepoužitých počas tohto času.\n\nReturns: `String`\n\nKaždých 10 minút framework volá `releaseunused()` s touto hodnotou na každom úložisku relácií. Predvolene `'-20 minutes'`. Relácie zostanú platné; ich údaje sa znova načítajú cez `ondata`.\n\nExample: config\n```js\n// /config\nallow_sessions_unused : -1 hour\n```\n","entries":[{"type":"method","name":"AUTH()","signature":"AUTH(fn)","since":"","deprecated":false},{"type":"method","name":"AUTH(options)","signature":"AUTH(options)","since":"","deprecated":false},{"type":"delegate","name":"options.onread","signature":"options.onread = function(meta, next, $)","since":"","deprecated":false},{"type":"method","name":"options.authcookie()","signature":"options.authcookie($, sessionid, userid, expiration, [cookieoptions])","since":"","deprecated":false},{"type":"method","name":"options.logout()","signature":"options.logout($)","since":"","deprecated":false},{"type":"method","name":"options.update()","signature":"options.update(userid, fn)","since":"0.0.56","deprecated":false},{"type":"method","name":"options.refresh()","signature":"options.refresh(userid, [exceptsessionid])","since":"0.0.56","deprecated":false},{"type":"class","name":"AuthOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success(user)","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([user])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"0.0.89","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"config","name":"+ and - route flags","signature":"ROUTE('+GET /url/') / ROUTE('-GET /url/')","since":"","deprecated":false},{"type":"config","name":"@role route flags","signature":"ROUTE('GET /url/', action, ['@role'])","since":"","deprecated":false},{"type":"method","name":"UNAUTHORIZED()","signature":"UNAUTHORIZED($, role, [role2], ...)","since":"","deprecated":false},{"type":"method","name":"BLOCKED()","signature":"BLOCKED($, [limit], [expiration])","since":"","deprecated":false},{"type":"property","name":"controller.user","signature":"controller.user","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"controller.session","signature":"controller.session / controller.sessionid","since":"","deprecated":false},{"type":"method","name":"controller.cookie()","signature":"controller.cookie(name, [value], [expires], [options])","since":"","deprecated":false},{"type":"method","name":"res.cookie()","signature":"res.cookie(name, value, [expires], [options])","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_samesite","signature":"default_cookies_samesite : Lax","since":"","deprecated":false},{"type":"config","name":"CONF.default_cookies_secure","signature":"default_cookies_secure : false","since":"","deprecated":false},{"type":"method","name":"SESSION()","signature":"SESSION([name])","since":"","deprecated":false},{"type":"delegate","name":"session.ondata","signature":"session.ondata = function(meta, next)","since":"","deprecated":false},{"type":"event","name":"session.onremove","signature":"session.onremove = function(item)","since":"","deprecated":false},{"type":"method","name":"session.setcookie()","signature":"session.setcookie(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.getcookie()","signature":"session.getcookie(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.settoken()","signature":"session.settoken(res, opt, [callback])","since":"","deprecated":false},{"type":"method","name":"session.gettoken()","signature":"session.gettoken(req, opt, callback, [param])","since":"","deprecated":false},{"type":"method","name":"session.set()","signature":"session.set(sessionid, [id], data, expire, [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.get()","signature":"session.get(sessionid, [expire], callback)","since":"","deprecated":false},{"type":"method","name":"session.update()","signature":"session.update(sessionid, data, [expire], [note], [settings], [callback])","since":"","deprecated":false},{"type":"method","name":"session.remove()","signature":"session.remove(sessionid, [callback])","since":"","deprecated":false},{"type":"method","name":"session.release()","signature":"session.release([sessionid], [expire], [callback])","since":"","deprecated":false},{"type":"method","name":"session.contains()","signature":"session.contains(sessionid, callback)","since":"","deprecated":false},{"type":"method","name":"session.list()","signature":"session.list(id, callback)","since":"","deprecated":false},{"type":"method","name":"session.count()","signature":"session.count([id], callback)","since":"","deprecated":false},{"type":"method","name":"session.clear()","signature":"session.clear([lastusage], [callback])","since":"","deprecated":false},{"type":"config","name":"CONF.allow_sessions_unused","signature":"allow_sessions_unused : -20 minutes","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JafRk81vh60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Encryption","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and CONF.secret.","markdown":"---\ntitle: Encryption\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Encryption\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() and CONF.secret.\n\nThe functions that encrypt and decrypt values, and the secret they use. The guide [Encryption](../../guides/encryption/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nEncrypts a value with CONF.secret and a key.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | The value. |\n| `key` | `String` | no |  | Your key, combined with `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Different output for the same input. |\n\nReturns: `String` The encrypted value; an empty string for `null`.\n\nObjects are serialized to JSON, numbers to strings, and a function is called for its value. The result is a string you can store in a cookie or a URL. When `CONF.default_crypto` is set to a Node.js cipher name, the value is encrypted with that cipher, `key` as the cipher key and `CONF.default_crypto_iv`.\n\nExample: Encrypt an object\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nDecrypts a value from ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The encrypted value. |\n| `key` | `String` | no |  | The same key as in `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Parse the result as JSON. |\n\nReturns: `Object|String|null`\n\nBy default the result is parsed as JSON and `null` is returned when it is not JSON, so pass `false` as `jsonConvert` for a plain string. Returns `null` when the value cannot be decrypted.\n\nExample: Decrypt\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Plain string\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nEncrypts a value bound to the browser of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | The request. |\n| `value` | `Object|String` | yes |  | The value. |\n| `key` | `String` | no |  | Encryption key. |\n| `strict` | `Boolean` | no | `false` | Bind to the IP address too. |\n\nReturns: `String` The token.\n\nStores the user agent (and with `strict` the IP address) next to `value` and encrypts it with `ENCRYPT()`. `DECRYPTREQ()` returns the value only for a request with the same user agent (and IP address). `req` can be a request or a controller.\n\nExample: Sign-in cookie\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nDecrypts a value from ENCRYPTREQ() for the same browser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | The request. |\n| `value` | `String` | yes |  | The token. |\n| `key` | `String` | no |  | The same key as in `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nReturns the value, or `undefined` when it cannot be decrypted, or the user agent (or the IP address in strict mode) differs from the request.\n\nExample: In AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nThe secret of the app used by ENCRYPT() and DECRYPT().\n\nReturns: `String`\n\nDefaults to a hash generated for the app. Set your own value in `/config` so tokens stay valid when the app moves to another server. Changing it makes all encrypted tokens invalid.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafRk81vh60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Verschlüsselung","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() und CONF.secret.","markdown":"---\ntitle: \"Verschlüsselung\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Verschlüsselung\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() und CONF.secret.\n\nDie Funktionen, die Werte ver- und entschlüsseln, und das Secret, das sie verwenden. Der Guide [Verschlüsselung](../../guides/encryption/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nVerschlüsselt einen Wert mit CONF.secret und einem Schlüssel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | Der Wert. |\n| `key` | `String` | no |  | Dein Schlüssel, kombiniert mit `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Unterschiedliche Ausgabe für dieselbe Eingabe. |\n\nReturns: `String` Der verschlüsselte Wert; ein leerer String für `null`.\n\nObjekte werden zu JSON serialisiert, Zahlen zu Strings, und eine Funktion wird aufgerufen, um ihren Wert zu erhalten. Das Ergebnis ist ein String, den du in einem Cookie oder einer URL speichern kannst. Ist `CONF.default_crypto` auf den Namen einer Node.js-Cipher gesetzt, wird der Wert mit dieser Cipher verschlüsselt, mit `key` als Cipher-Schlüssel und `CONF.default_crypto_iv`.\n\nExample: Ein Objekt verschlüsseln\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nEntschlüsselt einen Wert aus ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der verschlüsselte Wert. |\n| `key` | `String` | no |  | Derselbe Schlüssel wie in `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Das Ergebnis als JSON parsen. |\n\nReturns: `Object|String|null`\n\nStandardmäßig wird das Ergebnis als JSON geparst, und `null` wird zurückgegeben, wenn es kein JSON ist; übergib also `false` als `jsonConvert` für einen reinen String. Gibt `null` zurück, wenn der Wert nicht entschlüsselt werden kann.\n\nExample: Entschlüsseln\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Reiner String\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nVerschlüsselt einen Wert, der an den Browser des Requests gebunden ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | Der Request. |\n| `value` | `Object|String` | yes |  | Der Wert. |\n| `key` | `String` | no |  | Verschlüsselungsschlüssel. |\n| `strict` | `Boolean` | no | `false` | Auch an die IP-Adresse binden. |\n\nReturns: `String` Das Token.\n\nSpeichert den User-Agent (und mit `strict` die IP-Adresse) neben `value` und verschlüsselt alles mit `ENCRYPT()`. `DECRYPTREQ()` gibt den Wert nur für einen Request mit demselben User-Agent (und derselben IP-Adresse) zurück. `req` kann ein Request oder ein Controller sein.\n\nExample: Anmelde-Cookie\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nEntschlüsselt einen Wert aus ENCRYPTREQ() für denselben Browser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | Der Request. |\n| `value` | `String` | yes |  | Das Token. |\n| `key` | `String` | no |  | Derselbe Schlüssel wie in `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nGibt den Wert zurück oder `undefined`, wenn er nicht entschlüsselt werden kann oder der User-Agent (oder im Strict-Modus die IP-Adresse) vom Request abweicht.\n\nExample: In AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nDas Secret der App, das ENCRYPT() und DECRYPT() verwenden.\n\nReturns: `String`\n\nStandardmäßig ein für die App erzeugter Hash. Setze in `/config` einen eigenen Wert, damit Tokens gültig bleiben, wenn die App auf einen anderen Server umzieht. Eine Änderung macht alle verschlüsselten Tokens ungültig.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafRk81vh60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Cifrado","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() y CONF.secret.","markdown":"---\ntitle: Cifrado\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Cifrado\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() y CONF.secret.\n\nLas funciones que cifran y descifran valores, y el secreto que usan. La guía [Cifrado](../../guides/encryption/) explica cómo usarlas con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nCifra un valor con CONF.secret y una clave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | El valor. |\n| `key` | `String` | no |  | Tu clave, combinada con `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Resultado distinto para la misma entrada. |\n\nReturns: `String` El valor cifrado; una cadena vacía para `null`.\n\nLos objetos se serializan a JSON, los números a cadenas, y una función se llama para obtener su valor. El resultado es una cadena que puedes guardar en una cookie o en una URL. Cuando `CONF.default_crypto` tiene el nombre de un cifrado de Node.js, el valor se cifra con ese cifrado, `key` como clave del cifrado y `CONF.default_crypto_iv`.\n\nExample: Cifrar un objeto\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nDescifra un valor de ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El valor cifrado. |\n| `key` | `String` | no |  | La misma clave que en `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Analizar el resultado como JSON. |\n\nReturns: `Object|String|null`\n\nPor defecto el resultado se analiza como JSON y se devuelve `null` cuando no es JSON, así que pasa `false` como `jsonConvert` para obtener una cadena simple. Devuelve `null` cuando el valor no se puede descifrar.\n\nExample: Descifrar\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Cadena simple\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nCifra un valor ligado al navegador de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La petición. |\n| `value` | `Object|String` | yes |  | El valor. |\n| `key` | `String` | no |  | Clave de cifrado. |\n| `strict` | `Boolean` | no | `false` | Ligar también a la dirección IP. |\n\nReturns: `String` El token.\n\nGuarda el user agent (y con `strict` la dirección IP) junto a `value` y lo cifra con `ENCRYPT()`. `DECRYPTREQ()` devuelve el valor solo para una petición con el mismo user agent (y dirección IP). `req` puede ser una petición o un controlador.\n\nExample: Cookie de inicio de sesión\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nDescifra un valor de ENCRYPTREQ() para el mismo navegador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La petición. |\n| `value` | `String` | yes |  | El token. |\n| `key` | `String` | no |  | La misma clave que en `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nDevuelve el valor, o `undefined` cuando no se puede descifrar o cuando el user agent (o la dirección IP en modo estricto) es distinto del de la petición.\n\nExample: En AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nEl secreto de la app usado por ENCRYPT() y DECRYPT().\n\nReturns: `String`\n\nPor defecto es un hash generado para la app. Define tu propio valor en `/config` para que los tokens sigan siendo válidos cuando la app se mueva a otro servidor. Cambiarlo invalida todos los tokens cifrados.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafRk81vh60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Chiffrement","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() et CONF.secret.","markdown":"---\ntitle: Chiffrement\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Chiffrement\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() et CONF.secret.\n\nLes fonctions qui chiffrent et déchiffrent des valeurs, et le secret qu'elles utilisent. Le guide [Chiffrement](../../guides/encryption/) explique comment les utiliser avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nChiffre une valeur avec CONF.secret et une clé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | La valeur. |\n| `key` | `String` | no |  | Ta clé, combinée avec `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Résultat différent pour une même entrée. |\n\nReturns: `String` La valeur chiffrée ; une chaîne vide pour `null`.\n\nLes objets sont sérialisés en JSON, les nombres en chaînes, et une fonction est appelée pour obtenir sa valeur. Le résultat est une chaîne que tu peux stocker dans un cookie ou une URL. Quand `CONF.default_crypto` contient le nom d'un algorithme de chiffrement de Node.js, la valeur est chiffrée avec cet algorithme, `key` comme clé et `CONF.default_crypto_iv`.\n\nExample: Chiffrer un objet\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nDéchiffre une valeur produite par ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La valeur chiffrée. |\n| `key` | `String` | no |  | La même clé que dans `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Analyser le résultat comme du JSON. |\n\nReturns: `Object|String|null`\n\nPar défaut, le résultat est analysé comme du JSON et `null` est renvoyé si ce n'est pas du JSON ; passe donc `false` comme `jsonConvert` pour obtenir une chaîne brute. Renvoie `null` quand la valeur ne peut pas être déchiffrée.\n\nExample: Déchiffrer\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Chaîne brute\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nChiffre une valeur liée au navigateur de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La requête. |\n| `value` | `Object|String` | yes |  | La valeur. |\n| `key` | `String` | no |  | Clé de chiffrement. |\n| `strict` | `Boolean` | no | `false` | Lier aussi à l'adresse IP. |\n\nReturns: `String` Le token.\n\nStocke le user agent (et, avec `strict`, l'adresse IP) à côté de `value` et chiffre le tout avec `ENCRYPT()`. `DECRYPTREQ()` ne renvoie la valeur que pour une requête avec le même user agent (et la même adresse IP). `req` peut être une requête ou un contrôleur.\n\nExample: Cookie de connexion\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nDéchiffre une valeur produite par ENCRYPTREQ() pour le même navigateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La requête. |\n| `value` | `String` | yes |  | Le token. |\n| `key` | `String` | no |  | La même clé que dans `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nRenvoie la valeur, ou `undefined` quand elle ne peut pas être déchiffrée ou que le user agent (ou l'adresse IP en mode strict) diffère de celui de la requête.\n\nExample: Dans AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nLe secret de l'application utilisé par ENCRYPT() et DECRYPT().\n\nReturns: `String`\n\nPar défaut, un hash généré pour l'application. Définis ta propre valeur dans `/config` pour que les tokens restent valides quand l'application change de serveur. Le modifier invalide tous les tokens chiffrés.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafRk81vh60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Cifratura","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() e CONF.secret.","markdown":"---\ntitle: Cifratura\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Cifratura\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() e CONF.secret.\n\nLe funzioni che cifrano e decifrano i valori e il secret che usano. La guida [Cifratura](../../guides/encryption/) spiega come usarle con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nCifra un valore con CONF.secret e una chiave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | Il valore. |\n| `key` | `String` | no |  | La tua chiave, combinata con `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Output diverso per lo stesso input. |\n\nReturns: `String` Il valore cifrato; una stringa vuota per `null`.\n\nGli oggetti vengono serializzati in JSON, i numeri in stringhe, e una funzione viene chiamata per ottenerne il valore. Il risultato è una stringa che puoi salvare in un cookie o in un URL. Quando `CONF.default_crypto` è impostato al nome di un cifrario di Node.js, il valore viene cifrato con quel cifrario, `key` come chiave del cifrario e `CONF.default_crypto_iv`.\n\nExample: Cifrare un oggetto\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nDecifra un valore prodotto da ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il valore cifrato. |\n| `key` | `String` | no |  | La stessa chiave usata in `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Analizza il risultato come JSON. |\n\nReturns: `Object|String|null`\n\nPer impostazione predefinita il risultato viene analizzato come JSON e viene restituito `null` quando non è JSON, quindi passa `false` come `jsonConvert` per una stringa semplice. Restituisce `null` quando il valore non può essere decifrato.\n\nExample: Decifrare\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Stringa semplice\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nCifra un valore legato al browser della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La richiesta. |\n| `value` | `Object|String` | yes |  | Il valore. |\n| `key` | `String` | no |  | Chiave di cifratura. |\n| `strict` | `Boolean` | no | `false` | Lega anche all'indirizzo IP. |\n\nReturns: `String` Il token.\n\nSalva lo user agent (e con `strict` l'indirizzo IP) accanto a `value` e lo cifra con `ENCRYPT()`. `DECRYPTREQ()` restituisce il valore solo per una richiesta con lo stesso user agent (e indirizzo IP). `req` può essere una richiesta o un controller.\n\nExample: Cookie di accesso\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nDecifra un valore prodotto da ENCRYPTREQ() per lo stesso browser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | La richiesta. |\n| `value` | `String` | yes |  | Il token. |\n| `key` | `String` | no |  | La stessa chiave usata in `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nRestituisce il valore, oppure `undefined` quando non può essere decifrato o quando lo user agent (o l'indirizzo IP in modalità strict) è diverso da quello della richiesta.\n\nExample: In AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nIl segreto dell'app usato da ENCRYPT() e DECRYPT().\n\nReturns: `String`\n\nPer impostazione predefinita è un hash generato per l'app. Imposta un tuo valore in `/config` così i token restano validi quando l'app viene spostata su un altro server. Cambiarlo rende non validi tutti i token cifrati.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafRk81vh60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/encryption/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Šifrovanie","summary":"ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() a CONF.secret.","markdown":"---\ntitle: \"Šifrovanie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/encryption/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Šifrovanie\n\n> ENCRYPT(), DECRYPT(), ENCRYPTREQ(), DECRYPTREQ() a CONF.secret.\n\nFunkcie, ktoré šifrujú a dešifrujú hodnoty, a secret, ktorý používajú. Príručka [Šifrovanie](../../guides/encryption/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### ENCRYPT(value, [key], [isUnique])\n\nType: `method`\n\nZašifruje hodnotu pomocou CONF.secret a kľúča.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Number` | yes |  | Hodnota. |\n| `key` | `String` | no |  | Tvoj kľúč, kombinovaný s `CONF.secret`. |\n| `isUnique` | `Boolean` | no |  | Iný výstup pre rovnaký vstup. |\n\nReturns: `String` Zašifrovaná hodnota; pre `null` prázdny reťazec.\n\nObjekty sa serializujú do JSON, čísla na reťazce a funkcia sa zavolá, aby vrátila hodnotu. Výsledkom je reťazec, ktorý môžeš uložiť do cookie alebo URL. Keď je `CONF.default_crypto` nastavené na názov šifry Node.js, hodnota sa zašifruje touto šifrou, s `key` ako kľúčom šifry a s `CONF.default_crypto_iv`.\n\nExample: Zašifrovanie objektu\n```js\nvar token = ENCRYPT({ id: user.id, expire: NOW.add('1 day') }, 'reset');\n```\n\n### DECRYPT(value, [key], [jsonConvert])\n\nType: `method`\n\nDešifruje hodnotu z ENCRYPT().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Zašifrovaná hodnota. |\n| `key` | `String` | no |  | Rovnaký kľúč ako v `ENCRYPT()`. |\n| `jsonConvert` | `Boolean` | no | `true` | Parsovať výsledok ako JSON. |\n\nReturns: `Object|String|null`\n\nPredvolene sa výsledok parsuje ako JSON a keď to nie je JSON, vráti sa `null`, preto pre obyčajný reťazec odovzdaj `false` ako `jsonConvert`. Vráti `null`, keď sa hodnota nedá dešifrovať.\n\nExample: Dešifrovanie\n```js\nvar data = DECRYPT(self.query.token, 'reset');\nif (!data || data.expire < NOW)\n\treturn self.invalid('error-token');\n```\n\nExample: Obyčajný reťazec\n```js\nvar id = DECRYPT(value, 'key', false);\n```\n\n### ENCRYPTREQ(req, value, [key], [strict])\n\nType: `method`\n\nZašifruje hodnotu viazanú na prehliadač požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | Požiadavka. |\n| `value` | `Object|String` | yes |  | Hodnota. |\n| `key` | `String` | no |  | Šifrovací kľúč. |\n| `strict` | `Boolean` | no | `false` | Viazať aj na IP adresu. |\n\nReturns: `String` Token.\n\nUloží user agenta (a so `strict` aj IP adresu) vedľa `value` a zašifruje to pomocou `ENCRYPT()`. `DECRYPTREQ()` vráti hodnotu len pre požiadavku s rovnakým user agentom (a IP adresou). `req` môže byť požiadavka alebo kontrolér.\n\nExample: Prihlasovacia cookie\n```js\nself.cookie('token', ENCRYPTREQ(self, user.id, 'auth'), '1 month');\n```\n\n### DECRYPTREQ(req, value, [key])\n\nType: `method`\n\nDešifruje hodnotu z ENCRYPTREQ() pre ten istý prehliadač.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request|Controller` | yes |  | Požiadavka. |\n| `value` | `String` | yes |  | Token. |\n| `key` | `String` | no |  | Rovnaký kľúč ako v `ENCRYPTREQ()`. |\n\nReturns: `Object|String|undefined`\n\nVráti hodnotu, alebo `undefined`, keď sa nedá dešifrovať alebo keď sa user agent (alebo v striktnom režime IP adresa) líši od požiadavky.\n\nExample: V AUTH()\n```js\nvar id = DECRYPTREQ($.req, $.cookie('token'), 'auth');\n```\n\n### secret : your-secret\n\nType: `config`\n\nTajný kľúč aplikácie, ktorý používajú ENCRYPT() a DECRYPT().\n\nReturns: `String`\n\nPredvolene je to hash vygenerovaný pre aplikáciu. Nastav vlastnú hodnotu v `/config`, aby tokeny zostali platné, keď sa aplikácia presunie na iný server. Jeho zmena zneplatní všetky zašifrované tokeny.\n\nExample: config\n```js\n// /config\nsecret : a-long-random-secret\n```\n","entries":[{"type":"method","name":"ENCRYPT()","signature":"ENCRYPT(value, [key], [isUnique])","since":"","deprecated":false},{"type":"method","name":"DECRYPT()","signature":"DECRYPT(value, [key], [jsonConvert])","since":"","deprecated":false},{"type":"method","name":"ENCRYPTREQ()","signature":"ENCRYPTREQ(req, value, [key], [strict])","since":"","deprecated":false},{"type":"method","name":"DECRYPTREQ()","signature":"DECRYPTREQ(req, value, [key])","since":"","deprecated":false},{"type":"config","name":"CONF.secret","signature":"secret : your-secret","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions and the $ object of a middleware.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nRegisters, replaces or removes a named middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name used in route flags (`#name`) and in `USE()`. |\n| `fn` | `Function($)` | yes |  | The middleware, or `null` to remove it. |\n| `types` | `String|String[]` | yes |  | Assigns the middleware globally to these request types. |\n| `first` | `Boolean` | yes |  | With `types`, puts the middleware before the others. |\n\n`fn` receives one argument, `$` (`MiddlewareOptions`). It must call `$.next()`, call `$.cancel()`, or respond with `$.res`; otherwise the request waits until its timeout. A middleware that is not registered but assigned to a route is skipped and logged as `Middleware not found`.\n\nWith `types`, the middleware is also assigned globally by calling `USE(name, '', types, first)`. Use a type name or an array: `web`, `file`, `websocket`, `all`.\n\n`fn = null` removes the middleware and removes its name from all routes and global lists. `NEWMIDDLEWARE()` is the same function. Middleware registered by a plugin or another owner is removed when that owner is unloaded.\n\nExample: Check an API key\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Register and assign to all static files\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Remove\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nAssigns middleware to all requests, to one type of request, or to routes under a URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Middleware name(s), or a function. |\n| `url` | `String|String[]` | yes |  | A URL prefix. An array here is taken as `types`. |\n| `types` | `String|String[]` | yes |  | Request types: `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Puts the middleware before the middleware already assigned. |\n\n`USE()` runs after the application is loaded, so it sees the routes from all controllers.\n\n- Without `url` and `types`, or with the type `all` or `*`, the middleware runs for every request, static files included, before the routing. `$.controller` is not set there.\n- With `types` only, it runs for every request of those types. `web` (also `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) means dynamic routes; `file` (also `files`, `static`) means static files and file routes; `websocket` (also `socket`, `sockets`, `websockets`, `ws`, `wss`) means WebSocket routes.\n- With `url` and `types`, it is added to each existing route of those types whose URL starts with `url`. A `url` of `*` means no URL.\n\n`name` can be a string with several names separated by commas or spaces (a leading `#` or `&` is ignored), an array of names, or a function, which is registered as a middleware with a generated name. A name that is already in a list is not added twice.\n\nExample: Every request\n```js\nUSE('poweredby');\n```\n\nExample: Only dynamic routes under /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: An anonymous middleware for WebSocket routes\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nThe argument of every middleware function.\n\nA new instance is created for each chain of middleware of a request. Besides the methods below, it has these read-only shortcuts:\n\n| Property | Value |\n| --- | --- |\n| `$.req`, `$.res` | The request and the response (for WebSocket routes, `$.res` is the WebSocket client) |\n| `$.user`, `$.session`, `$.sessionid` | The user and session set by authorization |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Request data |\n| `$.url`, `$.path`, `$.split` | The URL and its parts |\n| `$.query`, `$.body`, `$.files` | Query string, parsed body and uploaded files |\n| `$.params`, `$.id` | Route parameters and the controller ID (only when `$.controller` exists) |\n| `$.controller` | The controller, in middleware of dynamic routes |\n| `$.options` | The options object of the route |\n| `$.middleware` | The list of names in the current chain |\n\nExample: Read request data\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nContinues with the next middleware, or with the action when this was the last one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` to stop, or an error to respond with 500. |\n\n- No argument: continue.\n- `false`: stop the chain; the action is not run.\n- An `Error` or an `ErrorBuilder`: respond with an error 500 and stop.\n\nIf the response was already sent, the chain stops by itself.\n\nExample: Stop with an error\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nStops the chain of middleware without running the action.\n\nReturns: `MiddlewareOptions`\n\nThe same as `$.next(false)`. Use it after you have sent a response yourself. Returns `$`.\n\nExample: Answer and stop\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nContinues the chain; the same as `$.next()` without an argument.\n\nReturns: `MiddlewareOptions`\n\nReturns `$`.\n\nExample: Continue\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nThe options object from the flags of the route.\n\nReturns: `Object`\n\nAn object in the flags array of `ROUTE()` or a file route becomes `$.options` in all middleware of that route. For global middleware it is an empty object.\n\nExample: One middleware, different settings\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nThe controller of the request, in middleware of dynamic routes.\n\nReturns: `Controller`\n\nIt is set for middleware of a route and for middleware assigned with `USE(name, ...['web'])`. In global middleware of all requests, static files and file routes it is `undefined`. `$.params` and `$.id` read from it.\n\nExample: Use the controller\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nReturns the absolute path to a file in the middleware directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is set by `directory_middleware`.\n\nExample: Path\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nThe directory with middleware files. Default `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nEach `.js` file is loaded at startup and its `exports.install()` is called. Register the middleware there with `MIDDLEWARE()`.\n\nExample: A middleware file\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions und das Objekt $ einer Middleware.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions und das Objekt $ einer Middleware.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nRegistriert, ersetzt oder entfernt eine benannte Middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name, der in Routen-Flags (`#name`) und in `USE()` verwendet wird. |\n| `fn` | `Function($)` | yes |  | Die Middleware oder `null`, um sie zu entfernen. |\n| `types` | `String|String[]` | yes |  | Weist die Middleware global diesen Request-Typen zu. |\n| `first` | `Boolean` | yes |  | Stellt die Middleware mit `types` vor die anderen. |\n\n`fn` erhält ein Argument, `$` (`MiddlewareOptions`). Sie muss `$.next()` oder `$.cancel()` aufrufen oder mit `$.res` antworten; sonst wartet der Request bis zu seinem Timeout. Eine Middleware, die nicht registriert, aber einer Route zugewiesen ist, wird übersprungen und als `Middleware not found` protokolliert.\n\nMit `types` wird die Middleware zusätzlich global zugewiesen, indem `USE(name, '', types, first)` aufgerufen wird. Verwende einen Typnamen oder ein Array: `web`, `file`, `websocket`, `all`.\n\n`fn = null` entfernt die Middleware und entfernt ihren Namen aus allen Routen und globalen Listen. `NEWMIDDLEWARE()` ist dieselbe Funktion. Middleware, die von einem Plugin oder einem anderen Eigentümer registriert wurde, wird entfernt, wenn dieser Eigentümer entladen wird.\n\nExample: Einen API-Schlüssel prüfen\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Registrieren und allen statischen Dateien zuweisen\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Entfernen\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nWeist Middleware allen Requests, einer Art von Request oder den Routen unter einer URL zu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Name(n) der Middleware oder eine Funktion. |\n| `url` | `String|String[]` | yes |  | Ein URL-Präfix. Ein Array an dieser Stelle wird als `types` verwendet. |\n| `types` | `String|String[]` | yes |  | Request-Typen: `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Stellt die Middleware vor die bereits zugewiesene Middleware. |\n\n`USE()` läuft, nachdem die Anwendung geladen ist, und sieht deshalb die Routen aus allen Controllern.\n\n- Ohne `url` und `types` oder mit dem Typ `all` oder `*` läuft die Middleware für jeden Request, statische Dateien eingeschlossen, noch vor dem Routing. `$.controller` ist dort nicht gesetzt.\n- Nur mit `types` läuft sie für jeden Request dieser Typen. `web` (auch `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) bedeutet dynamische Routen; `file` (auch `files`, `static`) bedeutet statische Dateien und Datei-Routen; `websocket` (auch `socket`, `sockets`, `websockets`, `ws`, `wss`) bedeutet WebSocket-Routen.\n- Mit `url` und `types` wird sie jeder existierenden Route dieser Typen hinzugefügt, deren URL mit `url` beginnt. Eine `url` mit dem Wert `*` bedeutet keine URL.\n\n`name` kann ein String mit mehreren Namen sein, getrennt durch Kommas oder Leerzeichen (ein führendes `#` oder `&` wird ignoriert), ein Array von Namen oder eine Funktion, die als Middleware mit einem generierten Namen registriert wird. Ein Name, der bereits in einer Liste steht, wird nicht doppelt hinzugefügt.\n\nExample: Jeder Request\n```js\nUSE('poweredby');\n```\n\nExample: Nur dynamische Routen unter /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: Eine anonyme Middleware für WebSocket-Routen\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nDas Argument jeder Middleware-Funktion.\n\nFür jede Kette von Middleware eines Requests wird eine neue Instanz erstellt. Neben den Methoden unten hat sie diese schreibgeschützten Kurzformen:\n\n| Eigenschaft | Wert |\n| --- | --- |\n| `$.req`, `$.res` | Der Request und die Response (bei WebSocket-Routen ist `$.res` der WebSocket-Client) |\n| `$.user`, `$.session`, `$.sessionid` | Der Benutzer und die Session, die von der Autorisierung gesetzt wurden |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Daten des Requests |\n| `$.url`, `$.path`, `$.split` | Die URL und ihre Teile |\n| `$.query`, `$.body`, `$.files` | Query-String, geparster Body und hochgeladene Dateien |\n| `$.params`, `$.id` | Routenparameter und die Controller-ID (nur wenn `$.controller` existiert) |\n| `$.controller` | Der Controller, in Middleware dynamischer Routen |\n| `$.options` | Das Options-Objekt der Route |\n| `$.middleware` | Die Liste der Namen in der aktuellen Kette |\n\nExample: Daten des Requests lesen\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nFährt mit der nächsten Middleware fort oder mit der Action, wenn dies die letzte war.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` zum Beenden oder ein Fehler, um mit 500 zu antworten. |\n\n- Kein Argument: fortfahren.\n- `false`: die Kette beenden; die Action wird nicht ausgeführt.\n- Ein `Error` oder ein `ErrorBuilder`: mit einem Fehler 500 antworten und beenden.\n\nWenn die Response bereits gesendet wurde, endet die Kette von selbst.\n\nExample: Mit einem Fehler beenden\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nBeendet die Kette von Middleware, ohne die Action auszuführen.\n\nReturns: `MiddlewareOptions`\n\nDasselbe wie `$.next(false)`. Verwende es, nachdem du selbst eine Response gesendet hast. Gibt `$` zurück.\n\nExample: Antworten und beenden\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nSetzt die Kette fort; dasselbe wie `$.next()` ohne Argument.\n\nReturns: `MiddlewareOptions`\n\nGibt `$` zurück.\n\nExample: Fortfahren\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nDas Options-Objekt aus den Flags der Route.\n\nReturns: `Object`\n\nEin Objekt im Flags-Array von `ROUTE()` oder einer Datei-Route wird in jeder Middleware dieser Route zu `$.options`. Bei globaler Middleware ist es ein leeres Objekt.\n\nExample: Eine Middleware, verschiedene Einstellungen\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nDer Controller des Requests, in Middleware dynamischer Routen.\n\nReturns: `Controller`\n\nEr ist für Middleware einer Route gesetzt und für Middleware, die mit `USE(name, ...['web'])` zugewiesen wurde. In globaler Middleware aller Requests, statischer Dateien und Datei-Routen ist er `undefined`. `$.params` und `$.id` lesen aus ihm.\n\nExample: Den Controller verwenden\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nGibt den absoluten Pfad zu einer Datei im Middleware-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis wird durch `directory_middleware` festgelegt.\n\nExample: Pfad\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nDas Verzeichnis mit Middleware-Dateien. Standard `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nJede `.js`-Datei wird beim Start geladen und ihr `exports.install()` aufgerufen. Registriere die Middleware dort mit `MIDDLEWARE()`.\n\nExample: Eine Middleware-Datei\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions y el objeto $ del middleware.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions y el objeto $ del middleware.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nRegistra, reemplaza o elimina un middleware con nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre usado en los flags de ruta (`#name`) y en `USE()`. |\n| `fn` | `Function($)` | yes |  | El middleware, o `null` para eliminarlo. |\n| `types` | `String|String[]` | yes |  | Asigna el middleware globalmente a estos tipos de petición. |\n| `first` | `Boolean` | yes |  | Con `types`, coloca el middleware antes que los demás. |\n\n`fn` recibe un argumento, `$` (`MiddlewareOptions`). Debe llamar a `$.next()`, llamar a `$.cancel()` o responder con `$.res`; si no, la petición espera hasta agotar su tiempo. Un middleware que no está registrado pero sí asignado a una ruta se omite y se registra como `Middleware not found`.\n\nCon `types`, el middleware también se asigna globalmente llamando a `USE(name, '', types, first)`. Usa un nombre de tipo o un array: `web`, `file`, `websocket`, `all`.\n\n`fn = null` elimina el middleware y quita su nombre de todas las rutas y listas globales. `NEWMIDDLEWARE()` es la misma función. Un middleware registrado por un plugin u otro propietario se elimina cuando ese propietario se descarga.\n\nExample: Comprobar una API key\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Registrar y asignar a todos los archivos estáticos\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Eliminar\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nAsigna middleware a todas las peticiones, a un tipo de petición o a las rutas bajo una URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Nombre(s) de middleware, o una función. |\n| `url` | `String|String[]` | yes |  | Un prefijo de URL. Un array aquí se toma como `types`. |\n| `types` | `String|String[]` | yes |  | Tipos de petición: `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Coloca el middleware antes del middleware ya asignado. |\n\n`USE()` se ejecuta después de cargar la aplicación, así que ve las rutas de todos los controladores.\n\n- Sin `url` ni `types`, o con el tipo `all` o `*`, el middleware se ejecuta en todas las peticiones, incluidos los archivos estáticos, antes del enrutamiento. Ahí `$.controller` no está definido.\n- Solo con `types`, se ejecuta en todas las peticiones de esos tipos. `web` (también `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) significa rutas dinámicas; `file` (también `files`, `static`) significa archivos estáticos y rutas de archivo; `websocket` (también `socket`, `sockets`, `websockets`, `ws`, `wss`) significa rutas WebSocket.\n- Con `url` y `types`, se añade a cada ruta existente de esos tipos cuya URL empieza por `url`. Una `url` igual a `*` significa ninguna URL.\n\n`name` puede ser una cadena con varios nombres separados por comas o espacios (se ignora un `#` o `&` inicial), un array de nombres, o una función, que se registra como middleware con un nombre generado. Un nombre que ya está en una lista no se añade dos veces.\n\nExample: Todas las peticiones\n```js\nUSE('poweredby');\n```\n\nExample: Solo rutas dinámicas bajo /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: Un middleware anónimo para rutas WebSocket\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nEl argumento de toda función de middleware.\n\nSe crea una nueva instancia para cada cadena de middleware de una petición. Además de los métodos de abajo, tiene estos atajos de solo lectura:\n\n| Propiedad | Valor |\n| --- | --- |\n| `$.req`, `$.res` | La petición y la respuesta (en las rutas WebSocket, `$.res` es el cliente WebSocket) |\n| `$.user`, `$.session`, `$.sessionid` | El usuario y la sesión asignados por la autorización |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Datos de la petición |\n| `$.url`, `$.path`, `$.split` | La URL y sus partes |\n| `$.query`, `$.body`, `$.files` | Query string, cuerpo analizado y archivos subidos |\n| `$.params`, `$.id` | Parámetros de la ruta y el ID del controlador (solo cuando existe `$.controller`) |\n| `$.controller` | El controlador, en el middleware de rutas dinámicas |\n| `$.options` | El objeto de opciones de la ruta |\n| `$.middleware` | La lista de nombres de la cadena actual |\n\nExample: Leer datos de la petición\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nContinúa con el siguiente middleware, o con la acción si este era el último.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` para detener, o un error para responder con 500. |\n\n- Sin argumento: continúa.\n- `false`: detiene la cadena; la acción no se ejecuta.\n- Un `Error` o un `ErrorBuilder`: responde con un error 500 y se detiene.\n\nSi la respuesta ya se envió, la cadena se detiene por sí sola.\n\nExample: Detener con un error\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nDetiene la cadena de middleware sin ejecutar la acción.\n\nReturns: `MiddlewareOptions`\n\nLo mismo que `$.next(false)`. Úsalo después de haber enviado tú mismo una respuesta. Devuelve `$`.\n\nExample: Responder y detener\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nContinúa la cadena; lo mismo que `$.next()` sin argumento.\n\nReturns: `MiddlewareOptions`\n\nDevuelve `$`.\n\nExample: Continuar\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nEl objeto de opciones de los flags de la ruta.\n\nReturns: `Object`\n\nUn objeto en el array de flags de `ROUTE()` o de una ruta de archivo se convierte en `$.options` en todo el middleware de esa ruta. En el middleware global es un objeto vacío.\n\nExample: Un middleware, distintos ajustes\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nEl controlador de la petición, en el middleware de rutas dinámicas.\n\nReturns: `Controller`\n\nEstá definido en el middleware de una ruta y en el middleware asignado con `USE(name, ...['web'])`. En el middleware global de todas las peticiones, de archivos estáticos y de rutas de archivo es `undefined`. `$.params` y `$.id` se leen de él.\n\nExample: Usar el controlador\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nDevuelve la ruta absoluta de un archivo del directorio de middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio se define con `directory_middleware`.\n\nExample: Ruta\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nEl directorio con los archivos de middleware. Por defecto `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nCada archivo `.js` se carga al arrancar y se llama a su `exports.install()`. Registra ahí el middleware con `MIDDLEWARE()`.\n\nExample: Un archivo de middleware\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions et l'objet $ du middleware.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions et l'objet $ du middleware.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nEnregistre, remplace ou supprime un middleware nommé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom utilisé dans les flags de route (`#name`) et dans `USE()`. |\n| `fn` | `Function($)` | yes |  | Le middleware, ou `null` pour le supprimer. |\n| `types` | `String|String[]` | yes |  | Affecte globalement le middleware à ces types de requêtes. |\n| `first` | `Boolean` | yes |  | Avec `types`, place le middleware avant les autres. |\n\n`fn` reçoit un argument, `$` (`MiddlewareOptions`). Il doit appeler `$.next()`, appeler `$.cancel()` ou répondre avec `$.res` ; sinon, la requête attend jusqu'à l'expiration de son délai. Un middleware non enregistré mais affecté à une route est ignoré et journalisé avec `Middleware not found`.\n\nAvec `types`, le middleware est aussi affecté globalement en appelant `USE(name, '', types, first)`. Utilise un nom de type ou un tableau : `web`, `file`, `websocket`, `all`.\n\n`fn = null` supprime le middleware et retire son nom de toutes les routes et des listes globales. `NEWMIDDLEWARE()` est la même fonction. Un middleware enregistré par un plugin ou un autre propriétaire est supprimé quand ce propriétaire est déchargé.\n\nExample: Vérifier une clé d'API\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Enregistrer et affecter à tous les fichiers statiques\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Supprimer\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nAffecte un middleware à toutes les requêtes, à un type de requête ou aux routes sous une URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Nom(s) du middleware, ou une fonction. |\n| `url` | `String|String[]` | yes |  | Un préfixe d'URL. Un tableau à cet emplacement est pris comme `types`. |\n| `types` | `String|String[]` | yes |  | Types de requêtes : `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Place le middleware avant les middlewares déjà affectés. |\n\n`USE()` s'exécute une fois l'application chargée, il voit donc les routes de tous les contrôleurs.\n\n- Sans `url` ni `types`, ou avec le type `all` ou `*`, le middleware s'exécute pour chaque requête, fichiers statiques compris, avant le routage. `$.controller` n'y est pas défini.\n- Avec seulement `types`, il s'exécute pour chaque requête de ces types. `web` (ou `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) désigne les routes dynamiques ; `file` (ou `files`, `static`) les fichiers statiques et les routes de fichiers ; `websocket` (ou `socket`, `sockets`, `websockets`, `ws`, `wss`) les routes WebSocket.\n- Avec `url` et `types`, il est ajouté à chaque route existante de ces types dont l'URL commence par `url`. Une `url` valant `*` signifie aucune URL.\n\n`name` peut être une chaîne contenant plusieurs noms séparés par des virgules ou des espaces (un `#` ou un `&` initial est ignoré), un tableau de noms, ou une fonction, qui est enregistrée comme middleware avec un nom généré. Un nom déjà présent dans une liste n'est pas ajouté deux fois.\n\nExample: Chaque requête\n```js\nUSE('poweredby');\n```\n\nExample: Uniquement les routes dynamiques sous /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: Un middleware anonyme pour les routes WebSocket\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nL'argument de chaque fonction middleware.\n\nUne nouvelle instance est créée pour chaque chaîne de middlewares d'une requête. En plus des méthodes ci-dessous, elle possède ces raccourcis en lecture seule :\n\n| Propriété | Valeur |\n| --- | --- |\n| `$.req`, `$.res` | La requête et la réponse (pour les routes WebSocket, `$.res` est le client WebSocket) |\n| `$.user`, `$.session`, `$.sessionid` | L'utilisateur et la session définis par l'autorisation |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Données de la requête |\n| `$.url`, `$.path`, `$.split` | L'URL et ses parties |\n| `$.query`, `$.body`, `$.files` | Query string, corps analysé et fichiers envoyés |\n| `$.params`, `$.id` | Paramètres de la route et ID du contrôleur (uniquement quand `$.controller` existe) |\n| `$.controller` | Le contrôleur, dans le middleware des routes dynamiques |\n| `$.options` | L'objet d'options de la route |\n| `$.middleware` | La liste des noms de la chaîne courante |\n\nExample: Lire les données de la requête\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nPasse au middleware suivant, ou à l'action s'il s'agissait du dernier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` pour arrêter, ou une erreur pour répondre avec 500. |\n\n- Sans argument : continuer.\n- `false` : arrêter la chaîne ; l'action n'est pas exécutée.\n- Une `Error` ou un `ErrorBuilder` : répondre avec une erreur 500 et arrêter.\n\nSi la réponse a déjà été envoyée, la chaîne s'arrête d'elle-même.\n\nExample: Arrêter avec une erreur\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nArrête la chaîne de middlewares sans exécuter l'action.\n\nReturns: `MiddlewareOptions`\n\nÉquivaut à `$.next(false)`. Utilise-la après avoir envoyé toi-même une réponse. Renvoie `$`.\n\nExample: Répondre et arrêter\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nContinue la chaîne ; équivaut à `$.next()` sans argument.\n\nReturns: `MiddlewareOptions`\n\nRenvoie `$`.\n\nExample: Continuer\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nL'objet d'options issu des flags de la route.\n\nReturns: `Object`\n\nUn objet dans le tableau de flags de `ROUTE()` ou d'une route de fichier devient `$.options` dans tous les middlewares de cette route. Pour un middleware global, c'est un objet vide.\n\nExample: Un middleware, des réglages différents\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nLe contrôleur de la requête, dans le middleware des routes dynamiques.\n\nReturns: `Controller`\n\nIl est défini pour le middleware d'une route et pour le middleware affecté avec `USE(name, ...['web'])`. Dans le middleware global de toutes les requêtes, des fichiers statiques et des routes de fichiers, il vaut `undefined`. `$.params` et `$.id` le lisent.\n\nExample: Utiliser le contrôleur\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nRenvoie le chemin absolu d'un fichier du répertoire des middlewares.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est défini par `directory_middleware`.\n\nExample: Chemin\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nLe répertoire des fichiers de middleware. Par défaut `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nChaque fichier `.js` est chargé au démarrage et sa fonction `exports.install()` est appelée. Enregistres-y le middleware avec `MIDDLEWARE()`.\n\nExample: Un fichier de middleware\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions e l'oggetto $ del middleware.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions e l'oggetto $ del middleware.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nRegistra, sostituisce o rimuove un middleware con nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome usato nei flag delle route (`#name`) e in `USE()`. |\n| `fn` | `Function($)` | yes |  | Il middleware, oppure `null` per rimuoverlo. |\n| `types` | `String|String[]` | yes |  | Assegna il middleware globalmente a questi tipi di richiesta. |\n| `first` | `Boolean` | yes |  | Con `types`, mette il middleware prima degli altri. |\n\n`fn` riceve un argomento, `$` (`MiddlewareOptions`). Deve chiamare `$.next()`, chiamare `$.cancel()` oppure rispondere con `$.res`; altrimenti la richiesta resta in attesa fino al suo timeout. Un middleware non registrato ma assegnato a una route viene saltato e registrato nel log come `Middleware not found`.\n\nCon `types`, il middleware viene anche assegnato globalmente chiamando `USE(name, '', types, first)`. Usa il nome di un tipo o un array: `web`, `file`, `websocket`, `all`.\n\n`fn = null` rimuove il middleware e toglie il suo nome da tutte le route e dalle liste globali. `NEWMIDDLEWARE()` è la stessa funzione. Un middleware registrato da un plugin o da un altro proprietario viene rimosso quando quel proprietario viene scaricato.\n\nExample: Controllare una chiave API\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Registrare e assegnare a tutti i file statici\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Rimuovere\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nAssegna un middleware a tutte le richieste, a un tipo di richiesta o alle route sotto un URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Nome o nomi dei middleware, oppure una funzione. |\n| `url` | `String|String[]` | yes |  | Un prefisso di URL. Un array qui viene preso come `types`. |\n| `types` | `String|String[]` | yes |  | Tipi di richiesta: `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Mette il middleware prima dei middleware già assegnati. |\n\n`USE()` viene eseguito dopo il caricamento dell'applicazione, così vede le route di tutti i controller.\n\n- Senza `url` e `types`, o con il tipo `all` o `*`, il middleware viene eseguito per ogni richiesta, file statici inclusi, prima del routing. Lì `$.controller` non è impostato.\n- Con il solo `types`, viene eseguito per ogni richiesta di quei tipi. `web` (anche `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) indica le route dinamiche; `file` (anche `files`, `static`) indica i file statici e le route di file; `websocket` (anche `socket`, `sockets`, `websockets`, `ws`, `wss`) indica le route WebSocket.\n- Con `url` e `types`, viene aggiunto a ogni route esistente di quei tipi il cui URL inizia con `url`. Un `url` uguale a `*` significa nessun URL.\n\n`name` può essere una stringa con più nomi separati da virgole o spazi (un `#` o `&` iniziale viene ignorato), un array di nomi, oppure una funzione, che viene registrata come middleware con un nome generato. Un nome già presente in una lista non viene aggiunto due volte.\n\nExample: Ogni richiesta\n```js\nUSE('poweredby');\n```\n\nExample: Solo le route dinamiche sotto /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: Un middleware anonimo per le route WebSocket\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nL'argomento di ogni funzione middleware.\n\nViene creata una nuova istanza per ogni catena di middleware di una richiesta. Oltre ai metodi qui sotto, ha queste scorciatoie in sola lettura:\n\n| Proprietà | Valore |\n| --- | --- |\n| `$.req`, `$.res` | La richiesta e la risposta (per le route WebSocket, `$.res` è il client WebSocket) |\n| `$.user`, `$.session`, `$.sessionid` | L'utente e la sessione impostati dall'autorizzazione |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Dati della richiesta |\n| `$.url`, `$.path`, `$.split` | L'URL e le sue parti |\n| `$.query`, `$.body`, `$.files` | Query string, corpo analizzato e file caricati |\n| `$.params`, `$.id` | Parametri della route e ID del controller (solo quando `$.controller` esiste) |\n| `$.controller` | Il controller, nei middleware delle route dinamiche |\n| `$.options` | L'oggetto delle opzioni della route |\n| `$.middleware` | La lista dei nomi nella catena corrente |\n\nExample: Leggere i dati della richiesta\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nProsegue con il middleware successivo, oppure con l'azione se questo era l'ultimo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` per fermare, oppure un errore per rispondere con 500. |\n\n- Nessun argomento: prosegue.\n- `false`: ferma la catena; l'azione non viene eseguita.\n- Un `Error` o un `ErrorBuilder`: risponde con un errore 500 e si ferma.\n\nSe la risposta è già stata inviata, la catena si ferma da sola.\n\nExample: Fermarsi con un errore\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nFerma la catena di middleware senza eseguire l'azione.\n\nReturns: `MiddlewareOptions`\n\nEquivale a `$.next(false)`. Usalo dopo aver inviato tu stesso una risposta. Restituisce `$`.\n\nExample: Rispondere e fermarsi\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nProsegue la catena; equivale a `$.next()` senza argomenti.\n\nReturns: `MiddlewareOptions`\n\nRestituisce `$`.\n\nExample: Proseguire\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nL'oggetto delle opzioni dai flag della route.\n\nReturns: `Object`\n\nUn oggetto nell'array dei flag di `ROUTE()` o di una route di file diventa `$.options` in tutti i middleware di quella route. Per i middleware globali è un oggetto vuoto.\n\nExample: Un middleware, impostazioni diverse\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nIl controller della richiesta, nei middleware delle route dinamiche.\n\nReturns: `Controller`\n\nÈ impostato per i middleware di una route e per i middleware assegnati con `USE(name, ...['web'])`. Nei middleware globali di tutte le richieste, dei file statici e delle route di file è `undefined`. `$.params` e `$.id` leggono da esso.\n\nExample: Usare il controller\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nRestituisce il percorso assoluto di un file nella directory dei middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è impostata da `directory_middleware`.\n\nExample: Percorso\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nLa directory con i file dei middleware. Predefinita `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nOgni file `.js` viene caricato all'avvio e viene chiamato il suo `exports.install()`. Registra lì il middleware con `MIDDLEWARE()`.\n\nExample: Un file di middleware\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"Jafjlg1qX61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/middleware/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Middleware","summary":"MIDDLEWARE(), USE(), MiddlewareOptions a objekt $ middlewaru.","markdown":"---\ntitle: Middleware\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/middleware/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Middleware\n\n> MIDDLEWARE(), USE(), MiddlewareOptions a objekt $ middlewaru.\n\n## API\n\n### MIDDLEWARE(name, fn, [types], [first])\n\nType: `method`\n\nZaregistruje, nahradí alebo odstráni pomenovaný middleware.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov používaný vo flagoch trás (`#name`) a v `USE()`. |\n| `fn` | `Function($)` | yes |  | Middleware alebo `null` na jeho odstránenie. |\n| `types` | `String|String[]` | yes |  | Priradí middleware globálne týmto typom požiadaviek. |\n| `first` | `Boolean` | yes |  | S `types` zaradí middleware pred ostatné. |\n\n`fn` dostane jeden argument, `$` (`MiddlewareOptions`). Musí zavolať `$.next()`, zavolať `$.cancel()` alebo odpovedať cez `$.res`; inak požiadavka čaká až do vypršania časového limitu. Middleware, ktorý nie je zaregistrovaný, ale je priradený trase, sa preskočí a zaloguje ako `Middleware not found`.\n\nS `types` sa middleware priradí aj globálne zavolaním `USE(name, '', types, first)`. Použi názov typu alebo pole: `web`, `file`, `websocket`, `all`.\n\n`fn = null` odstráni middleware a odstráni jeho názov zo všetkých trás a globálnych zoznamov. `NEWMIDDLEWARE()` je tá istá funkcia. Middleware zaregistrovaný pluginom alebo iným vlastníkom sa odstráni, keď sa tento vlastník uvoľní.\n\nExample: Kontrola API kľúča\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n\nexports.install = function() {\n\tROUTE('GET /api/products/', products, ['#apikey']);\n};\n```\n\nExample: Registrácia a priradenie všetkým statickým súborom\n```js\nMIDDLEWARE('cors', function($) {\n\t$.res.setHeader('Access-Control-Allow-Origin', '*');\n\t$.next();\n}, ['file']);\n```\n\nExample: Odstránenie\n```js\nMIDDLEWARE('apikey', null);\n```\n\n### USE(name, [url], [types], [first])\n\nType: `method`\n\nPriradí middleware všetkým požiadavkám, jednému typu požiadaviek alebo trasám pod URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|String[]|Function` | yes |  | Názov (názvy) middlewaru alebo funkcia. |\n| `url` | `String|String[]` | yes |  | Prefix URL. Pole sa tu berie ako `types`. |\n| `types` | `String|String[]` | yes |  | Typy požiadaviek: `web`, `file`, `websocket`, `all`. |\n| `first` | `Boolean` | yes |  | Zaradí middleware pred už priradené middleware. |\n\n`USE()` sa spustí po načítaní aplikácie, takže vidí trasy zo všetkých kontrolérov.\n\n- Bez `url` a `types` alebo s typom `all` či `*` sa middleware spustí pre každú požiadavku, vrátane statických súborov, ešte pred smerovaním. `$.controller` tam nie je nastavený.\n- Len s `types` sa spustí pre každú požiadavku týchto typov. `web` (aj `route`, `routes`, `dynamic`, `http`, `https`, `api`, `schema`, `schemas`) znamená dynamické trasy; `file` (aj `files`, `static`) znamená statické súbory a súborové trasy; `websocket` (aj `socket`, `sockets`, `websockets`, `ws`, `wss`) znamená WebSocket trasy.\n- S `url` a `types` sa pridá ku každej existujúcej trase týchto typov, ktorej URL začína na `url`. `url` s hodnotou `*` znamená žiadnu URL.\n\n`name` môže byť reťazec s viacerými názvami oddelenými čiarkami alebo medzerami (úvodné `#` alebo `&` sa ignoruje), pole názvov alebo funkcia, ktorá sa zaregistruje ako middleware s vygenerovaným názvom. Názov, ktorý už v zozname je, sa nepridá druhýkrát.\n\nExample: Každá požiadavka\n```js\nUSE('poweredby');\n```\n\nExample: Len dynamické trasy pod /api/\n```js\nUSE('apikey', '/api/', ['web']);\n```\n\nExample: Anonymný middleware pre WebSocket trasy\n```js\nUSE(function($) {\n\tconsole.log('WebSocket', $.url);\n\t$.next();\n}, ['websocket']);\n```\n\n### $\n\nType: `class`\n\nArgument každej funkcie middlewaru.\n\nPre každý reťazec middlewarov požiadavky sa vytvorí nová inštancia. Okrem metód nižšie má tieto skratky len na čítanie:\n\n| Vlastnosť | Hodnota |\n| --- | --- |\n| `$.req`, `$.res` | Požiadavka a odpoveď (pri WebSocket trasách je `$.res` WebSocket klient) |\n| `$.user`, `$.session`, `$.sessionid` | Používateľ a relácia nastavené autorizáciou |\n| `$.headers`, `$.ip`, `$.ua`, `$.language` | Údaje požiadavky |\n| `$.url`, `$.path`, `$.split` | URL a jej časti |\n| `$.query`, `$.body`, `$.files` | Query string, sparsované telo a nahrané súbory |\n| `$.params`, `$.id` | Parametre trasy a ID kontroléra (len keď existuje `$.controller`) |\n| `$.controller` | Kontrolér, v middlewari dynamických trás |\n| `$.options` | Objekt možností trasy |\n| `$.middleware` | Zoznam názvov v aktuálnom reťazci |\n\nExample: Čítanie údajov požiadavky\n```js\nMIDDLEWARE('logger', function($) {\n\tconsole.log($.ip, $.url, $.ua);\n\t$.next();\n});\n```\n\n### $.next([err])\n\nType: `method`\n\nPokračuje ďalším middlewarom alebo akciou, keď bol tento posledný.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Boolean|Error|ErrorBuilder` | yes |  | `false` na zastavenie alebo chyba na odpoveď 500. |\n\n- Bez argumentu: pokračovať.\n- `false`: zastaviť reťazec; akcia sa nespustí.\n- `Error` alebo `ErrorBuilder`: odpovedať chybou 500 a zastaviť.\n\nAk už bola odpoveď odoslaná, reťazec sa zastaví sám.\n\nExample: Zastavenie s chybou\n```js\nMIDDLEWARE('maintenance', function($) {\n\tif (CONF.maintenance)\n\t\t$.next(new Error('Maintenance'));\n\telse\n\t\t$.next();\n});\n```\n\n### $.cancel()\n\nType: `method`\n\nZastaví reťazec middlewarov bez spustenia akcie.\n\nReturns: `MiddlewareOptions`\n\nTo isté ako `$.next(false)`. Použi ju, keď si odpoveď už poslal sám. Vráti `$`.\n\nExample: Odpovedať a zastaviť\n```js\nMIDDLEWARE('ping', function($) {\n\tif ($.url === '/ping/') {\n\t\t$.res.send(200, 'pong', 'text/plain');\n\t\t$.cancel();\n\t} else\n\t\t$.next();\n});\n```\n\n### $.callback()\n\nType: `method`\n\nPokračuje v reťazci; to isté ako `$.next()` bez argumentu.\n\nReturns: `MiddlewareOptions`\n\nVráti `$`.\n\nExample: Pokračovanie\n```js\nMIDDLEWARE('log', function($) {\n\tconsole.log($.url);\n\t$.callback();\n});\n```\n\n### $.options\n\nType: `property`\n\nObjekt možností z flagov trasy.\n\nReturns: `Object`\n\nObjekt v poli flagov `ROUTE()` alebo súborovej trasy sa stane `$.options` vo všetkých middlewaroch tejto trasy. Pre globálny middleware je to prázdny objekt.\n\nExample: Jeden middleware, rôzne nastavenia\n```js\nMIDDLEWARE('role', function($) {\n\tif ($.user && $.user.roles.includes($.options.role))\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n\nexports.install = function() {\n\tROUTE('GET /admin/', admin, ['#role', { role: 'admin' }]);\n\tROUTE('GET /editor/', editor, ['#role', { role: 'editor' }]);\n};\n```\n\n### $.controller\n\nType: `property`\n\nKontrolér požiadavky, v middlewari dynamických trás.\n\nReturns: `Controller`\n\nJe nastavený pre middleware trasy a pre middleware priradený pomocou `USE(name, ...['web'])`. V globálnom middlewari všetkých požiadaviek, statických súborov a súborových trás je `undefined`. `$.params` a `$.id` čítajú z neho.\n\nExample: Použitie kontroléra\n```js\nMIDDLEWARE('product', function($) {\n\tif ($.params.id)\n\t\t$.next();\n\telse\n\t\t$.controller.throw404();\n});\n```\n\n### PATH.middleware([filename])\n\nType: `method`\n\nVráti absolútnu cestu k súboru v priečinku middlewarov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nPriečinok nastavuje `directory_middleware`.\n\nExample: Cesta\n```js\nPATH.middleware('auth.js');\n```\n\n### directory_middleware\n\nType: `config`\n\nPriečinok so súbormi middlewarov. Predvolene `/middleware/`.\n\nReturns: `String` '/middleware/'\n\nKaždý súbor `.js` sa načíta pri štarte a zavolá sa jeho `exports.install()`. Tam zaregistruj middleware pomocou `MIDDLEWARE()`.\n\nExample: Súbor middlewaru\n```js\n// /middleware/auth.js\nexports.install = function() {\n\tMIDDLEWARE('auth', function($) {\n\t\tif ($.user)\n\t\t\t$.next();\n\t\telse\n\t\t\t$.res.throw401();\n\t});\n};\n```\n","entries":[{"type":"method","name":"MIDDLEWARE()","signature":"MIDDLEWARE(name, fn, [types], [first])","since":"","deprecated":false},{"type":"method","name":"USE()","signature":"USE(name, [url], [types], [first])","since":"","deprecated":false},{"type":"class","name":"MiddlewareOptions","signature":"$","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next([err])","since":"","deprecated":false},{"type":"method","name":"$.cancel()","signature":"$.cancel()","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback()","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"method","name":"PATH.middleware()","signature":"PATH.middleware([filename])","since":"","deprecated":false},{"type":"config","name":"directory_middleware","signature":"directory_middleware","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Static files","summary":"File routes, the response methods for files, and the helpers and config of static files.","markdown":"---\ntitle: Static files\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Static files\n\n> File routes, the response methods for files, and the helpers and config of static files.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nCreates a file route; `ROUTE('FILE /url/*.ext', action, [flags])` calls it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | The URL pattern, or a function `(req, res)` returning `true`. |\n| `action` | `Function(req, res)|String` | yes |  | The handler, a file name or a URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, an options object. |\n\nA file route handles requests for static files (paths that end with an extension) before the framework looks into `public/`. The first matching route wins; longer URLs are tested first.\n\nThe `url` forms:\n\n| URL | Matches |\n| --- | --- |\n| `/photos/*.jpg` | `.jpg` files under `/photos/` |\n| `/photos/*` or `/photos/*.*` | any file under `/photos/` |\n| `/favicon.ico` | exactly this file |\n\n`action` is `function(req, res)`. It can also be a string: an absolute file name to send with `res.file()`, or an `http://`/`https://` URL whose response is streamed. Instead of a URL you can pass a function `function(req, res)` that returns `true` for the requests to handle.\n\nFlags: `#name` adds middleware, `.ext` limits the extensions, `id:name` sets the route ID, and an object becomes `$.options` in middleware. For file routes, put middleware in the flags array, not inline in the URL. When the action does not answer itself, call `res.continue()` to serve the file from `public/`.\n\nExample: Protected downloads\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: A fixed file\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Validation function\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nSets a handler for static files that do not exist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | The handler. |\n\n`fn(req, res)` is called instead of the 404 response for static files that are missing, not allowed by `static_accepts`, or not found by `res.file()`. Return `true` when you answered the request; otherwise the framework responds with 404.\n\nExample: Placeholder image\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nSends a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | An absolute path. |\n| `download` | `String|Boolean` | yes |  | A download name, or `true` for the file name. |\n| `headers` | `Object` | yes |  | Additional headers. |\n| `callback` | `Function` | yes |  | Called when the file is sent. |\n\nReturns: `Response`\n\n`filename` is an absolute path; a leading `@` means a file of a package. The content type comes from the extension of the request (or of the file). The file gets the same caching, GZIP compression, `Range` support and `304 Not Modified` handling as files in `public/`. `.html` files are localized when `allow_localize` is on.\n\n`download` adds `Content-Disposition: attachment` with this file name; `true` uses the name of the file. In release mode the framework remembers the file of each URL; call `TOUCH(url)` when it changes.\n\nExample: Download\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nProcesses an image with GraphicsMagick or ImageMagick and sends the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The source image. |\n| `make` | `Function(image, res)` | yes |  | Sets the image operations. |\n| `headers` | `Object` | yes |  | Additional headers. |\n| `callback` | `Function` | yes |  | Called when the image is sent. |\n| `persistent` | `Boolean` | yes |  | Stores the result as a persistent file. |\n\nReturns: `Response`\n\n`filename` is an absolute path or a readable stream. `make(image, res)` gets an image object and sets the operations (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). The result is stored in `/tmp/` under the URL of the request and later requests get the stored file.\n\n`persistent` stores the result as a persistent file (`timg_` prefix in `/tmp/`) and reuses it while it exists; when omitted, it follows `allow_persistent_images` (default `true`). `res.image_nocache(filename, make, [headers], [callback])` does the same without the cache.\n\nExample: Thumbnails\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nSends a file from a FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The FileStorage name. |\n| `id` | `String|Number` | yes |  | The file ID. |\n| `download` | `String` | yes |  | A download name. |\n| `headers` | `Object` | yes |  | Additional headers. |\n| `callback` | `Function` | yes |  | Called when done. |\n| `checkmeta` | `Function(meta)` | yes |  | Checks the metadata of the file. |\n\nReturns: `Response`\n\nReads the file `id` from `FILESTORAGE(name)` and sends it with its stored content type. `checkmeta(meta)` can inspect the metadata of the file before it is sent.\n\nExample: Files from storage\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nProcesses an image from a FileStorage and sends the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The FileStorage name. |\n| `id` | `String|Number` | yes |  | The file ID. |\n| `make` | `Function(image, res)` | yes |  | Sets the image operations. |\n| `headers` | `Object` | yes |  | Additional headers. |\n| `callback` | `Function` | yes |  | Called when done. |\n| `checkmeta` | `Function(meta)` | yes |  | Checks the metadata of the file. |\n\nReturns: `Response`\n\nLike `res.filefs()`, but `make(image, res)` sets image operations as in `res.image()`.\n\nExample: Avatars from storage\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nSends a readable stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The content type. |\n| `stream` | `Stream` | yes |  | A readable stream. |\n| `download` | `String` | yes |  | A download name. |\n| `headers` | `Object` | yes |  | Additional headers. |\n| `callback` | `Function` | yes |  | Called when done. |\n| `nocompress` | `Boolean` | yes |  | Disables compression. |\n\nReturns: `Response`\n\nThe stream is compressed with GZIP when the content type can be compressed and the client accepts it, unless `nocompress` is `true`.\n\nExample: Stream a file\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nServes the requested static file from the public directory, as without a file route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Called when the file is sent. |\n\nReturns: `Response`\n\nUse it in a file route or a middleware that decides not to answer the request itself. The extension must be in `static_accepts`; otherwise, and when the file does not exist, the response is 404 (or the `FILE404()` handler). It also applies `MAP()`, `MERGE()` and `RESIZE()`.\n\nExample: Serve only to signed-in users\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nServes a generated file from `/tmp/`, or asks you to create it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Creates the missing file. |\n\nThe file name in `/tmp/` is built from the URL of the request. When the file exists, it is sent and `callback` is not called. Otherwise `callback(next, filename, req, res)` is called: write the file to `filename`, send the response (for example `res.file(filename)`), and call `next()`. At most 20 files are generated at the same time.\n\nExample: Generated file\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nThe extension of a static-file request, without the dot.\n\nReturns: `String`\n\nSet for requests whose path ends with an extension (`req.isStaticFile` is `true`).\n\nExample: Branch by extension\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nServes static files through the translator, or sets the language of requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | The URL pattern, or the language function. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` and route flags such as `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifies HTML. Default `true`. |\n\n`LOCALIZE(url)` creates a file route that reads the files under `url` from `public/`, replaces `@(Text)` markers with translations in the request language, and caches the result per language in release mode. HTML is minified when `allow_compile_html` is on; the flag `nocompress` or `minify = false` turns it off.\n\nThe URL can end with a file pattern such as `/templates/*.html`. Without an extension, `.html`, `.htm`, `.md` and `.txt` files are handled; `.ext` flags choose others. A URL starting with `#` is a sitemap ID.\n\n`LOCALIZE(fn)` sets the function `fn(req, res, isStaticFile)` that returns the language of a request. Static `.html` and `.htm` files from `public/` are localized automatically when `allow_localize` is on.\n\nExample: Language and files\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nCreates resized images on the fly for a URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | A URL path, optionally with `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Sets the image operations. |\n| `flags` | `String[]` | yes |  | Source path or URL, `.ext`, `nocache`. |\n\nRequests for images under `url` are made from the source images by `fn(image)` and cached in `/tmp/`. By default the source is the same path in `public/`. In `flags`, a path (`/img/`, or `~/absolute/path/`) or an `http(s)://` URL sets where the source images are, `.ext` adds an extension, and `nocache` disables the cache. JPG, JPEG, PNG, GIF, APNG, HEIF and HEIC are always handled.\n\nExample: Small images from /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nServes a URL from another file or directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL. |\n| `filename` | `String` | yes |  | A file or a directory. |\n| `filter` | `String[]|Function` | yes |  | Filters the files of a directory. |\n\nWhen `filename` has an extension, the URL is mapped to that file. Otherwise it is a directory and every file inside is mapped under `url`; `filter` is an array of extensions or a function `(filename)` that returns `true` for the files to map.\n\nA relative `filename` is looked up in `public/` first. Prefixes: `~` for a path from the application root, `@` for a package, `=` for a theme. A `url` starting with `#` is a sitemap ID. The mapped file is still served only when its extension is allowed.\n\nExample: File and directory\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nServes several files as one file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of the merged file. |\n| `file1` | `String|String[]` | yes |  | Files to merge, in order. |\n\nThe files are joined into one file stored in `/tmp/`. Each argument can be a file name, a URL or an array. A file name with `@` is from a package, with `=` from a theme. The `url` follows the `/versions` file.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nAllows an extension for static files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | An extension, with or without the dot. |\n| `type` | `String` | yes |  | The content type. |\n\nAdds the extension to `static_accepts`. With `type`, it also sets the content type of the extension.\n\nExample: 3D models\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nClears the cache of processed static files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | A URL such as `/css/default.css`. |\n\nThe framework remembers each processed file (minified, compressed or not found) by its URL. `TOUCH(url)` forgets one URL, so the next request reads the file again; `TOUCH()` forgets all.\n\nExample: After a change\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nReturns the absolute path to a file in the public directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | A relative file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is set by `directory_public`.\n\nExample: Path\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nReturns the URL of a static file, with `static_url` and the `/versions` file applied.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A file name. |\n| `theme` | `String` | yes |  | A theme name. |\n\nReturns: `String` A URL.\n\nRelative names get the prefix of the helper: `F.public()` uses `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` and `F.public_download()` `static_url_download`. Names starting with `/` get no prefix. A name starting with `~` ignores the theme, `=theme/` selects a theme (`=?/` the default theme). With `default_root`, the root is added. Views use the same helpers.\n\nExample: URLs\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nReturns the URL of a script, with `static_url_script` as the prefix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A file name. |\n| `theme` | `String` | yes |  | A theme name. |\n\nReturns: `String` A URL.\n\nSee `F.public()` for the rules.\n\nExample: Script\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nReturns the URL of a stylesheet, with `static_url_style` as the prefix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A file name. |\n| `theme` | `String` | yes |  | A theme name. |\n\nReturns: `String` A URL.\n\nSee `F.public()` for the rules.\n\nExample: Stylesheet\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nReturns the URL of an image, with `static_url_image` as the prefix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A file name. |\n| `theme` | `String` | yes |  | A theme name. |\n\nReturns: `String` A URL.\n\nSee `F.public()` for the rules.\n\nExample: Image\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nThe directory with static files. Default `/public/`.\n\nReturns: `String` '/public/'\n\nStatic-file requests are looked up here. `PATH.public()` builds paths into it.\n\nExample: Config file\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nThe prefix of URLs made by `F.public()`. Default empty.\n\nReturns: `String` ''\n\nThe other prefixes are `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) and `static_url_download` (`/download/`). They change only the generated URLs; files are still served from their path in `public/`. A prefix can be a full URL, for example of a CDN.\n\nExample: Config file\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nThe prefix of URLs made by `F.public_js()`. Default `/js/`.\n\nReturns: `String` '/js/'\n\nSee `static_url`.\n\nExample: Config file\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nThe extensions that static files may have.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nStatic files with other extensions answer 404. The default list: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nIn the config file, `static_accepts` **replaces** the list, while `static_accepts_custom` adds extensions to it. Both take a comma-separated list. In code, use `ACCEPT()`.\n\nExample: Config file\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nTurns handling of static files on or off. Default `true`.\n\nReturns: `Boolean` true\n\nWhen `false`, paths with an extension are routed as normal requests and the public directory is not served.\n\nExample: Config file\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nCompresses static files with GZIP. Default `true`.\n\nReturns: `Boolean` true\n\nApplies to text types: plain text, HTML, CSS, JavaScript, JSX, JSON, XML, SVG and Markdown, when the client sends `Accept-Encoding: gzip`. The compressed copy is stored in `/tmp/`.\n\nExample: Config file\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifies static JavaScript, CSS and HTML. Default `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript and `.mjs`), `allow_compile_style` (CSS) and `allow_compile_html` (localized HTML) switch single types; all default to `true`. Files named like `*.min.js`, `*-min.css` or `*.min@version.js` are not minified. In CSS, `url()` values follow the `/versions` file.\n\nExample: Config file\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLocalizes static `.html` and `.htm` files. Default `true`.\n\nReturns: `Boolean` true\n\nThe `@(Text)` markers in HTML files from `public/` are translated to the request language set with `LOCALIZE(fn)`.\n\nExample: Config file\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nStores images made by `res.image()` as persistent files. Default `true`.\n\nReturns: `Boolean` true\n\nThe default for the `persistent` argument of `res.image()`.\n\nExample: Config file\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nA value added to the `ETag` of static files.\n\nReturns: `String` ''\n\nWhen empty, it is set from `version` (without dots and spaces) at startup. Change `version` or `etag_version` to make browsers download changed files again.\n\nExample: Config file\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nA URL prefix when the application runs under a sub-path.\n\nReturns: `String` ''\n\nWith `default_root : /app/`, static URLs made by `F.public()` and the views start with `/app/`, and the `/versions` file is applied with this prefix.\n\nExample: Config file\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nThe `/versions` file in the root of the application maps file URLs to versioned URLs.\n\nReturns: `File`\n\nEach line is `url : newurl`. The value `auto` adds a hash of the file content to the name at startup (`/js/app.js` becomes `/js/app-<hash>.js`). With `-->` instead of `:`, the new URL is also mapped to the original file. Lines starting with `#` or `// ` are comments. The helpers `F.public_*()`, `MERGE()` and views use the new URLs.\n\nExample: Config file\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nChanges the content of views, styles and scripts before they are compiled.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A path relative to the app, for example `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)` that returns the new content. |\n\nThe function is called with `(type, filename, value, controller)`, where `type` is `'view'`, `'style'`, `'script'` or `'static'` (a static file localized by Total.js) and `filename` is the path relative to the app with a leading `/`. Return the new content; a falsy result keeps it as it was.\n\nWith `filename` (for example `'/views/index.html'`) the function runs only for that file. The change is made in memory, the file on the disk stays as it is. In release mode compiled content is cached, so the function runs once per file. A function registered by a plugin or a module is removed when it is uninstalled.\n\nExample: Add a banner to every view\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: One file only\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Statische Dateien","summary":"Datei-Routen, die Response-Methoden für Dateien sowie die Helfer und die Konfiguration statischer Dateien.","markdown":"---\ntitle: Statische Dateien\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Statische Dateien\n\n> Datei-Routen, die Response-Methoden für Dateien sowie die Helfer und die Konfiguration statischer Dateien.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nErstellt eine Datei-Route; `ROUTE('FILE /url/*.ext', action, [flags])` ruft sie auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Das URL-Muster oder eine Funktion `(req, res)`, die `true` zurückgibt. |\n| `action` | `Function(req, res)|String` | yes |  | Der Handler, ein Dateiname oder eine URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, ein Options-Objekt. |\n\nEine Datei-Route behandelt Requests nach statischen Dateien (Pfade, die auf eine Endung enden), bevor das Framework in `public/` nachsieht. Die erste passende Route gewinnt; längere URLs werden zuerst geprüft.\n\nDie Formen von `url`:\n\n| URL | Passt zu |\n| --- | --- |\n| `/photos/*.jpg` | `.jpg`-Dateien unter `/photos/` |\n| `/photos/*` oder `/photos/*.*` | jeder Datei unter `/photos/` |\n| `/favicon.ico` | genau dieser Datei |\n\n`action` ist `function(req, res)`. Es kann auch ein String sein: ein absoluter Dateiname, der mit `res.file()` gesendet wird, oder eine URL `http://`/`https://`, deren Response gestreamt wird. Statt einer URL kannst du eine Funktion `function(req, res)` übergeben, die für die zu behandelnden Requests `true` zurückgibt.\n\nFlags: `#name` fügt Middleware hinzu, `.ext` beschränkt die Endungen, `id:name` setzt die ID der Route, und ein Objekt wird in der Middleware zu `$.options`. Bei Datei-Routen gehört Middleware in das Flags-Array, nicht inline in die URL. Wenn die Action nicht selbst antwortet, rufe `res.continue()` auf, um die Datei aus `public/` auszuliefern.\n\nExample: Geschützte Downloads\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: Eine feste Datei\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Prüffunktion\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nSetzt einen Handler für statische Dateien, die nicht existieren.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | Der Handler. |\n\n`fn(req, res)` wird statt der Response 404 für statische Dateien aufgerufen, die fehlen, von `static_accepts` nicht erlaubt sind oder von `res.file()` nicht gefunden werden. Gib `true` zurück, wenn du den Request beantwortet hast; andernfalls antwortet das Framework mit 404.\n\nExample: Platzhalterbild\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nSendet eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Ein absoluter Pfad. |\n| `download` | `String|Boolean` | yes |  | Ein Download-Name oder `true` für den Dateinamen. |\n| `headers` | `Object` | yes |  | Zusätzliche Header. |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn die Datei gesendet ist. |\n\nReturns: `Response`\n\n`filename` ist ein absoluter Pfad; ein führendes `@` bedeutet eine Datei eines Pakets. Der Content-Type ergibt sich aus der Endung des Requests (oder der Datei). Die Datei erhält dasselbe Caching, dieselbe GZIP-Komprimierung, dieselbe Unterstützung für `Range` und dieselbe Behandlung von `304 Not Modified` wie Dateien in `public/`. `.html`-Dateien werden lokalisiert, wenn `allow_localize` aktiv ist.\n\n`download` fügt `Content-Disposition: attachment` mit diesem Dateinamen hinzu; `true` verwendet den Namen der Datei. Im Release-Modus merkt sich das Framework die Datei jeder URL; rufe `TOUCH(url)` auf, wenn sie sich ändert.\n\nExample: Download\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nVerarbeitet ein Bild mit GraphicsMagick oder ImageMagick und sendet das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Das Quellbild. |\n| `make` | `Function(image, res)` | yes |  | Legt die Bildoperationen fest. |\n| `headers` | `Object` | yes |  | Zusätzliche Header. |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn das Bild gesendet ist. |\n| `persistent` | `Boolean` | yes |  | Speichert das Ergebnis als persistente Datei. |\n\nReturns: `Response`\n\n`filename` ist ein absoluter Pfad oder ein lesbarer Stream. `make(image, res)` erhält ein Bildobjekt und legt die Operationen fest (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). Das Ergebnis wird in `/tmp/` unter der URL des Requests gespeichert, und spätere Requests erhalten die gespeicherte Datei.\n\n`persistent` speichert das Ergebnis als persistente Datei (Präfix `timg_` in `/tmp/`) und verwendet sie wieder, solange sie existiert; ohne Angabe richtet es sich nach `allow_persistent_images` (Standard `true`). `res.image_nocache(filename, make, [headers], [callback])` tut dasselbe ohne Cache.\n\nExample: Vorschaubilder\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nSendet eine Datei aus einem FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des FileStorage. |\n| `id` | `String|Number` | yes |  | Die ID der Datei. |\n| `download` | `String` | yes |  | Ein Download-Name. |\n| `headers` | `Object` | yes |  | Zusätzliche Header. |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn alles erledigt ist. |\n| `checkmeta` | `Function(meta)` | yes |  | Prüft die Metadaten der Datei. |\n\nReturns: `Response`\n\nLiest die Datei `id` aus `FILESTORAGE(name)` und sendet sie mit ihrem gespeicherten Content-Type. `checkmeta(meta)` kann die Metadaten der Datei prüfen, bevor sie gesendet wird.\n\nExample: Dateien aus dem Speicher\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nVerarbeitet ein Bild aus einem FileStorage und sendet das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des FileStorage. |\n| `id` | `String|Number` | yes |  | Die ID der Datei. |\n| `make` | `Function(image, res)` | yes |  | Legt die Bildoperationen fest. |\n| `headers` | `Object` | yes |  | Zusätzliche Header. |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn alles erledigt ist. |\n| `checkmeta` | `Function(meta)` | yes |  | Prüft die Metadaten der Datei. |\n\nReturns: `Response`\n\nWie `res.filefs()`, aber `make(image, res)` legt Bildoperationen fest wie bei `res.image()`.\n\nExample: Avatare aus dem Speicher\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nSendet einen lesbaren Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Content-Type. |\n| `stream` | `Stream` | yes |  | Ein lesbarer Stream. |\n| `download` | `String` | yes |  | Ein Download-Name. |\n| `headers` | `Object` | yes |  | Zusätzliche Header. |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn alles erledigt ist. |\n| `nocompress` | `Boolean` | yes |  | Schaltet die Komprimierung ab. |\n\nReturns: `Response`\n\nDer Stream wird mit GZIP komprimiert, wenn sich der Content-Type komprimieren lässt und der Client es akzeptiert, außer `nocompress` ist `true`.\n\nExample: Eine Datei streamen\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nLiefert die angeforderte statische Datei aus dem Verzeichnis public aus, wie ohne Datei-Route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Wird aufgerufen, wenn die Datei gesendet ist. |\n\nReturns: `Response`\n\nVerwende es in einer Datei-Route oder einer Middleware, die den Request nicht selbst beantworten will. Die Endung muss in `static_accepts` stehen; andernfalls, und wenn die Datei nicht existiert, lautet die Response 404 (oder der Handler `FILE404()`). Es wendet auch `MAP()`, `MERGE()` und `RESIZE()` an.\n\nExample: Nur an angemeldete Benutzer ausliefern\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nLiefert eine generierte Datei aus `/tmp/` aus oder bittet dich, sie zu erstellen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Erstellt die fehlende Datei. |\n\nDer Dateiname in `/tmp/` wird aus der URL des Requests gebildet. Existiert die Datei, wird sie gesendet und `callback` nicht aufgerufen. Andernfalls wird `callback(next, filename, req, res)` aufgerufen: Schreibe die Datei nach `filename`, sende die Response (zum Beispiel `res.file(filename)`) und rufe `next()` auf. Es werden höchstens 20 Dateien gleichzeitig generiert.\n\nExample: Generierte Datei\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nDie Endung eines Requests nach einer statischen Datei, ohne Punkt.\n\nReturns: `String`\n\nGesetzt für Requests, deren Pfad auf eine Endung endet (`req.isStaticFile` ist `true`).\n\nExample: Nach Endung verzweigen\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nLiefert statische Dateien über den Übersetzer aus oder legt die Sprache der Requests fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Das URL-Muster oder die Sprachfunktion. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` und Routen-Flags wie `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifiziert HTML. Standard `true`. |\n\n`LOCALIZE(url)` erstellt eine Datei-Route, die die Dateien unter `url` aus `public/` liest, `@(Text)`-Marker durch Übersetzungen in der Sprache des Requests ersetzt und das Ergebnis im Release-Modus pro Sprache cacht. HTML wird minifiziert, wenn `allow_compile_html` aktiv ist; das Flag `nocompress` oder `minify = false` schaltet das ab.\n\nDie URL kann auf ein Dateimuster wie `/templates/*.html` enden. Ohne Endung werden `.html`-, `.htm`-, `.md`- und `.txt`-Dateien behandelt; Flags `.ext` wählen andere. Eine URL, die mit `#` beginnt, ist eine Sitemap-ID.\n\n`LOCALIZE(fn)` setzt die Funktion `fn(req, res, isStaticFile)`, die die Sprache eines Requests zurückgibt. Statische `.html`- und `.htm`-Dateien aus `public/` werden automatisch lokalisiert, wenn `allow_localize` aktiv ist.\n\nExample: Sprache und Dateien\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nErstellt für eine URL skalierte Bilder im laufenden Betrieb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Ein URL-Pfad, optional mit `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Legt die Bildoperationen fest. |\n| `flags` | `String[]` | yes |  | Quellpfad oder URL, `.ext`, `nocache`. |\n\nRequests nach Bildern unter `url` werden von `fn(image)` aus den Quellbildern erzeugt und in `/tmp/` gecacht. Standardmäßig ist die Quelle derselbe Pfad in `public/`. In `flags` legt ein Pfad (`/img/` oder `~/absolute/path/`) oder eine URL `http(s)://` fest, wo die Quellbilder liegen, `.ext` fügt eine Endung hinzu, und `nocache` schaltet den Cache ab. JPG, JPEG, PNG, GIF, APNG, HEIF und HEIC werden immer behandelt.\n\nExample: Kleine Bilder aus /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nLiefert eine URL aus einer anderen Datei oder einem anderen Verzeichnis aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL. |\n| `filename` | `String` | yes |  | Eine Datei oder ein Verzeichnis. |\n| `filter` | `String[]|Function` | yes |  | Filtert die Dateien eines Verzeichnisses. |\n\nHat `filename` eine Endung, wird die URL auf diese Datei abgebildet. Andernfalls ist es ein Verzeichnis, und jede Datei darin wird unter `url` abgebildet; `filter` ist ein Array von Endungen oder eine Funktion `(filename)`, die für die abzubildenden Dateien `true` zurückgibt.\n\nEin relativer `filename` wird zuerst in `public/` gesucht. Präfixe: `~` für einen Pfad ab dem Stammverzeichnis der Anwendung, `@` für ein Paket, `=` für ein Theme. Eine `url`, die mit `#` beginnt, ist eine Sitemap-ID. Die abgebildete Datei wird trotzdem nur ausgeliefert, wenn ihre Endung erlaubt ist.\n\nExample: Datei und Verzeichnis\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nLiefert mehrere Dateien als eine Datei aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL der zusammengefügten Datei. |\n| `file1` | `String|String[]` | yes |  | Die zusammenzufügenden Dateien, in Reihenfolge. |\n\nDie Dateien werden zu einer Datei zusammengefügt, die in `/tmp/` gespeichert wird. Jedes Argument kann ein Dateiname, eine URL oder ein Array sein. Ein Dateiname mit `@` stammt aus einem Paket, mit `=` aus einem Theme. Die `url` richtet sich nach der Datei `/versions`.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nErlaubt eine Endung für statische Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | Eine Endung, mit oder ohne Punkt. |\n| `type` | `String` | yes |  | Der Content-Type. |\n\nFügt die Endung zu `static_accepts` hinzu. Mit `type` setzt es auch den Content-Type der Endung.\n\nExample: 3D-Modelle\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nLeert den Cache verarbeiteter statischer Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Eine URL wie `/css/default.css`. |\n\nDas Framework merkt sich jede verarbeitete Datei (minifiziert, komprimiert oder nicht gefunden) anhand ihrer URL. `TOUCH(url)` vergisst eine URL, sodass der nächste Request die Datei erneut liest; `TOUCH()` vergisst alle.\n\nExample: Nach einer Änderung\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nGibt den absoluten Pfad zu einer Datei im Verzeichnis public zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Ein relativer Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis wird durch `directory_public` festgelegt.\n\nExample: Pfad\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nGibt die URL einer statischen Datei zurück, mit angewendetem `static_url` und der Datei `/versions`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Dateiname. |\n| `theme` | `String` | yes |  | Ein Theme-Name. |\n\nReturns: `String` Eine URL.\n\nRelative Namen erhalten das Präfix des jeweiligen Helfers: `F.public()` verwendet `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` und `F.public_download()` `static_url_download`. Namen, die mit `/` beginnen, erhalten kein Präfix. Ein Name, der mit `~` beginnt, ignoriert das Theme, `=theme/` wählt ein Theme (`=?/` das Standard-Theme). Mit `default_root` wird das Stammverzeichnis hinzugefügt. Views verwenden dieselben Helfer.\n\nExample: URLs\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nGibt die URL eines Skripts zurück, mit `static_url_script` als Präfix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Dateiname. |\n| `theme` | `String` | yes |  | Ein Theme-Name. |\n\nReturns: `String` Eine URL.\n\nDie Regeln findest du bei `F.public()`.\n\nExample: Skript\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nGibt die URL eines Stylesheets zurück, mit `static_url_style` als Präfix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Dateiname. |\n| `theme` | `String` | yes |  | Ein Theme-Name. |\n\nReturns: `String` Eine URL.\n\nDie Regeln findest du bei `F.public()`.\n\nExample: Stylesheet\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nGibt die URL eines Bildes zurück, mit `static_url_image` als Präfix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Dateiname. |\n| `theme` | `String` | yes |  | Ein Theme-Name. |\n\nReturns: `String` Eine URL.\n\nDie Regeln findest du bei `F.public()`.\n\nExample: Bild\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nDas Verzeichnis mit statischen Dateien. Standard `/public/`.\n\nReturns: `String` '/public/'\n\nRequests nach statischen Dateien werden hier gesucht. `PATH.public()` bildet Pfade in dieses Verzeichnis.\n\nExample: Konfigurationsdatei\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nDas Präfix der URLs, die `F.public()` erzeugt. Standardmäßig leer.\n\nReturns: `String` ''\n\nDie anderen Präfixe sind `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) und `static_url_download` (`/download/`). Sie ändern nur die erzeugten URLs; die Dateien werden weiterhin von ihrem Pfad in `public/` ausgeliefert. Ein Präfix kann eine vollständige URL sein, zum Beispiel die eines CDN.\n\nExample: Konfigurationsdatei\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nDas Präfix der URLs, die `F.public_js()` erzeugt. Standard `/js/`.\n\nReturns: `String` '/js/'\n\nSiehe `static_url`.\n\nExample: Konfigurationsdatei\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nDie Endungen, die statische Dateien haben dürfen.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nStatische Dateien mit anderen Endungen antworten mit 404. Die Standardliste: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nIn der Konfigurationsdatei **ersetzt** `static_accepts` die Liste, während `static_accepts_custom` ihr Endungen hinzufügt. Beide nehmen eine kommagetrennte Liste. Im Code verwendest du `ACCEPT()`.\n\nExample: Konfigurationsdatei\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nSchaltet die Behandlung statischer Dateien ein oder aus. Standard `true`.\n\nReturns: `Boolean` true\n\nBei `false` werden Pfade mit Endung wie normale Requests geroutet, und das Verzeichnis public wird nicht ausgeliefert.\n\nExample: Konfigurationsdatei\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nKomprimiert statische Dateien mit GZIP. Standard `true`.\n\nReturns: `Boolean` true\n\nGilt für Texttypen: reiner Text, HTML, CSS, JavaScript, JSX, JSON, XML, SVG und Markdown, wenn der Client `Accept-Encoding: gzip` sendet. Die komprimierte Kopie wird in `/tmp/` gespeichert.\n\nExample: Konfigurationsdatei\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifiziert statisches JavaScript, CSS und HTML. Standard `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript und `.mjs`), `allow_compile_style` (CSS) und `allow_compile_html` (lokalisiertes HTML) schalten einzelne Typen; alle sind standardmäßig `true`. Dateien mit Namen wie `*.min.js`, `*-min.css` oder `*.min@version.js` werden nicht minifiziert. In CSS richten sich `url()`-Werte nach der Datei `/versions`.\n\nExample: Konfigurationsdatei\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLokalisiert statische `.html`- und `.htm`-Dateien. Standard `true`.\n\nReturns: `Boolean` true\n\nDie `@(Text)`-Marker in HTML-Dateien aus `public/` werden in die Sprache des Requests übersetzt, die mit `LOCALIZE(fn)` festgelegt wird.\n\nExample: Konfigurationsdatei\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nSpeichert Bilder, die `res.image()` erzeugt, als persistente Dateien. Standard `true`.\n\nReturns: `Boolean` true\n\nDer Standardwert für das Argument `persistent` von `res.image()`.\n\nExample: Konfigurationsdatei\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nEin Wert, der dem `ETag` statischer Dateien hinzugefügt wird.\n\nReturns: `String` ''\n\nIst er leer, wird er beim Start aus `version` gesetzt (ohne Punkte und Leerzeichen). Ändere `version` oder `etag_version`, damit Browser geänderte Dateien erneut herunterladen.\n\nExample: Konfigurationsdatei\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nEin URL-Präfix, wenn die Anwendung unter einem Unterpfad läuft.\n\nReturns: `String` ''\n\nMit `default_root : /app/` beginnen statische URLs, die von `F.public()` und den Views erzeugt werden, mit `/app/`, und die Datei `/versions` wird mit diesem Präfix angewendet.\n\nExample: Konfigurationsdatei\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nDie Datei `/versions` im Stammverzeichnis der Anwendung bildet Datei-URLs auf versionierte URLs ab.\n\nReturns: `File`\n\nJede Zeile hat die Form `url : newurl`. Der Wert `auto` fügt beim Start einen Hash des Dateiinhalts an den Namen an (`/js/app.js` wird zu `/js/app-<hash>.js`). Mit `-->` statt `:` wird die neue URL zusätzlich auf die ursprüngliche Datei abgebildet. Zeilen, die mit `#` oder `// ` beginnen, sind Kommentare. Die Helfer `F.public_*()`, `MERGE()` und Views verwenden die neuen URLs.\n\nExample: Konfigurationsdatei\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nÄndert den Inhalt von Views, Styles und Skripten, bevor sie kompiliert werden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Pfad relativ zur App, zum Beispiel `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)`, die den neuen Inhalt zurückgibt. |\n\nDie Funktion wird mit `(type, filename, value, controller)` aufgerufen, wobei `type` `'view'`, `'style'`, `'script'` oder `'static'` ist (eine von Total.js lokalisierte statische Datei) und `filename` der Pfad relativ zur App mit führendem `/`. Gib den neuen Inhalt zurück; ein falsy Ergebnis lässt ihn unverändert.\n\nMit `filename` (zum Beispiel `'/views/index.html'`) läuft die Funktion nur für diese Datei. Die Änderung erfolgt im Speicher, die Datei auf der Festplatte bleibt unverändert. Im Release-Modus wird kompilierter Inhalt gecacht, sodass die Funktion einmal pro Datei läuft. Eine von einem Plugin oder Modul registrierte Funktion wird entfernt, wenn es deinstalliert wird.\n\nExample: Jeder View ein Banner hinzufügen\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: Nur eine Datei\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Archivos estáticos","summary":"Rutas de archivo, los métodos de respuesta para archivos, y las utilidades y la configuración de los archivos estáticos.","markdown":"---\ntitle: \"Archivos estáticos\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Archivos estáticos\n\n> Rutas de archivo, los métodos de respuesta para archivos, y las utilidades y la configuración de los archivos estáticos.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nCrea una ruta de archivo; `ROUTE('FILE /url/*.ext', action, [flags])` la llama.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | El patrón de URL, o una función `(req, res)` que devuelve `true`. |\n| `action` | `Function(req, res)|String` | yes |  | El manejador, un nombre de archivo o una URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, un objeto de opciones. |\n\nUna ruta de archivo gestiona las peticiones de archivos estáticos (rutas que terminan con una extensión) antes de que el framework busque en `public/`. Gana la primera ruta que coincide; las URLs más largas se prueban primero.\n\nLas formas de `url`:\n\n| URL | Coincide con |\n| --- | --- |\n| `/photos/*.jpg` | archivos `.jpg` bajo `/photos/` |\n| `/photos/*` o `/photos/*.*` | cualquier archivo bajo `/photos/` |\n| `/favicon.ico` | exactamente este archivo |\n\n`action` es `function(req, res)`. También puede ser una cadena: un nombre de archivo absoluto que se envía con `res.file()`, o una URL `http://`/`https://` cuya respuesta se transmite. En lugar de una URL puedes pasar una función `function(req, res)` que devuelve `true` para las peticiones que hay que gestionar.\n\nFlags: `#name` añade middleware, `.ext` limita las extensiones, `id:name` define el ID de la ruta, y un objeto se convierte en `$.options` en el middleware. En las rutas de archivo, pon el middleware en el array de flags, no dentro de la URL. Cuando la acción no responde por sí misma, llama a `res.continue()` para servir el archivo desde `public/`.\n\nExample: Descargas protegidas\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: Un archivo fijo\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Función de validación\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nDefine un manejador para archivos estáticos que no existen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | El manejador. |\n\n`fn(req, res)` se llama en lugar de la respuesta 404 para los archivos estáticos que faltan, que `static_accepts` no permite o que `res.file()` no encuentra. Devuelve `true` cuando hayas respondido a la petición; si no, el framework responde con 404.\n\nExample: Imagen de reemplazo\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nEnvía un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Una ruta absoluta. |\n| `download` | `String|Boolean` | yes |  | Un nombre de descarga, o `true` para el nombre del archivo. |\n| `headers` | `Object` | yes |  | Cabeceras adicionales. |\n| `callback` | `Function` | yes |  | Se llama cuando se envía el archivo. |\n\nReturns: `Response`\n\n`filename` es una ruta absoluta; un `@` inicial indica un archivo de un paquete. El tipo de contenido sale de la extensión de la petición (o del archivo). El archivo recibe la misma caché, compresión GZIP, soporte de `Range` y gestión de `304 Not Modified` que los archivos de `public/`. Los archivos `.html` se localizan cuando `allow_localize` está activado.\n\n`download` añade `Content-Disposition: attachment` con este nombre de archivo; `true` usa el nombre del archivo. En modo release el framework recuerda el archivo de cada URL; llama a `TOUCH(url)` cuando cambie.\n\nExample: Descarga\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nProcesa una imagen con GraphicsMagick o ImageMagick y envía el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | La imagen de origen. |\n| `make` | `Function(image, res)` | yes |  | Define las operaciones de imagen. |\n| `headers` | `Object` | yes |  | Cabeceras adicionales. |\n| `callback` | `Function` | yes |  | Se llama cuando se envía la imagen. |\n| `persistent` | `Boolean` | yes |  | Guarda el resultado como archivo persistente. |\n\nReturns: `Response`\n\n`filename` es una ruta absoluta o un stream legible. `make(image, res)` recibe un objeto de imagen y define las operaciones (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). El resultado se guarda en `/tmp/` bajo la URL de la petición y las peticiones posteriores reciben el archivo guardado.\n\n`persistent` guarda el resultado como archivo persistente (prefijo `timg_` en `/tmp/`) y lo reutiliza mientras exista; si se omite, sigue `allow_persistent_images` (por defecto `true`). `res.image_nocache(filename, make, [headers], [callback])` hace lo mismo sin la caché.\n\nExample: Miniaturas\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nEnvía un archivo desde un FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del FileStorage. |\n| `id` | `String|Number` | yes |  | El ID del archivo. |\n| `download` | `String` | yes |  | Un nombre de descarga. |\n| `headers` | `Object` | yes |  | Cabeceras adicionales. |\n| `callback` | `Function` | yes |  | Se llama al terminar. |\n| `checkmeta` | `Function(meta)` | yes |  | Comprueba los metadatos del archivo. |\n\nReturns: `Response`\n\nLee el archivo `id` de `FILESTORAGE(name)` y lo envía con su tipo de contenido guardado. `checkmeta(meta)` puede inspeccionar los metadatos del archivo antes de enviarlo.\n\nExample: Archivos desde el almacenamiento\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nProcesa una imagen de un FileStorage y envía el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del FileStorage. |\n| `id` | `String|Number` | yes |  | El ID del archivo. |\n| `make` | `Function(image, res)` | yes |  | Define las operaciones de imagen. |\n| `headers` | `Object` | yes |  | Cabeceras adicionales. |\n| `callback` | `Function` | yes |  | Se llama al terminar. |\n| `checkmeta` | `Function(meta)` | yes |  | Comprueba los metadatos del archivo. |\n\nReturns: `Response`\n\nComo `res.filefs()`, pero `make(image, res)` define operaciones de imagen como en `res.image()`.\n\nExample: Avatares desde el almacenamiento\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nEnvía un stream legible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El tipo de contenido. |\n| `stream` | `Stream` | yes |  | Un stream legible. |\n| `download` | `String` | yes |  | Un nombre de descarga. |\n| `headers` | `Object` | yes |  | Cabeceras adicionales. |\n| `callback` | `Function` | yes |  | Se llama al terminar. |\n| `nocompress` | `Boolean` | yes |  | Desactiva la compresión. |\n\nReturns: `Response`\n\nEl stream se comprime con GZIP cuando el tipo de contenido se puede comprimir y el cliente lo acepta, salvo que `nocompress` sea `true`.\n\nExample: Transmitir un archivo\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nSirve el archivo estático solicitado desde el directorio público, como sin ruta de archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Se llama cuando se envía el archivo. |\n\nReturns: `Response`\n\nÚsalo en una ruta de archivo o en un middleware que decide no responder por sí mismo a la petición. La extensión debe estar en `static_accepts`; si no, y cuando el archivo no existe, la respuesta es 404 (o el manejador de `FILE404()`). También aplica `MAP()`, `MERGE()` y `RESIZE()`.\n\nExample: Servir solo a usuarios autenticados\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nSirve un archivo generado desde `/tmp/`, o te pide que lo crees.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Crea el archivo que falta. |\n\nEl nombre del archivo en `/tmp/` se construye a partir de la URL de la petición. Cuando el archivo existe, se envía y `callback` no se llama. Si no, se llama a `callback(next, filename, req, res)`: escribe el archivo en `filename`, envía la respuesta (por ejemplo `res.file(filename)`) y llama a `next()`. Se generan como máximo 20 archivos a la vez.\n\nExample: Archivo generado\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nLa extensión de una petición de archivo estático, sin el punto.\n\nReturns: `String`\n\nEstá definida en las peticiones cuya ruta termina con una extensión (`req.isStaticFile` es `true`).\n\nExample: Bifurcar según la extensión\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nSirve archivos estáticos a través del traductor, o define el idioma de las peticiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | El patrón de URL, o la función de idioma. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` y flags de ruta como `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifica el HTML. Por defecto `true`. |\n\n`LOCALIZE(url)` crea una ruta de archivo que lee los archivos bajo `url` desde `public/`, reemplaza los marcadores `@(Text)` por traducciones en el idioma de la petición y guarda en caché el resultado por idioma en modo release. El HTML se minifica cuando `allow_compile_html` está activado; el flag `nocompress` o `minify = false` lo desactiva.\n\nLa URL puede terminar con un patrón de archivo como `/templates/*.html`. Sin extensión, se gestionan los archivos `.html`, `.htm`, `.md` y `.txt`; los flags `.ext` eligen otros. Una URL que empieza con `#` es un ID del sitemap.\n\n`LOCALIZE(fn)` define la función `fn(req, res, isStaticFile)` que devuelve el idioma de una petición. Los archivos estáticos `.html` y `.htm` de `public/` se localizan automáticamente cuando `allow_localize` está activado.\n\nExample: Idioma y archivos\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nCrea imágenes redimensionadas al vuelo para una URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una ruta de URL, opcionalmente con `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Define las operaciones de imagen. |\n| `flags` | `String[]` | yes |  | Ruta o URL de origen, `.ext`, `nocache`. |\n\nLas peticiones de imágenes bajo `url` se generan a partir de las imágenes de origen con `fn(image)` y se guardan en caché en `/tmp/`. Por defecto el origen es la misma ruta en `public/`. En `flags`, una ruta (`/img/`, o `~/absolute/path/`) o una URL `http(s)://` indica dónde están las imágenes de origen, `.ext` añade una extensión y `nocache` desactiva la caché. JPG, JPEG, PNG, GIF, APNG, HEIF y HEIC se gestionan siempre.\n\nExample: Imágenes pequeñas desde /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nSirve una URL desde otro archivo o directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL. |\n| `filename` | `String` | yes |  | Un archivo o un directorio. |\n| `filter` | `String[]|Function` | yes |  | Filtra los archivos de un directorio. |\n\nCuando `filename` tiene extensión, la URL se mapea a ese archivo. Si no, es un directorio y cada archivo de dentro se mapea bajo `url`; `filter` es un array de extensiones o una función `(filename)` que devuelve `true` para los archivos que hay que mapear.\n\nUn `filename` relativo se busca primero en `public/`. Prefijos: `~` para una ruta desde la raíz de la aplicación, `@` para un paquete, `=` para un tema. Una `url` que empieza con `#` es un ID del sitemap. El archivo mapeado solo se sirve si su extensión está permitida.\n\nExample: Archivo y directorio\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nSirve varios archivos como un solo archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL del archivo combinado. |\n| `file1` | `String|String[]` | yes |  | Archivos que se combinan, en orden. |\n\nLos archivos se unen en un solo archivo guardado en `/tmp/`. Cada argumento puede ser un nombre de archivo, una URL o un array. Un nombre de archivo con `@` es de un paquete, con `=` de un tema. La `url` sigue el archivo `/versions`.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nPermite una extensión para archivos estáticos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | Una extensión, con o sin el punto. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n\nAñade la extensión a `static_accepts`. Con `type`, también define el tipo de contenido de la extensión.\n\nExample: Modelos 3D\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nBorra la caché de archivos estáticos procesados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una URL como `/css/default.css`. |\n\nEl framework recuerda cada archivo procesado (minificado, comprimido o no encontrado) por su URL. `TOUCH(url)` olvida una URL, de modo que la siguiente petición vuelve a leer el archivo; `TOUCH()` las olvida todas.\n\nExample: Tras un cambio\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nDevuelve la ruta absoluta de un archivo del directorio público.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nombre de archivo relativo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio se define con `directory_public`.\n\nExample: Ruta\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nDevuelve la URL de un archivo estático, con `static_url` y el archivo `/versions` aplicados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre de archivo. |\n| `theme` | `String` | yes |  | Un nombre de tema. |\n\nReturns: `String` Una URL.\n\nLos nombres relativos reciben el prefijo de la utilidad: `F.public()` usa `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` y `F.public_download()` `static_url_download`. Los nombres que empiezan con `/` no reciben prefijo. Un nombre que empieza con `~` ignora el tema, `=theme/` selecciona un tema (`=?/` el tema por defecto). Con `default_root`, se añade la raíz. Las vistas usan las mismas utilidades.\n\nExample: URLs\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nDevuelve la URL de un script, con `static_url_script` como prefijo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre de archivo. |\n| `theme` | `String` | yes |  | Un nombre de tema. |\n\nReturns: `String` Una URL.\n\nConsulta `F.public()` para las reglas.\n\nExample: Script\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nDevuelve la URL de una hoja de estilos, con `static_url_style` como prefijo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre de archivo. |\n| `theme` | `String` | yes |  | Un nombre de tema. |\n\nReturns: `String` Una URL.\n\nConsulta `F.public()` para las reglas.\n\nExample: Hoja de estilos\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nDevuelve la URL de una imagen, con `static_url_image` como prefijo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre de archivo. |\n| `theme` | `String` | yes |  | Un nombre de tema. |\n\nReturns: `String` Una URL.\n\nConsulta `F.public()` para las reglas.\n\nExample: Imagen\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nEl directorio con los archivos estáticos. Por defecto `/public/`.\n\nReturns: `String` '/public/'\n\nLas peticiones de archivos estáticos se buscan aquí. `PATH.public()` construye rutas dentro de él.\n\nExample: Archivo de configuración\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nEl prefijo de las URLs generadas por `F.public()`. Por defecto vacío.\n\nReturns: `String` ''\n\nLos otros prefijos son `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) y `static_url_download` (`/download/`). Solo cambian las URLs generadas; los archivos se siguen sirviendo desde su ruta en `public/`. Un prefijo puede ser una URL completa, por ejemplo de una CDN.\n\nExample: Archivo de configuración\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nEl prefijo de las URLs generadas por `F.public_js()`. Por defecto `/js/`.\n\nReturns: `String` '/js/'\n\nConsulta `static_url`.\n\nExample: Archivo de configuración\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nLas extensiones que pueden tener los archivos estáticos.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nLos archivos estáticos con otras extensiones responden 404. La lista por defecto: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nEn el archivo de configuración, `static_accepts` **reemplaza** la lista, mientras que `static_accepts_custom` le añade extensiones. Ambos aceptan una lista separada por comas. En el código, usa `ACCEPT()`.\n\nExample: Archivo de configuración\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nActiva o desactiva la gestión de archivos estáticos. Por defecto `true`.\n\nReturns: `Boolean` true\n\nCon `false`, las rutas con extensión se enrutan como peticiones normales y el directorio público no se sirve.\n\nExample: Archivo de configuración\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nComprime los archivos estáticos con GZIP. Por defecto `true`.\n\nReturns: `Boolean` true\n\nSe aplica a los tipos de texto: texto plano, HTML, CSS, JavaScript, JSX, JSON, XML, SVG y Markdown, cuando el cliente envía `Accept-Encoding: gzip`. La copia comprimida se guarda en `/tmp/`.\n\nExample: Archivo de configuración\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifica JavaScript, CSS y HTML estáticos. Por defecto `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript y `.mjs`), `allow_compile_style` (CSS) y `allow_compile_html` (HTML localizado) activan cada tipo por separado; todos son `true` por defecto. Los archivos con nombres como `*.min.js`, `*-min.css` o `*.min@version.js` no se minifican. En CSS, los valores `url()` siguen el archivo `/versions`.\n\nExample: Archivo de configuración\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLocaliza los archivos estáticos `.html` y `.htm`. Por defecto `true`.\n\nReturns: `Boolean` true\n\nLos marcadores `@(Text)` de los archivos HTML de `public/` se traducen al idioma de la petición definido con `LOCALIZE(fn)`.\n\nExample: Archivo de configuración\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nGuarda las imágenes generadas por `res.image()` como archivos persistentes. Por defecto `true`.\n\nReturns: `Boolean` true\n\nEl valor por defecto del argumento `persistent` de `res.image()`.\n\nExample: Archivo de configuración\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nUn valor que se añade al `ETag` de los archivos estáticos.\n\nReturns: `String` ''\n\nCuando está vacío, se toma de `version` (sin puntos ni espacios) al arrancar. Cambia `version` o `etag_version` para que los navegadores vuelvan a descargar los archivos modificados.\n\nExample: Archivo de configuración\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nUn prefijo de URL cuando la aplicación se ejecuta bajo una subruta.\n\nReturns: `String` ''\n\nCon `default_root : /app/`, las URLs estáticas generadas por `F.public()` y las vistas empiezan con `/app/`, y el archivo `/versions` se aplica con este prefijo.\n\nExample: Archivo de configuración\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nEl archivo `/versions` en la raíz de la aplicación mapea URLs de archivos a URLs con versión.\n\nReturns: `File`\n\nCada línea es `url : newurl`. El valor `auto` añade un hash del contenido del archivo al nombre al arrancar (`/js/app.js` se convierte en `/js/app-<hash>.js`). Con `-->` en lugar de `:`, la nueva URL también se mapea al archivo original. Las líneas que empiezan con `#` o `// ` son comentarios. Las utilidades `F.public_*()`, `MERGE()` y las vistas usan las nuevas URLs.\n\nExample: Archivo de configuración\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nCambia el contenido de vistas, estilos y scripts antes de compilarlos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Una ruta relativa a la aplicación, por ejemplo `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)` que devuelve el nuevo contenido. |\n\nLa función se llama con `(type, filename, value, controller)`, donde `type` es `'view'`, `'style'`, `'script'` o `'static'` (un archivo estático localizado por Total.js) y `filename` es la ruta relativa a la aplicación con una `/` inicial. Devuelve el nuevo contenido; un resultado falsy lo deja como estaba.\n\nCon `filename` (por ejemplo `'/views/index.html'`) la función solo se ejecuta para ese archivo. El cambio se hace en memoria; el archivo en disco queda como está. En modo release el contenido compilado se cachea, así que la función se ejecuta una vez por archivo. Una función registrada por un plugin o un módulo se elimina cuando se desinstala.\n\nExample: Añadir un banner a cada vista\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: Solo un archivo\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Fichiers statiques","summary":"Les routes de fichiers, les méthodes de réponse pour les fichiers, ainsi que les fonctions et la configuration des fichiers statiques.","markdown":"---\ntitle: Fichiers statiques\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Fichiers statiques\n\n> Les routes de fichiers, les méthodes de réponse pour les fichiers, ainsi que les fonctions et la configuration des fichiers statiques.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nCrée une route de fichier ; `ROUTE('FILE /url/*.ext', action, [flags])` l'appelle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Le motif d'URL, ou une fonction `(req, res)` qui renvoie `true`. |\n| `action` | `Function(req, res)|String` | yes |  | Le gestionnaire, un nom de fichier ou une URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, un objet d'options. |\n\nUne route de fichier traite les requêtes de fichiers statiques (chemins qui se terminent par une extension) avant que le framework ne cherche dans `public/`. La première route qui correspond l'emporte ; les URL les plus longues sont testées en premier.\n\nLes formes d'`url` :\n\n| URL | Correspond à |\n| --- | --- |\n| `/photos/*.jpg` | les fichiers `.jpg` sous `/photos/` |\n| `/photos/*` ou `/photos/*.*` | n'importe quel fichier sous `/photos/` |\n| `/favicon.ico` | exactement ce fichier |\n\n`action` est `function(req, res)`. Ce peut aussi être une chaîne : un nom de fichier absolu à envoyer avec `res.file()`, ou une URL `http://`/`https://` dont la réponse est transmise en flux. À la place d'une URL, tu peux passer une fonction `function(req, res)` qui renvoie `true` pour les requêtes à traiter.\n\nFlags : `#name` ajoute un middleware, `.ext` limite les extensions, `id:name` définit l'ID de la route, et un objet devient `$.options` dans le middleware. Pour les routes de fichiers, place le middleware dans le tableau de flags, et non directement dans l'URL. Quand l'action ne répond pas elle-même, appelle `res.continue()` pour servir le fichier depuis `public/`.\n\nExample: Téléchargements protégés\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: Un fichier fixe\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Fonction de validation\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nDéfinit un gestionnaire pour les fichiers statiques qui n'existent pas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | Le gestionnaire. |\n\n`fn(req, res)` est appelée à la place de la réponse 404 pour les fichiers statiques absents, non autorisés par `static_accepts` ou introuvables par `res.file()`. Renvoie `true` quand tu as répondu à la requête ; sinon, le framework répond avec 404.\n\nExample: Image de remplacement\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nEnvoie un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un chemin absolu. |\n| `download` | `String|Boolean` | yes |  | Un nom de téléchargement, ou `true` pour le nom du fichier. |\n| `headers` | `Object` | yes |  | En-têtes supplémentaires. |\n| `callback` | `Function` | yes |  | Appelée quand le fichier est envoyé. |\n\nReturns: `Response`\n\n`filename` est un chemin absolu ; un `@` initial désigne un fichier d'un paquet. Le type de contenu vient de l'extension de la requête (ou du fichier). Le fichier bénéficie de la même mise en cache, de la compression GZIP, de la prise en charge de `Range` et de la gestion de `304 Not Modified` que les fichiers de `public/`. Les fichiers `.html` sont localisés quand `allow_localize` est activé.\n\n`download` ajoute `Content-Disposition: attachment` avec ce nom de fichier ; `true` utilise le nom du fichier. En mode release, le framework mémorise le fichier de chaque URL ; appelle `TOUCH(url)` quand il change.\n\nExample: Téléchargement\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nTraite une image avec GraphicsMagick ou ImageMagick et envoie le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'image source. |\n| `make` | `Function(image, res)` | yes |  | Définit les opérations sur l'image. |\n| `headers` | `Object` | yes |  | En-têtes supplémentaires. |\n| `callback` | `Function` | yes |  | Appelée quand l'image est envoyée. |\n| `persistent` | `Boolean` | yes |  | Stocke le résultat comme fichier persistant. |\n\nReturns: `Response`\n\n`filename` est un chemin absolu ou un flux lisible. `make(image, res)` reçoit un objet image et définit les opérations (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). Le résultat est stocké dans `/tmp/` sous l'URL de la requête et les requêtes suivantes reçoivent le fichier stocké.\n\n`persistent` stocke le résultat comme fichier persistant (préfixe `timg_` dans `/tmp/`) et le réutilise tant qu'il existe ; s'il est omis, il suit `allow_persistent_images` (par défaut `true`). `res.image_nocache(filename, make, [headers], [callback])` fait la même chose sans le cache.\n\nExample: Miniatures\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nEnvoie un fichier depuis un FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du FileStorage. |\n| `id` | `String|Number` | yes |  | L'ID du fichier. |\n| `download` | `String` | yes |  | Un nom de téléchargement. |\n| `headers` | `Object` | yes |  | En-têtes supplémentaires. |\n| `callback` | `Function` | yes |  | Appelée à la fin. |\n| `checkmeta` | `Function(meta)` | yes |  | Vérifie les métadonnées du fichier. |\n\nReturns: `Response`\n\nLit le fichier `id` dans `FILESTORAGE(name)` et l'envoie avec son type de contenu enregistré. `checkmeta(meta)` peut examiner les métadonnées du fichier avant son envoi.\n\nExample: Fichiers depuis le stockage\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nTraite une image depuis un FileStorage et envoie le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du FileStorage. |\n| `id` | `String|Number` | yes |  | L'ID du fichier. |\n| `make` | `Function(image, res)` | yes |  | Définit les opérations sur l'image. |\n| `headers` | `Object` | yes |  | En-têtes supplémentaires. |\n| `callback` | `Function` | yes |  | Appelée à la fin. |\n| `checkmeta` | `Function(meta)` | yes |  | Vérifie les métadonnées du fichier. |\n\nReturns: `Response`\n\nComme `res.filefs()`, mais `make(image, res)` définit les opérations sur l'image comme dans `res.image()`.\n\nExample: Avatars depuis le stockage\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nEnvoie un flux lisible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le type de contenu. |\n| `stream` | `Stream` | yes |  | Un flux lisible. |\n| `download` | `String` | yes |  | Un nom de téléchargement. |\n| `headers` | `Object` | yes |  | En-têtes supplémentaires. |\n| `callback` | `Function` | yes |  | Appelée à la fin. |\n| `nocompress` | `Boolean` | yes |  | Désactive la compression. |\n\nReturns: `Response`\n\nLe flux est compressé avec GZIP quand le type de contenu peut être compressé et que le client l'accepte, sauf si `nocompress` vaut `true`.\n\nExample: Envoyer un fichier en flux\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nSert le fichier statique demandé depuis le répertoire public, comme sans route de fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Appelée quand le fichier est envoyé. |\n\nReturns: `Response`\n\nUtilise-la dans une route de fichier ou un middleware qui décide de ne pas répondre lui-même à la requête. L'extension doit figurer dans `static_accepts` ; sinon, et quand le fichier n'existe pas, la réponse est 404 (ou le gestionnaire `FILE404()`). Elle applique aussi `MAP()`, `MERGE()` et `RESIZE()`.\n\nExample: Servir uniquement aux utilisateurs connectés\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nSert un fichier généré depuis `/tmp/`, ou te demande de le créer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Crée le fichier manquant. |\n\nLe nom du fichier dans `/tmp/` est construit à partir de l'URL de la requête. Quand le fichier existe, il est envoyé et `callback` n'est pas appelée. Sinon, `callback(next, filename, req, res)` est appelée : écris le fichier dans `filename`, envoie la réponse (par exemple `res.file(filename)`) et appelle `next()`. Au plus 20 fichiers sont générés en même temps.\n\nExample: Fichier généré\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nL'extension d'une requête de fichier statique, sans le point.\n\nReturns: `String`\n\nDéfinie pour les requêtes dont le chemin se termine par une extension (`req.isStaticFile` vaut `true`).\n\nExample: Choisir selon l'extension\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nSert des fichiers statiques via le traducteur, ou définit la langue des requêtes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Le motif d'URL, ou la fonction de langue. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` et des flags de route comme `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifie le HTML. Par défaut `true`. |\n\n`LOCALIZE(url)` crée une route de fichier qui lit les fichiers situés sous `url` dans `public/`, remplace les marqueurs `@(Text)` par les traductions dans la langue de la requête et met le résultat en cache par langue en mode release. Le HTML est minifié quand `allow_compile_html` est activé ; le flag `nocompress` ou `minify = false` désactive la minification.\n\nL'URL peut se terminer par un motif de fichier comme `/templates/*.html`. Sans extension, les fichiers `.html`, `.htm`, `.md` et `.txt` sont traités ; les flags `.ext` en choisissent d'autres. Une URL qui commence par `#` est un ID de sitemap.\n\n`LOCALIZE(fn)` définit la fonction `fn(req, res, isStaticFile)` qui renvoie la langue d'une requête. Les fichiers statiques `.html` et `.htm` de `public/` sont localisés automatiquement quand `allow_localize` est activé.\n\nExample: Langue et fichiers\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nCrée à la volée des images redimensionnées pour une URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un chemin d'URL, éventuellement avec `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Définit les opérations sur l'image. |\n| `flags` | `String[]` | yes |  | Chemin ou URL source, `.ext`, `nocache`. |\n\nLes requêtes d'images sous `url` sont produites à partir des images sources par `fn(image)` et mises en cache dans `/tmp/`. Par défaut, la source est le même chemin dans `public/`. Dans `flags`, un chemin (`/img/`, ou `~/absolute/path/`) ou une URL `http(s)://` indique où se trouvent les images sources, `.ext` ajoute une extension et `nocache` désactive le cache. JPG, JPEG, PNG, GIF, APNG, HEIF et HEIC sont toujours pris en charge.\n\nExample: Petites images depuis /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nSert une URL depuis un autre fichier ou répertoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `filename` | `String` | yes |  | Un fichier ou un répertoire. |\n| `filter` | `String[]|Function` | yes |  | Filtre les fichiers d'un répertoire. |\n\nQuand `filename` a une extension, l'URL est associée à ce fichier. Sinon, c'est un répertoire et chaque fichier qu'il contient est associé sous `url` ; `filter` est un tableau d'extensions ou une fonction `(filename)` qui renvoie `true` pour les fichiers à associer.\n\nUn `filename` relatif est d'abord cherché dans `public/`. Préfixes : `~` pour un chemin depuis la racine de l'application, `@` pour un paquet, `=` pour un thème. Une `url` qui commence par `#` est un ID de sitemap. Le fichier associé n'est servi que si son extension est autorisée.\n\nExample: Fichier et répertoire\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nSert plusieurs fichiers comme un seul fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL du fichier fusionné. |\n| `file1` | `String|String[]` | yes |  | Fichiers à fusionner, dans l'ordre. |\n\nLes fichiers sont réunis en un seul fichier stocké dans `/tmp/`. Chaque argument peut être un nom de fichier, une URL ou un tableau. Un nom de fichier avec `@` vient d'un paquet, avec `=` d'un thème. L'`url` suit le fichier `/versions`.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nAutorise une extension pour les fichiers statiques.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | Une extension, avec ou sans le point. |\n| `type` | `String` | yes |  | Le type de contenu. |\n\nAjoute l'extension à `static_accepts`. Avec `type`, définit aussi le type de contenu de l'extension.\n\nExample: Modèles 3D\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nVide le cache des fichiers statiques traités.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Une URL comme `/css/default.css`. |\n\nLe framework mémorise chaque fichier traité (minifié, compressé ou introuvable) par son URL. `TOUCH(url)` oublie une URL, si bien que la requête suivante relit le fichier ; `TOUCH()` les oublie toutes.\n\nExample: Après une modification\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nRenvoie le chemin absolu d'un fichier du répertoire public.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nom de fichier relatif. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est défini par `directory_public`.\n\nExample: Chemin\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nRenvoie l'URL d'un fichier statique, avec `static_url` et le fichier `/versions` appliqués.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom de fichier. |\n| `theme` | `String` | yes |  | Un nom de thème. |\n\nReturns: `String` Une URL.\n\nLes noms relatifs reçoivent le préfixe de la fonction : `F.public()` utilise `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` et `F.public_download()` `static_url_download`. Les noms qui commencent par `/` ne reçoivent pas de préfixe. Un nom qui commence par `~` ignore le thème, `=theme/` sélectionne un thème (`=?/` le thème par défaut). Avec `default_root`, la racine est ajoutée. Les vues utilisent les mêmes fonctions.\n\nExample: URL\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nRenvoie l'URL d'un script, avec `static_url_script` comme préfixe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom de fichier. |\n| `theme` | `String` | yes |  | Un nom de thème. |\n\nReturns: `String` Une URL.\n\nConsulte `F.public()` pour les règles.\n\nExample: Script\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nRenvoie l'URL d'une feuille de style, avec `static_url_style` comme préfixe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom de fichier. |\n| `theme` | `String` | yes |  | Un nom de thème. |\n\nReturns: `String` Une URL.\n\nConsulte `F.public()` pour les règles.\n\nExample: Feuille de style\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nRenvoie l'URL d'une image, avec `static_url_image` comme préfixe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom de fichier. |\n| `theme` | `String` | yes |  | Un nom de thème. |\n\nReturns: `String` Une URL.\n\nConsulte `F.public()` pour les règles.\n\nExample: Image\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nLe répertoire des fichiers statiques. Par défaut `/public/`.\n\nReturns: `String` '/public/'\n\nLes requêtes de fichiers statiques y sont recherchées. `PATH.public()` construit des chemins vers ce répertoire.\n\nExample: Fichier de configuration\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nLe préfixe des URL produites par `F.public()`. Vide par défaut.\n\nReturns: `String` ''\n\nLes autres préfixes sont `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) et `static_url_download` (`/download/`). Ils ne modifient que les URL générées ; les fichiers sont toujours servis depuis leur chemin dans `public/`. Un préfixe peut être une URL complète, par exemple celle d'un CDN.\n\nExample: Fichier de configuration\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nLe préfixe des URL produites par `F.public_js()`. Par défaut `/js/`.\n\nReturns: `String` '/js/'\n\nVoir `static_url`.\n\nExample: Fichier de configuration\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nLes extensions que peuvent avoir les fichiers statiques.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nLes fichiers statiques avec d'autres extensions répondent 404. La liste par défaut : `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nDans le fichier de configuration, `static_accepts` **remplace** la liste, tandis que `static_accepts_custom` y ajoute des extensions. Les deux acceptent une liste séparée par des virgules. Dans le code, utilise `ACCEPT()`.\n\nExample: Fichier de configuration\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nActive ou désactive le traitement des fichiers statiques. Par défaut `true`.\n\nReturns: `Boolean` true\n\nAvec `false`, les chemins avec une extension sont routés comme des requêtes normales et le répertoire public n'est pas servi.\n\nExample: Fichier de configuration\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nCompresse les fichiers statiques avec GZIP. Par défaut `true`.\n\nReturns: `Boolean` true\n\nS'applique aux types texte : texte brut, HTML, CSS, JavaScript, JSX, JSON, XML, SVG et Markdown, quand le client envoie `Accept-Encoding: gzip`. La copie compressée est stockée dans `/tmp/`.\n\nExample: Fichier de configuration\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifie le JavaScript, le CSS et le HTML statiques. Par défaut `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript et `.mjs`), `allow_compile_style` (CSS) et `allow_compile_html` (HTML localisé) activent chaque type séparément ; tous valent `true` par défaut. Les fichiers nommés comme `*.min.js`, `*-min.css` ou `*.min@version.js` ne sont pas minifiés. Dans le CSS, les valeurs `url()` suivent le fichier `/versions`.\n\nExample: Fichier de configuration\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLocalise les fichiers statiques `.html` et `.htm`. Par défaut `true`.\n\nReturns: `Boolean` true\n\nLes marqueurs `@(Text)` des fichiers HTML de `public/` sont traduits dans la langue de la requête définie avec `LOCALIZE(fn)`.\n\nExample: Fichier de configuration\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nStocke les images produites par `res.image()` comme fichiers persistants. Par défaut `true`.\n\nReturns: `Boolean` true\n\nLa valeur par défaut de l'argument `persistent` de `res.image()`.\n\nExample: Fichier de configuration\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nUne valeur ajoutée à l'`ETag` des fichiers statiques.\n\nReturns: `String` ''\n\nQuand elle est vide, elle est définie au démarrage à partir de `version` (sans les points ni les espaces). Modifie `version` ou `etag_version` pour que les navigateurs téléchargent de nouveau les fichiers modifiés.\n\nExample: Fichier de configuration\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nUn préfixe d'URL quand l'application s'exécute sous un sous-chemin.\n\nReturns: `String` ''\n\nAvec `default_root : /app/`, les URL statiques produites par `F.public()` et par les vues commencent par `/app/`, et le fichier `/versions` est appliqué avec ce préfixe.\n\nExample: Fichier de configuration\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nLe fichier `/versions` à la racine de l'application associe des URL de fichiers à des URL versionnées.\n\nReturns: `File`\n\nChaque ligne est de la forme `url : newurl`. La valeur `auto` ajoute un hash du contenu du fichier à son nom au démarrage (`/js/app.js` devient `/js/app-<hash>.js`). Avec `-->` au lieu de `:`, la nouvelle URL est aussi associée au fichier d'origine. Les lignes qui commencent par `#` ou `// ` sont des commentaires. Les fonctions `F.public_*()`, `MERGE()` et les vues utilisent les nouvelles URL.\n\nExample: Fichier de configuration\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nModifie le contenu des vues, des styles et des scripts avant leur compilation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un chemin relatif à l'application, par exemple `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)` qui renvoie le nouveau contenu. |\n\nLa fonction est appelée avec `(type, filename, value, controller)`, où `type` vaut `'view'`, `'style'`, `'script'` ou `'static'` (un fichier statique localisé par Total.js) et `filename` est le chemin relatif à l'application, avec un `/` initial. Renvoie le nouveau contenu ; un résultat falsy le laisse inchangé.\n\nAvec `filename` (par exemple `'/views/index.html'`), la fonction ne s'exécute que pour ce fichier. La modification est faite en mémoire ; le fichier sur le disque reste inchangé. En mode release, le contenu compilé est mis en cache ; la fonction s'exécute donc une fois par fichier. Une fonction enregistrée par un plugin ou un module est supprimée lors de sa désinstallation.\n\nExample: Ajouter une bannière à chaque vue\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: Un seul fichier\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"File statici","summary":"Le file route, i metodi di risposta per i file, gli helper e la configurazione dei file statici.","markdown":"---\ntitle: File statici\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# File statici\n\n> Le file route, i metodi di risposta per i file, gli helper e la configurazione dei file statici.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nCrea una route di file; `ROUTE('FILE /url/*.ext', action, [flags])` la chiama.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Il pattern dell'URL, oppure una funzione `(req, res)` che restituisce `true`. |\n| `action` | `Function(req, res)|String` | yes |  | Il gestore, un nome di file o un URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, un oggetto di opzioni. |\n\nUna route di file gestisce le richieste di file statici (percorsi che terminano con un'estensione) prima che il framework guardi in `public/`. Vince la prima route che corrisponde; gli URL più lunghi vengono testati per primi.\n\nLe forme di `url`:\n\n| URL | Corrisponde a |\n| --- | --- |\n| `/photos/*.jpg` | i file `.jpg` sotto `/photos/` |\n| `/photos/*` o `/photos/*.*` | qualsiasi file sotto `/photos/` |\n| `/favicon.ico` | esattamente questo file |\n\n`action` è `function(req, res)`. Può anche essere una stringa: un nome di file assoluto da inviare con `res.file()`, oppure un URL `http://`/`https://` la cui risposta viene trasmessa in streaming. Al posto di un URL puoi passare una funzione `function(req, res)` che restituisce `true` per le richieste da gestire.\n\nFlag: `#name` aggiunge un middleware, `.ext` limita le estensioni, `id:name` imposta l'ID della route e un oggetto diventa `$.options` nei middleware. Per le route di file, metti i middleware nell'array dei flag, non inline nell'URL. Quando l'azione non risponde da sola, chiama `res.continue()` per servire il file da `public/`.\n\nExample: Download protetti\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: Un file fisso\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Funzione di validazione\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nImposta un gestore per i file statici che non esistono.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | Il gestore. |\n\n`fn(req, res)` viene chiamato al posto della risposta 404 per i file statici mancanti, non consentiti da `static_accepts` o non trovati da `res.file()`. Restituisci `true` quando hai risposto alla richiesta; altrimenti il framework risponde con 404.\n\nExample: Immagine segnaposto\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nInvia un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un percorso assoluto. |\n| `download` | `String|Boolean` | yes |  | Un nome per il download, oppure `true` per il nome del file. |\n| `headers` | `Object` | yes |  | Header aggiuntivi. |\n| `callback` | `Function` | yes |  | Chiamata quando il file è stato inviato. |\n\nReturns: `Response`\n\n`filename` è un percorso assoluto; una `@` iniziale indica un file di un pacchetto. Il content type deriva dall'estensione della richiesta (o del file). Il file riceve la stessa cache, la compressione GZIP, il supporto a `Range` e la gestione di `304 Not Modified` dei file in `public/`. I file `.html` vengono localizzati quando `allow_localize` è attivo.\n\n`download` aggiunge `Content-Disposition: attachment` con questo nome di file; `true` usa il nome del file. In modalità release il framework ricorda il file di ogni URL; chiama `TOUCH(url)` quando cambia.\n\nExample: Download\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nElabora un'immagine con GraphicsMagick o ImageMagick e invia il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | L'immagine sorgente. |\n| `make` | `Function(image, res)` | yes |  | Imposta le operazioni sull'immagine. |\n| `headers` | `Object` | yes |  | Header aggiuntivi. |\n| `callback` | `Function` | yes |  | Chiamata quando l'immagine è stata inviata. |\n| `persistent` | `Boolean` | yes |  | Salva il risultato come file persistente. |\n\nReturns: `Response`\n\n`filename` è un percorso assoluto o uno stream leggibile. `make(image, res)` riceve un oggetto immagine e imposta le operazioni (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). Il risultato viene salvato in `/tmp/` sotto l'URL della richiesta e le richieste successive ricevono il file salvato.\n\n`persistent` salva il risultato come file persistente (prefisso `timg_` in `/tmp/`) e lo riutilizza finché esiste; se omesso, segue `allow_persistent_images` (predefinito `true`). `res.image_nocache(filename, make, [headers], [callback])` fa lo stesso senza la cache.\n\nExample: Miniature\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nInvia un file da un FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del FileStorage. |\n| `id` | `String|Number` | yes |  | L'ID del file. |\n| `download` | `String` | yes |  | Un nome per il download. |\n| `headers` | `Object` | yes |  | Header aggiuntivi. |\n| `callback` | `Function` | yes |  | Chiamata al termine. |\n| `checkmeta` | `Function(meta)` | yes |  | Controlla i metadati del file. |\n\nReturns: `Response`\n\nLegge il file `id` da `FILESTORAGE(name)` e lo invia con il content type salvato. `checkmeta(meta)` può esaminare i metadati del file prima che venga inviato.\n\nExample: File dallo storage\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nElabora un'immagine da un FileStorage e invia il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del FileStorage. |\n| `id` | `String|Number` | yes |  | L'ID del file. |\n| `make` | `Function(image, res)` | yes |  | Imposta le operazioni sull'immagine. |\n| `headers` | `Object` | yes |  | Header aggiuntivi. |\n| `callback` | `Function` | yes |  | Chiamata al termine. |\n| `checkmeta` | `Function(meta)` | yes |  | Controlla i metadati del file. |\n\nReturns: `Response`\n\nCome `res.filefs()`, ma `make(image, res)` imposta le operazioni sull'immagine come in `res.image()`.\n\nExample: Avatar dallo storage\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nInvia uno stream leggibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il content type. |\n| `stream` | `Stream` | yes |  | Uno stream leggibile. |\n| `download` | `String` | yes |  | Un nome per il download. |\n| `headers` | `Object` | yes |  | Header aggiuntivi. |\n| `callback` | `Function` | yes |  | Chiamata al termine. |\n| `nocompress` | `Boolean` | yes |  | Disattiva la compressione. |\n\nReturns: `Response`\n\nLo stream viene compresso con GZIP quando il content type può essere compresso e il client lo accetta, a meno che `nocompress` sia `true`.\n\nExample: Trasmettere un file in streaming\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nServe il file statico richiesto dalla directory public, come senza una route di file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Chiamata quando il file è stato inviato. |\n\nReturns: `Response`\n\nUsalo in una route di file o in un middleware che decide di non rispondere da sé alla richiesta. L'estensione deve essere in `static_accepts`; altrimenti, e quando il file non esiste, la risposta è 404 (o il gestore `FILE404()`). Applica anche `MAP()`, `MERGE()` e `RESIZE()`.\n\nExample: Servire solo agli utenti autenticati\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nServe un file generato da `/tmp/`, oppure ti chiede di crearlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Crea il file mancante. |\n\nIl nome del file in `/tmp/` viene costruito dall'URL della richiesta. Quando il file esiste, viene inviato e `callback` non viene chiamata. Altrimenti viene chiamata `callback(next, filename, req, res)`: scrivi il file in `filename`, invia la risposta (per esempio `res.file(filename)`) e chiama `next()`. Vengono generati al massimo 20 file contemporaneamente.\n\nExample: File generato\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nL'estensione di una richiesta di file statico, senza il punto.\n\nReturns: `String`\n\nImpostata per le richieste il cui percorso termina con un'estensione (`req.isStaticFile` è `true`).\n\nExample: Diramare in base all'estensione\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nServe i file statici attraverso il traduttore, oppure imposta la lingua delle richieste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Il pattern dell'URL, oppure la funzione della lingua. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` e flag di route come `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifica l'HTML. Predefinito `true`. |\n\n`LOCALIZE(url)` crea una route di file che legge i file sotto `url` da `public/`, sostituisce i marcatori `@(Text)` con le traduzioni nella lingua della richiesta e, in modalità release, mette in cache il risultato per lingua. L'HTML viene minificato quando `allow_compile_html` è attivo; il flag `nocompress` o `minify = false` lo disattiva.\n\nL'URL può terminare con un pattern di file come `/templates/*.html`. Senza un'estensione, vengono gestiti i file `.html`, `.htm`, `.md` e `.txt`; i flag `.ext` ne scelgono altri. Un URL che inizia con `#` è un ID della sitemap.\n\n`LOCALIZE(fn)` imposta la funzione `fn(req, res, isStaticFile)` che restituisce la lingua di una richiesta. I file statici `.html` e `.htm` da `public/` vengono localizzati automaticamente quando `allow_localize` è attivo.\n\nExample: Lingua e file\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nCrea al volo immagini ridimensionate per un URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un percorso URL, facoltativamente con `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Imposta le operazioni sull'immagine. |\n| `flags` | `String[]` | yes |  | Percorso o URL sorgente, `.ext`, `nocache`. |\n\nLe richieste di immagini sotto `url` vengono generate dalle immagini sorgente tramite `fn(image)` e messe in cache in `/tmp/`. Per impostazione predefinita la sorgente è lo stesso percorso in `public/`. In `flags`, un percorso (`/img/`, o `~/absolute/path/`) o un URL `http(s)://` indica dove si trovano le immagini sorgente, `.ext` aggiunge un'estensione e `nocache` disattiva la cache. JPG, JPEG, PNG, GIF, APNG, HEIF e HEIC sono sempre gestiti.\n\nExample: Immagini piccole da /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nServe un URL da un altro file o da un'altra directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL. |\n| `filename` | `String` | yes |  | Un file o una directory. |\n| `filter` | `String[]|Function` | yes |  | Filtra i file di una directory. |\n\nQuando `filename` ha un'estensione, l'URL viene mappato a quel file. Altrimenti è una directory e ogni file al suo interno viene mappato sotto `url`; `filter` è un array di estensioni o una funzione `(filename)` che restituisce `true` per i file da mappare.\n\nUn `filename` relativo viene cercato prima in `public/`. Prefissi: `~` per un percorso dalla radice dell'applicazione, `@` per un pacchetto, `=` per un tema. Un `url` che inizia con `#` è un ID della sitemap. Il file mappato viene comunque servito solo quando la sua estensione è consentita.\n\nExample: File e directory\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nServe più file come un unico file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL del file unito. |\n| `file1` | `String|String[]` | yes |  | File da unire, in ordine. |\n\nI file vengono uniti in un unico file salvato in `/tmp/`. Ogni argomento può essere un nome di file, un URL o un array. Un nome di file con `@` proviene da un pacchetto, con `=` da un tema. L'`url` segue il file `/versions`.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nConsente un'estensione per i file statici.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | Un'estensione, con o senza il punto. |\n| `type` | `String` | yes |  | Il content type. |\n\nAggiunge l'estensione a `static_accepts`. Con `type`, imposta anche il content type dell'estensione.\n\nExample: Modelli 3D\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nSvuota la cache dei file statici elaborati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un URL come `/css/default.css`. |\n\nIl framework ricorda ogni file elaborato (minificato, compresso o non trovato) in base al suo URL. `TOUCH(url)` dimentica un URL, così la richiesta successiva legge di nuovo il file; `TOUCH()` li dimentica tutti.\n\nExample: Dopo una modifica\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nRestituisce il percorso assoluto di un file nella directory public.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un nome di file relativo. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è impostata da `directory_public`.\n\nExample: Percorso\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nRestituisce l'URL di un file statico, con `static_url` e il file `/versions` applicati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome di file. |\n| `theme` | `String` | yes |  | Un nome di tema. |\n\nReturns: `String` Un URL.\n\nI nomi relativi ricevono il prefisso dell'helper: `F.public()` usa `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` e `F.public_download()` `static_url_download`. I nomi che iniziano con `/` non ricevono alcun prefisso. Un nome che inizia con `~` ignora il tema, `=theme/` seleziona un tema (`=?/` il tema predefinito). Con `default_root`, viene aggiunta la radice. Le viste usano gli stessi helper.\n\nExample: URL\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nRestituisce l'URL di uno script, con `static_url_script` come prefisso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome di file. |\n| `theme` | `String` | yes |  | Un nome di tema. |\n\nReturns: `String` Un URL.\n\nVedi `F.public()` per le regole.\n\nExample: Script\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nRestituisce l'URL di un foglio di stile, con `static_url_style` come prefisso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome di file. |\n| `theme` | `String` | yes |  | Un nome di tema. |\n\nReturns: `String` Un URL.\n\nVedi `F.public()` per le regole.\n\nExample: Foglio di stile\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nRestituisce l'URL di un'immagine, con `static_url_image` come prefisso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome di file. |\n| `theme` | `String` | yes |  | Un nome di tema. |\n\nReturns: `String` Un URL.\n\nVedi `F.public()` per le regole.\n\nExample: Immagine\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nLa directory con i file statici. Predefinita `/public/`.\n\nReturns: `String` '/public/'\n\nLe richieste di file statici vengono cercate qui. `PATH.public()` costruisce i percorsi al suo interno.\n\nExample: File di configurazione\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nIl prefisso degli URL generati da `F.public()`. Predefinito vuoto.\n\nReturns: `String` ''\n\nGli altri prefissi sono `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) e `static_url_download` (`/download/`). Cambiano solo gli URL generati; i file vengono comunque serviti dal loro percorso in `public/`. Un prefisso può essere un URL completo, per esempio di una CDN.\n\nExample: File di configurazione\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nIl prefisso degli URL generati da `F.public_js()`. Predefinito `/js/`.\n\nReturns: `String` '/js/'\n\nVedi `static_url`.\n\nExample: File di configurazione\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nLe estensioni che i file statici possono avere.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nI file statici con altre estensioni rispondono 404. La lista predefinita: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nNel file di configurazione, `static_accepts` **sostituisce** la lista, mentre `static_accepts_custom` vi aggiunge estensioni. Entrambi accettano una lista separata da virgole. Nel codice, usa `ACCEPT()`.\n\nExample: File di configurazione\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nAttiva o disattiva la gestione dei file statici. Predefinito `true`.\n\nReturns: `Boolean` true\n\nQuando è `false`, i percorsi con un'estensione vengono instradati come richieste normali e la directory public non viene servita.\n\nExample: File di configurazione\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nComprime i file statici con GZIP. Predefinito `true`.\n\nReturns: `Boolean` true\n\nSi applica ai tipi di testo: testo semplice, HTML, CSS, JavaScript, JSX, JSON, XML, SVG e Markdown, quando il client invia `Accept-Encoding: gzip`. La copia compressa viene salvata in `/tmp/`.\n\nExample: File di configurazione\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifica JavaScript, CSS e HTML statici. Predefinito `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript e `.mjs`), `allow_compile_style` (CSS) e `allow_compile_html` (HTML localizzato) attivano i singoli tipi; tutti sono predefiniti a `true`. I file con nomi come `*.min.js`, `*-min.css` o `*.min@version.js` non vengono minificati. Nel CSS, i valori `url()` seguono il file `/versions`.\n\nExample: File di configurazione\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLocalizza i file statici `.html` e `.htm`. Predefinito `true`.\n\nReturns: `Boolean` true\n\nI marcatori `@(Text)` nei file HTML da `public/` vengono tradotti nella lingua della richiesta impostata con `LOCALIZE(fn)`.\n\nExample: File di configurazione\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nSalva le immagini create da `res.image()` come file persistenti. Predefinito `true`.\n\nReturns: `Boolean` true\n\nIl valore predefinito per l'argomento `persistent` di `res.image()`.\n\nExample: File di configurazione\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nUn valore aggiunto all'`ETag` dei file statici.\n\nReturns: `String` ''\n\nQuando è vuoto, all'avvio viene impostato da `version` (senza punti e spazi). Cambia `version` o `etag_version` per far scaricare di nuovo ai browser i file modificati.\n\nExample: File di configurazione\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nUn prefisso di URL quando l'applicazione gira sotto un sotto-percorso.\n\nReturns: `String` ''\n\nCon `default_root : /app/`, gli URL statici generati da `F.public()` e dalle viste iniziano con `/app/`, e il file `/versions` viene applicato con questo prefisso.\n\nExample: File di configurazione\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nIl file `/versions` nella radice dell'applicazione mappa gli URL dei file a URL con versione.\n\nReturns: `File`\n\nOgni riga è `url : newurl`. Il valore `auto` aggiunge al nome, all'avvio, un hash del contenuto del file (`/js/app.js` diventa `/js/app-<hash>.js`). Con `-->` al posto di `:`, anche il nuovo URL viene mappato al file originale. Le righe che iniziano con `#` o `// ` sono commenti. Gli helper `F.public_*()`, `MERGE()` e le viste usano i nuovi URL.\n\nExample: File di configurazione\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nModifica il contenuto di viste, stili e script prima che vengano compilati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un percorso relativo all'app, ad esempio `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)` che restituisce il nuovo contenuto. |\n\nLa funzione viene chiamata con `(type, filename, value, controller)`, dove `type` è `'view'`, `'style'`, `'script'` o `'static'` (un file statico localizzato da Total.js) e `filename` è il percorso relativo all'app con una `/` iniziale. Restituisci il nuovo contenuto; un risultato falsy lo lascia com'era.\n\nCon `filename` (ad esempio `'/views/index.html'`) la funzione viene eseguita solo per quel file. La modifica avviene in memoria, il file su disco resta com'è. In modalità release il contenuto compilato viene messo in cache, quindi la funzione viene eseguita una volta per file. Una funzione registrata da un plugin o da un modulo viene rimossa quando questo viene disinstallato.\n\nExample: Aggiungere un banner a ogni vista\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: Un solo file\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JafjoZ2pX60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/static-files/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Statické súbory","summary":"Súborové trasy, metódy odpovede pre súbory a pomocné funkcie a konfigurácia statických súborov.","markdown":"---\ntitle: \"Statické súbory\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/static-files/\nupdated: 2026-11-18T16:57:34.578Z\n---\n\n# Statické súbory\n\n> Súborové trasy, metódy odpovede pre súbory a pomocné funkcie a konfigurácia statických súborov.\n\n## API\n\n### FILE(url, action, [flags])\n\nType: `method`\n\nVytvorí súborovú trasu; volá ju `ROUTE('FILE /url/*.ext', action, [flags])`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Vzor URL alebo funkcia `(req, res)` vracajúca `true`. |\n| `action` | `Function(req, res)|String` | yes |  | Obsluha, názov súboru alebo URL. |\n| `flags` | `Array` | yes |  | `#middleware`, `.ext`, `id:name`, objekt možností. |\n\nSúborová trasa obsluhuje požiadavky na statické súbory (cesty, ktoré končia príponou) skôr, než framework hľadá v `public/`. Vyhráva prvá zhodná trasa; dlhšie URL sa testujú ako prvé.\n\nTvary `url`:\n\n| URL | Zhoduje sa s |\n| --- | --- |\n| `/photos/*.jpg` | súbory `.jpg` pod `/photos/` |\n| `/photos/*` alebo `/photos/*.*` | ľubovoľný súbor pod `/photos/` |\n| `/favicon.ico` | presne týmto súborom |\n\n`action` je `function(req, res)`. Môže to byť aj reťazec: absolútny názov súboru, ktorý sa pošle pomocou `res.file()`, alebo URL `http://`/`https://`, ktorej odpoveď sa streamuje. Namiesto URL môžeš odovzdať funkciu `function(req, res)`, ktorá vráti `true` pre požiadavky, ktoré sa majú obslúžiť.\n\nFlagy: `#name` pridá middleware, `.ext` obmedzí prípony, `id:name` nastaví ID trasy a objekt sa v middlewari stane `$.options`. Pri súborových trasách vkladaj middleware do poľa flagov, nie priamo do URL. Keď akcia sama neodpovie, zavolaj `res.continue()`, aby sa súbor obslúžil z `public/`.\n\nExample: Chránené sťahovanie\n```js\nexports.install = function() {\n\tROUTE('FILE /docs/*.pdf', function(req, res) {\n\t\tres.file(PATH.root('documents/' + U.getName(req.uri.pathname)));\n\t}, ['#auth']);\n};\n```\n\nExample: Pevný súbor\n```js\nROUTE('FILE /robots.txt', PATH.root('robots.txt'));\n```\n\nExample: Overovacia funkcia\n```js\nFILE(function(req, res) {\n\treturn req.uri.pathname.startsWith('/uploads/');\n}, function(req, res) {\n\tres.continue();\n}, ['#auth']);\n```\n\n### FILE404(fn)\n\nType: `method`\n\nNastaví obsluhu pre statické súbory, ktoré neexistujú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(req, res)` | yes |  | Obsluha. |\n\n`fn(req, res)` sa zavolá namiesto odpovede 404 pre statické súbory, ktoré chýbajú, nie sú povolené v `static_accepts` alebo ich nenašla `res.file()`. Vráť `true`, keď si na požiadavku odpovedal; inak framework odpovie 404.\n\nExample: Zástupný obrázok\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'jpg' || req.extension === 'png') {\n\t\tres.file(PATH.public('img/placeholder.png'));\n\t\treturn true;\n\t}\n});\n```\n\n### res.file(filename, [download], [headers], [callback])\n\nType: `method`\n\nPošle súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Absolútna cesta. |\n| `download` | `String|Boolean` | yes |  | Názov na stiahnutie alebo `true` pre názov súboru. |\n| `headers` | `Object` | yes |  | Ďalšie hlavičky. |\n| `callback` | `Function` | yes |  | Volá sa po odoslaní súboru. |\n\nReturns: `Response`\n\n`filename` je absolútna cesta; úvodné `@` znamená súbor balíka. Typ obsahu sa určí podľa prípony požiadavky (alebo súboru). Súbor dostane rovnaké cachovanie, GZIP kompresiu, podporu `Range` a spracovanie `304 Not Modified` ako súbory v `public/`. Súbory `.html` sa lokalizujú, keď je zapnuté `allow_localize`.\n\n`download` pridá `Content-Disposition: attachment` s týmto názvom súboru; `true` použije názov súboru. V režime release si framework pamätá súbor každej URL; keď sa zmení, zavolaj `TOUCH(url)`.\n\nExample: Stiahnutie\n```js\nROUTE('FILE /invoices/*.pdf', function(req, res) {\n\tvar name = U.getName(req.uri.pathname);\n\tres.file(PATH.databases('invoices/' + name), 'invoice.pdf');\n});\n```\n\n### res.image(filename, make, [headers], [callback], [persistent])\n\nType: `method`\n\nSpracuje obrázok pomocou GraphicsMagick alebo ImageMagick a pošle výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Zdrojový obrázok. |\n| `make` | `Function(image, res)` | yes |  | Nastaví operácie s obrázkom. |\n| `headers` | `Object` | yes |  | Ďalšie hlavičky. |\n| `callback` | `Function` | yes |  | Volá sa po odoslaní obrázka. |\n| `persistent` | `Boolean` | yes |  | Uloží výsledok ako trvalý súbor. |\n\nReturns: `Response`\n\n`filename` je absolútna cesta alebo čitateľný stream. `make(image, res)` dostane objekt obrázka a nastaví operácie (`resize()`, `crop()`, `quality()`, `grayscale()`, `output()`...). Výsledok sa uloží do `/tmp/` pod URL požiadavky a ďalšie požiadavky dostanú uložený súbor.\n\n`persistent` uloží výsledok ako trvalý súbor (prefix `timg_` v `/tmp/`) a opakovane ho používa, kým existuje; keď ho vynecháš, riadi sa podľa `allow_persistent_images` (predvolene `true`). `res.image_nocache(filename, make, [headers], [callback])` robí to isté bez cache.\n\nExample: Náhľady\n```js\nROUTE('FILE /thumbnails/*.jpg', function(req, res) {\n\tres.image(PATH.public('photos/' + U.getName(req.uri.pathname)), function(image) {\n\t\timage.resize(150, 150);\n\t\timage.quality(80);\n\t});\n});\n```\n\n### res.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nPošle súbor z FileStorage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov FileStorage. |\n| `id` | `String|Number` | yes |  | ID súboru. |\n| `download` | `String` | yes |  | Názov na stiahnutie. |\n| `headers` | `Object` | yes |  | Ďalšie hlavičky. |\n| `callback` | `Function` | yes |  | Volá sa po dokončení. |\n| `checkmeta` | `Function(meta)` | yes |  | Skontroluje metadáta súboru. |\n\nReturns: `Response`\n\nPrečíta súbor `id` z `FILESTORAGE(name)` a pošle ho s jeho uloženým typom obsahu. `checkmeta(meta)` môže pred odoslaním skontrolovať metadáta súboru.\n\nExample: Súbory z úložiska\n```js\nROUTE('FILE /files/*.*', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace(/\\..*$/, '');\n\tres.filefs('files', id);\n});\n```\n\n### res.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nSpracuje obrázok z FileStorage a pošle výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov FileStorage. |\n| `id` | `String|Number` | yes |  | ID súboru. |\n| `make` | `Function(image, res)` | yes |  | Nastaví operácie s obrázkom. |\n| `headers` | `Object` | yes |  | Ďalšie hlavičky. |\n| `callback` | `Function` | yes |  | Volá sa po dokončení. |\n| `checkmeta` | `Function(meta)` | yes |  | Skontroluje metadáta súboru. |\n\nReturns: `Response`\n\nAko `res.filefs()`, ale `make(image, res)` nastaví operácie s obrázkom ako v `res.image()`.\n\nExample: Avatary z úložiska\n```js\nROUTE('FILE /avatars/*.jpg', function(req, res) {\n\tvar id = U.getName(req.uri.pathname).replace('.jpg', '');\n\tres.imagefs('avatars', id, function(image) {\n\t\timage.resize(100, 100);\n\t});\n});\n```\n\n### res.stream(type, stream, [download], [headers], [callback], [nocompress])\n\nType: `method`\n\nPošle čitateľný stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Typ obsahu. |\n| `stream` | `Stream` | yes |  | Čitateľný stream. |\n| `download` | `String` | yes |  | Názov na stiahnutie. |\n| `headers` | `Object` | yes |  | Ďalšie hlavičky. |\n| `callback` | `Function` | yes |  | Volá sa po dokončení. |\n| `nocompress` | `Boolean` | yes |  | Vypne kompresiu. |\n\nReturns: `Response`\n\nStream sa komprimuje pomocou GZIP, keď sa typ obsahu dá komprimovať a klient to akceptuje, pokiaľ `nocompress` nie je `true`.\n\nExample: Streamovanie súboru\n```js\nROUTE('FILE /logs/*.txt', function(req, res) {\n\tvar stream = require('fs').createReadStream(PATH.logs(U.getName(req.uri.pathname)));\n\tres.stream('text/plain', stream);\n}, ['#admin']);\n```\n\n### res.continue([callback])\n\nType: `method`\n\nObslúži požadovaný statický súbor z verejného priečinka, ako keby súborová trasa neexistovala.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Volá sa po odoslaní súboru. |\n\nReturns: `Response`\n\nPouži ju v súborovej trase alebo v middlewari, ktorý sa rozhodne na požiadavku neodpovedať sám. Prípona musí byť v `static_accepts`; inak, a aj keď súbor neexistuje, je odpoveď 404 (alebo obsluha `FILE404()`). Uplatňuje aj `MAP()`, `MERGE()` a `RESIZE()`.\n\nExample: Obsluha len pre prihlásených používateľov\n```js\nROUTE('FILE /private/*.*', function(req, res) {\n\tif (req.user)\n\t\tres.continue();\n\telse\n\t\tres.throw401();\n});\n```\n\n### req.filecache(callback)\n\nType: `method`\n\nObslúži vygenerovaný súbor z `/tmp/` alebo ťa požiada o jeho vytvorenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(next, filename, req, res)` | yes |  | Vytvorí chýbajúci súbor. |\n\nNázov súboru v `/tmp/` sa zostaví z URL požiadavky. Keď súbor existuje, pošle sa a `callback` sa nezavolá. Inak sa zavolá `callback(next, filename, req, res)`: zapíš súbor do `filename`, pošli odpoveď (napríklad `res.file(filename)`) a zavolaj `next()`. Naraz sa generuje najviac 20 súborov.\n\nExample: Vygenerovaný súbor\n```js\nROUTE('FILE /reports/*.csv', function(req, res) {\n\treq.filecache(function(next, filename) {\n\t\trequire('fs').writeFile(filename, 'id;name\\n1;Peter\\n', function() {\n\t\t\tres.file(filename);\n\t\t\tnext();\n\t\t});\n\t});\n});\n```\n\n### req.extension\n\nType: `property`\n\nPrípona požiadavky na statický súbor, bez bodky.\n\nReturns: `String`\n\nNastavená pre požiadavky, ktorých cesta končí príponou (`req.isStaticFile` je `true`).\n\nExample: Vetvenie podľa prípony\n```js\nFILE404(function(req, res) {\n\tif (req.extension === 'svg') {\n\t\tres.send(200, '<svg xmlns=\"http://www.w3.org/2000/svg\"/>', 'image/svg+xml');\n\t\treturn true;\n\t}\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nObsluhuje statické súbory cez prekladač alebo nastavuje jazyk požiadaviek.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Function` | yes |  | Vzor URL alebo funkcia jazyka. |\n| `flags` | `String[]` | yes |  | `nocompress`, `.ext` a flagy trasy ako `#middleware`. |\n| `minify` | `Boolean` | yes |  | Minifikuje HTML. Predvolene `true`. |\n\n`LOCALIZE(url)` vytvorí súborovú trasu, ktorá číta súbory pod `url` z `public/`, nahrádza značky `@(Text)` prekladmi v jazyku požiadavky a v režime release cachuje výsledok pre každý jazyk. HTML sa minifikuje, keď je zapnuté `allow_compile_html`; flag `nocompress` alebo `minify = false` to vypne.\n\nURL môže končiť vzorom súborov, napríklad `/templates/*.html`. Bez prípony sa obsluhujú súbory `.html`, `.htm`, `.md` a `.txt`; flagy `.ext` vyberú iné. URL začínajúca znakom `#` je ID sitemapy.\n\n`LOCALIZE(fn)` nastaví funkciu `fn(req, res, isStaticFile)`, ktorá vráti jazyk požiadavky. Statické súbory `.html` a `.htm` z `public/` sa lokalizujú automaticky, keď je zapnuté `allow_localize`.\n\nExample: Jazyk a súbory\n```js\nLOCALIZE(function(req, res) {\n\treturn (req.headers['accept-language'] || 'en').substring(0, 2);\n});\n\nLOCALIZE('/templates/*.html');\nLOCALIZE('/texts/*.md', ['nocompress']);\n```\n\n### RESIZE(url, fn, [flags])\n\nType: `method`\n\nVytvára obrázky so zmenenou veľkosťou za behu pre URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cesta URL, voliteľne s `*.ext`. |\n| `fn` | `Function(image)` | yes |  | Nastaví operácie s obrázkom. |\n| `flags` | `String[]` | yes |  | Zdrojová cesta alebo URL, `.ext`, `nocache`. |\n\nPožiadavky na obrázky pod `url` sa vytvoria zo zdrojových obrázkov pomocou `fn(image)` a cachujú sa v `/tmp/`. Predvolene je zdrojom rovnaká cesta v `public/`. Vo `flags` cesta (`/img/` alebo `~/absolute/path/`) alebo URL `http(s)://` určuje, kde sú zdrojové obrázky, `.ext` pridá príponu a `nocache` vypne cache. JPG, JPEG, PNG, GIF, APNG, HEIF a HEIC sa obsluhujú vždy.\n\nExample: Malé obrázky z /public/img/\n```js\nRESIZE('/img/small/*.jpg', function(image) {\n\timage.resize(200, 200);\n\timage.quality(80);\n}, ['/img/']);\n```\n\n### MAP(url, filename, [filter])\n\nType: `method`\n\nObslúži URL z iného súboru alebo priečinka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `filename` | `String` | yes |  | Súbor alebo priečinok. |\n| `filter` | `String[]|Function` | yes |  | Filtruje súbory priečinka. |\n\nKeď má `filename` príponu, URL sa namapuje na tento súbor. Inak je to priečinok a každý súbor v ňom sa namapuje pod `url`; `filter` je pole prípon alebo funkcia `(filename)`, ktorá vráti `true` pre súbory na namapovanie.\n\nRelatívny `filename` sa najprv hľadá v `public/`. Prefixy: `~` pre cestu od koreňa aplikácie, `@` pre balík, `=` pre tému. `url` začínajúca znakom `#` je ID sitemapy. Namapovaný súbor sa aj tak obslúži len vtedy, keď je jeho prípona povolená.\n\nExample: Súbor a priečinok\n```js\nMAP('/favicon.ico', '/img/favicon.ico');\nMAP('/manuals/', '/files/manuals/', ['.pdf']);\n```\n\n### MERGE(url, file1, [file2], [fileN])\n\nType: `method`\n\nObslúži niekoľko súborov ako jeden súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL spojeného súboru. |\n| `file1` | `String|String[]` | yes |  | Súbory na spojenie, v poradí. |\n\nSúbory sa spoja do jedného súboru uloženého v `/tmp/`. Každý argument môže byť názov súboru, URL alebo pole. Názov súboru s `@` je z balíka, s `=` z témy. `url` sa riadi súborom `/versions`.\n\nExample: Bundle\n```js\nMERGE('/js/bundle.js', '/js/jquery.js', '/js/app.js');\nMERGE('/css/bundle.css', ['/css/base.css', '/css/theme.css']);\n```\n\n### ACCEPT(extension, [type])\n\nType: `method`\n\nPovolí príponu pre statické súbory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `extension` | `String` | yes |  | Prípona, s bodkou alebo bez nej. |\n| `type` | `String` | yes |  | Typ obsahu. |\n\nPridá príponu do `static_accepts`. S `type` nastaví aj typ obsahu prípony.\n\nExample: 3D modely\n```js\nACCEPT('.glb', 'model/gltf-binary');\n```\n\n### TOUCH([url])\n\nType: `method`\n\nVymaže cache spracovaných statických súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL, napríklad `/css/default.css`. |\n\nFramework si pamätá každý spracovaný súbor (minifikovaný, komprimovaný alebo nenájdený) podľa jeho URL. `TOUCH(url)` zabudne jednu URL, takže ďalšia požiadavka súbor načíta znova; `TOUCH()` zabudne všetky.\n\nExample: Po zmene\n```js\nrequire('fs').writeFile(PATH.public('css/theme.css'), css, function() {\n\tTOUCH('/css/theme.css');\n});\n```\n\n### PATH.public([filename])\n\nType: `method`\n\nVráti absolútnu cestu k súboru vo verejnom priečinku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Relatívny názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nPriečinok nastavuje `directory_public`.\n\nExample: Cesta\n```js\nvar filename = PATH.public('img/logo.png');\n```\n\n### F.public(name, [theme])\n\nType: `method`\n\nVráti URL statického súboru s uplatnením `static_url` a súboru `/versions`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru. |\n| `theme` | `String` | yes |  | Názov témy. |\n\nReturns: `String` URL.\n\nRelatívne názvy dostanú prefix pomocnej funkcie: `F.public()` používa `static_url`, `F.public_js()` `static_url_script`, `F.public_css()` `static_url_style`, `F.public_image()` `static_url_image`, `F.public_video()` `static_url_video`, `F.public_font()` `static_url_font` a `F.public_download()` `static_url_download`. Názvy začínajúce znakom `/` nedostanú žiadny prefix. Názov začínajúci znakom `~` ignoruje tému, `=theme/` vyberie tému (`=?/` predvolenú tému). S `default_root` sa pridá koreň. View používajú rovnaké pomocné funkcie.\n\nExample: URL\n```js\nF.public('/robots.txt');       // /robots.txt\nF.public_font('icons.woff2');   // /fonts/icons.woff2\nF.public_download('manual.pdf');  // /download/manual.pdf\n```\n\n### F.public_js(name, [theme])\n\nType: `method`\n\nVráti URL skriptu s `static_url_script` ako prefixom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru. |\n| `theme` | `String` | yes |  | Názov témy. |\n\nReturns: `String` URL.\n\nPravidlá nájdeš pri `F.public()`.\n\nExample: Skript\n```js\nF.public_js('app.js'); // /js/app.js\n```\n\n### F.public_css(name, [theme])\n\nType: `method`\n\nVráti URL štýlu s `static_url_style` ako prefixom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru. |\n| `theme` | `String` | yes |  | Názov témy. |\n\nReturns: `String` URL.\n\nPravidlá nájdeš pri `F.public()`.\n\nExample: Štýl\n```js\nF.public_css('default.css'); // /css/default.css\n```\n\n### F.public_image(name, [theme])\n\nType: `method`\n\nVráti URL obrázka s `static_url_image` ako prefixom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru. |\n| `theme` | `String` | yes |  | Názov témy. |\n\nReturns: `String` URL.\n\nPravidlá nájdeš pri `F.public()`.\n\nExample: Obrázok\n```js\nF.public_image('logo.png'); // /img/logo.png\n```\n\n### directory_public\n\nType: `config`\n\nPriečinok so statickými súbormi. Predvolene `/public/`.\n\nReturns: `String` '/public/'\n\nTu sa hľadajú požiadavky na statické súbory. `PATH.public()` zostavuje cesty doň.\n\nExample: Konfiguračný súbor\n```text\ndirectory_public : /www/\n```\n\n### static_url\n\nType: `config`\n\nPrefix URL vytváraných pomocou `F.public()`. Predvolene prázdny.\n\nReturns: `String` ''\n\nOstatné prefixy sú `static_url_script` (`/js/`), `static_url_style` (`/css/`), `static_url_image` (`/img/`), `static_url_video` (`/videos/`), `static_url_font` (`/fonts/`) a `static_url_download` (`/download/`). Menia len generované URL; súbory sa stále obsluhujú zo svojej cesty v `public/`. Prefix môže byť celá URL, napríklad CDN.\n\nExample: Konfiguračný súbor\n```text\nstatic_url_image : https://cdn.example.com/img/\n```\n\n### static_url_script\n\nType: `config`\n\nPrefix URL vytváraných pomocou `F.public_js()`. Predvolene `/js/`.\n\nReturns: `String` '/js/'\n\nPozri `static_url`.\n\nExample: Konfiguračný súbor\n```text\nstatic_url_script : /scripts/\n```\n\n### static_accepts\n\nType: `config`\n\nPrípony, ktoré môžu mať statické súbory.\n\nReturns: `Object` flac, jpg, jpeg, png, gif, ico, wasm, js, mjs, css, txt, xml, ...\n\nStatické súbory s inými príponami odpovedajú 404. Predvolený zoznam: `flac`, `jpg`, `jpeg`, `png`, `gif`, `ico`, `wasm`, `js`, `mjs`, `css`, `txt`, `xml`, `woff`, `woff2`, `otf`, `ttf`, `eot`, `svg`, `zip`, `rar`, `pdf`, `docx`, `xlsx`, `doc`, `xls`, `html`, `htm`, `appcache`, `manifest`, `map`, `ogv`, `ogg`, `mp4`, `mp3`, `webp`, `webm`, `swf`, `package`, `json`, `ui`, `md`, `m4v`, `jsx`, `heif`, `heic`, `ics`, `ts`, `m3u8`, `wav`, `xslt`, `xsd`.\n\nV konfiguračnom súbore `static_accepts` zoznam **nahradí**, zatiaľ čo `static_accepts_custom` do neho prípony pridá. Oba prijímajú zoznam oddelený čiarkami. V kóde použi `ACCEPT()`.\n\nExample: Konfiguračný súbor\n```text\nstatic_accepts_custom : glb, usdz\n```\n\n### allow_static_files\n\nType: `config`\n\nZapne alebo vypne obsluhu statických súborov. Predvolene `true`.\n\nReturns: `Boolean` true\n\nKeď je `false`, cesty s príponou sa smerujú ako bežné požiadavky a verejný priečinok sa neobsluhuje.\n\nExample: Konfiguračný súbor\n```text\nallow_static_files : false\n```\n\n### allow_gzip\n\nType: `config`\n\nKomprimuje statické súbory pomocou GZIP. Predvolene `true`.\n\nReturns: `Boolean` true\n\nPlatí pre textové typy: obyčajný text, HTML, CSS, JavaScript, JSX, JSON, XML, SVG a Markdown, keď klient pošle `Accept-Encoding: gzip`. Komprimovaná kópia sa uloží do `/tmp/`.\n\nExample: Konfiguračný súbor\n```text\nallow_gzip : false\n```\n\n### allow_compile\n\nType: `config`\n\nMinifikuje statický JavaScript, CSS a HTML. Predvolene `true`.\n\nReturns: `Boolean` true\n\n`allow_compile_script` (JavaScript a `.mjs`), `allow_compile_style` (CSS) a `allow_compile_html` (lokalizované HTML) prepínajú jednotlivé typy; všetky majú predvolene `true`. Súbory s názvom ako `*.min.js`, `*-min.css` alebo `*.min@version.js` sa neminifikujú. V CSS sa hodnoty `url()` riadia súborom `/versions`.\n\nExample: Konfiguračný súbor\n```text\nallow_compile_script : false\n```\n\n### allow_localize\n\nType: `config`\n\nLokalizuje statické súbory `.html` a `.htm`. Predvolene `true`.\n\nReturns: `Boolean` true\n\nZnačky `@(Text)` v HTML súboroch z `public/` sa preložia do jazyka požiadavky nastaveného pomocou `LOCALIZE(fn)`.\n\nExample: Konfiguračný súbor\n```text\nallow_localize : false\n```\n\n### allow_persistent_images\n\nType: `config`\n\nUkladá obrázky vytvorené pomocou `res.image()` ako trvalé súbory. Predvolene `true`.\n\nReturns: `Boolean` true\n\nPredvolená hodnota argumentu `persistent` metódy `res.image()`.\n\nExample: Konfiguračný súbor\n```text\nallow_persistent_images : false\n```\n\n### etag_version\n\nType: `config`\n\nHodnota pridávaná do `ETag` statických súborov.\n\nReturns: `String` ''\n\nKeď je prázdna, nastaví sa pri štarte z `version` (bez bodiek a medzier). Zmeň `version` alebo `etag_version`, aby prehliadače zmenené súbory stiahli znova.\n\nExample: Konfiguračný súbor\n```text\netag_version : 2\n```\n\n### default_root\n\nType: `config`\n\nPrefix URL, keď aplikácia beží pod podcestou.\n\nReturns: `String` ''\n\nS `default_root : /app/` začínajú statické URL vytvorené pomocou `F.public()` a view na `/app/` a súbor `/versions` sa uplatní s týmto prefixom.\n\nExample: Konfiguračný súbor\n```text\ndefault_root : /app/\n```\n\n### versions\n\nType: `config`\n\nSúbor `/versions` v koreni aplikácie mapuje URL súborov na verzované URL.\n\nReturns: `File`\n\nKaždý riadok má tvar `url : newurl`. Hodnota `auto` pridá pri štarte k názvu hash obsahu súboru (`/js/app.js` sa zmení na `/js/app-<hash>.js`). S `-->` namiesto `:` sa nová URL namapuje aj na pôvodný súbor. Riadky začínajúce na `#` alebo `// ` sú komentáre. Pomocné funkcie `F.public_*()`, `MERGE()` a view používajú nové URL.\n\nExample: Konfiguračný súbor\n```text\n/js/app.js     : /js/app-2.js\n/css/style.css : auto\n/img/logo.png  --> /img/logo-2023.png\n```\n\n### MODIFY([filename], fn)\n\nType: `method`\n\nMení obsah view, štýlov a skriptov pred ich kompiláciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Cesta relatívna k aplikácii, napríklad `'/views/index.html'`. |\n| `fn` | `Function` | yes |  | `function(type, filename, value, controller)`, ktorá vráti nový obsah. |\n\nFunkcia sa volá s `(type, filename, value, controller)`, kde `type` je `'view'`, `'style'`, `'script'` alebo `'static'` (statický súbor lokalizovaný cez Total.js) a `filename` je cesta relatívna k aplikácii s úvodným `/`. Vráť nový obsah; nepravdivý výsledok ho ponechá tak, ako bol.\n\nS `filename` (napríklad `'/views/index.html'`) sa funkcia spustí iba pre daný súbor. Zmena sa robí v pamäti, súbor na disku zostáva taký, aký je. V režime release sa skompilovaný obsah ukladá do cache, takže funkcia sa spustí raz pre každý súbor. Funkcia zaregistrovaná pluginom alebo modulom sa odstráni pri jeho odinštalovaní.\n\nExample: Pridanie banneru do každého view\n```js\nMODIFY(function(type, filename, value) {\n\tif (type === 'view')\n\t\treturn value.replace('</body>', '<div class=\"banner\">Beta</div></body>');\n});\n```\n\nExample: Iba jeden súbor\n```js\nMODIFY('/views/index.html', function(type, filename, value) {\n\treturn value.replace('@@VERSION@@', CONF.version);\n});\n```\n","entries":[{"type":"method","name":"FILE()","signature":"FILE(url, action, [flags])","since":"","deprecated":false},{"type":"method","name":"FILE404()","signature":"FILE404(fn)","since":"","deprecated":false},{"type":"method","name":"res.file()","signature":"res.file(filename, [download], [headers], [callback])","since":"","deprecated":false},{"type":"method","name":"res.image()","signature":"res.image(filename, make, [headers], [callback], [persistent])","since":"","deprecated":false},{"type":"method","name":"res.filefs()","signature":"res.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.imagefs()","signature":"res.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"res.stream()","signature":"res.stream(type, stream, [download], [headers], [callback], [nocompress])","since":"","deprecated":false},{"type":"method","name":"res.continue()","signature":"res.continue([callback])","since":"","deprecated":false},{"type":"method","name":"req.filecache()","signature":"req.filecache(callback)","since":"","deprecated":false},{"type":"property","name":"req.extension","signature":"req.extension","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"method","name":"RESIZE()","signature":"RESIZE(url, fn, [flags])","since":"","deprecated":false},{"type":"method","name":"MAP()","signature":"MAP(url, filename, [filter])","since":"","deprecated":false},{"type":"method","name":"MERGE()","signature":"MERGE(url, file1, [file2], [fileN])","since":"","deprecated":false},{"type":"method","name":"ACCEPT()","signature":"ACCEPT(extension, [type])","since":"","deprecated":false},{"type":"method","name":"TOUCH()","signature":"TOUCH([url])","since":"","deprecated":false},{"type":"method","name":"PATH.public()","signature":"PATH.public([filename])","since":"","deprecated":false},{"type":"method","name":"F.public()","signature":"F.public(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_js()","signature":"F.public_js(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_css()","signature":"F.public_css(name, [theme])","since":"","deprecated":false},{"type":"method","name":"F.public_image()","signature":"F.public_image(name, [theme])","since":"","deprecated":false},{"type":"config","name":"directory_public","signature":"directory_public","since":"","deprecated":false},{"type":"config","name":"static_url","signature":"static_url","since":"","deprecated":false},{"type":"config","name":"static_url_script","signature":"static_url_script","since":"","deprecated":false},{"type":"config","name":"static_accepts","signature":"static_accepts","since":"","deprecated":false},{"type":"config","name":"allow_static_files","signature":"allow_static_files","since":"","deprecated":false},{"type":"config","name":"allow_gzip","signature":"allow_gzip","since":"","deprecated":false},{"type":"config","name":"allow_compile","signature":"allow_compile","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize","since":"","deprecated":false},{"type":"config","name":"allow_persistent_images","signature":"allow_persistent_images","since":"","deprecated":false},{"type":"config","name":"etag_version","signature":"etag_version","since":"","deprecated":false},{"type":"config","name":"default_root","signature":"default_root","since":"","deprecated":false},{"type":"config","name":"versions","signature":"versions","since":"","deprecated":false},{"type":"method","name":"MODIFY()","signature":"MODIFY([filename], fn)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:34.578Z"}
{"id":"JabWc91e361f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"WebSockets","summary":"The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSockets\n\n> The SOCKET route, the WebSocket controller, the connected client and WEBSOCKETCLIENT().\n\nA `SOCKET` route creates a WebSocket controller shared by all clients of a URL; each connection is a client object, and `WEBSOCKETCLIENT()` connects from the server to other WebSocket servers. The guide [WebSockets](../../guides/websockets/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDeclares a WebSocket route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, optionally with `+`/`-`, `{params}` and `@apiname` |\n| `action` | `Function` | yes |  | Initializes the WebSocket controller |\n| `flags` | `Array` | yes |  | Flags, origins, protocols, middleware, a length or an options object |\n| `length` | `Number` | yes |  | Maximum message size in kB |\n\nReturns: `FrameworkRoute` The route instance\n\nThe URL starts with `SOCKET` (or `WS`, `WSS`). A `+` or `-` before it limits the route to signed-in or anonymous users. `action` runs once, when the first client connects to the URL, with the WebSocket controller as `this` and the dynamic URL parameters as arguments. `length` is the maximum size of one message in kB (default `CONF.default_websocket_maxlength`, `2`). With `@name` in the URL and no action, the route processes the WebSocket API `@name` and destroys itself when the last client leaves.\n\nThe flags are described in the entry **WebSocket route flags**.\n\nExample: Chat route\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: WebSocket API without an action\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlags that set the data type, access, origins and protocols of a WebSocket route.\n\n- `json` (default): incoming messages are parsed as JSON (invalid JSON is ignored) and outgoing objects are serialized.\n- `text`, `plain`: messages are strings; objects you send are serialized as JSON.\n- `binary`: messages are `Buffer` objects.\n- `raw`: turns off `json` and `binary` (text mode).\n- `buffer`: the `message` event always receives the raw `Buffer`.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: signed-in or anonymous users only.\n- `@role`: a role flag; it makes the route `authorize`.\n- `http://...`, `https://...`: allowed origins; the request `Origin` must contain one of them.\n- `#middleware`, `&middleware`: middleware names.\n- `id:name`: the route identifier.\n- `get`, `csrf`, `http`, `https`, `debug`, `release`: standard route flags.\n- Any other word is a required sub-protocol. Every listed protocol must be in the client's `Sec-WebSocket-Protocol` header, otherwise the connection is closed with `4001`.\n- A number is the maximum message size in kB; an object is the middleware options.\n\nExample: Binary route for one origin\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Required sub-protocol\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nThe number of connected clients.\n\nReturns: `Number`\n\nUpdated whenever a client connects or disconnects.\n\nExample: Broadcast the count\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nAll connected clients by their id.\n\nReturns: `Object`\n\nAn object whose keys are client ids and values are client objects. `websocket.keys` holds the same ids as an array. `websocket.id` is the key of the controller in `F.connections`: the URL followed by `#` and the route flags.\n\nExample: Read a client\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nThe URL of the connection.\n\nReturns: `String`\n\nThe path the first client connected to, with a trailing slash.\n\n### websocket.params\n\nType: `property`\n\nThe dynamic parameters of the URL.\n\nReturns: `Object`\n\nEach `{name}` of the route becomes a key. The same values arrive as arguments of the action.\n\nExample: Room name\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nAn object for your own data.\n\nReturns: `Object`\n\nCreated on first access and kept for the life of the controller.\n\nExample: Keep history\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nRegisters an event handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Event name |\n| `callback` | `Function` | yes |  | Handler |\n\nReturns: `WebSocket` The controller\n\nEvents: `open`, `close`, `message`, `error` and `destroy`. `this` in the handler is the controller. `once(name, fn)` registers a handler for one call, `removeListener(name, fn)` and `removeAllListeners([name])` remove handlers, and `emit(name, [args...])` calls the handlers of your own events.\n\nExample: Events\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nSends a message to all clients or to the clients you select.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | The message |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` returns `true` to send |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer |\n| `params` | `Object` | yes |  | Value passed to `comparer` |\n\nReturns: `WebSocket`\n\nIn a `json` route the message is serialized once and sent to every client. `comparer(client, message, params)` returns `true` for the clients that receive the message. `replacer` is passed to `JSON.stringify()`; `true` uses the framework's JSON replacer. When the third argument is not a function, it is used as `params`.\n\nExample: Everybody except the sender\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: With params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nFinds the first client that matches a function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` returns `true` for the wanted client |\n\nReturns: `Object` The client or `undefined`\n\nReturns `undefined` when no client matches.\n\nExample: Find a user\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nReturns all connected clients as an array.\n\nReturns: `Array`\n\nExample: List users\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nCloses all connected clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Close reason |\n| `code` | `Number` | yes |  | Close code, default `1000` |\n\nReturns: `WebSocket`\n\nEvery client receives a close frame with `code` (default `1000`) and `message`. The controller itself stays; use `destroy()` to remove it.\n\nExample: Close everybody\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nCloses all clients and removes the controller.\n\nReturns: `WebSocket`\n\nEmits `destroy`, removes the controller from `F.connections` and frees it. The next client of the URL creates a new controller.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDestroys the controller when no client is online.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Called before the controller is destroyed |\n\nReturns: `WebSocket`\n\nWhen the last client disconnects and nobody connects within 5 seconds, `callback` is called (with the controller as `this`) and the controller is destroyed. Calling it again adds another callback.\n\nExample: Auto destroy\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nSends a ping to all clients.\n\nReturns: `WebSocket`\n\nThe framework calls it on its own every `CONF.default_interval_websocket_ping` ms. The pong answer sets `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nProcesses WebSocket API messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | API name, with or without `@` |\n\nReturns: `WebSocket`\n\nRegisters a `message` handler that runs `API` routes with the given `@name` for messages whose `TYPE` is `api`. The message `data` is `{ schema: 'operation/param', data: {} }`; the answer is sent back to the client when the message has `callbackid`, with `success: true` and `data`, or `error: true` and the error items.\n\nExample: Process an API\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nEncrypts messages with `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Default `true` |\n\nReturns: `WebSocket`\n\nWhen enabled and `CONF.secret_encryption` is set, outgoing text messages are encrypted and incoming ones decrypted. Without an argument it enables encryption.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nA client connected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | The new client |\n\nEmitted after the client joined the controller, so `this.online` already counts it.\n\nExample: Welcome\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nA client sent a message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | The sender |\n| `message` | `Object/String/Buffer` | yes |  | The message |\n\n`message` is an object in `json` routes, a string in `text` routes and a `Buffer` in `binary` or `buffer` routes.\n\nExample: Echo\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nA client disconnected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | The client |\n| `code` | `Number` | yes |  | Close code |\n| `message` | `String` | yes |  | Close reason |\n\n`code` and `message` come from the close frame of the client, when it sent one.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nA socket error occurred.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | The error |\n| `client` | `Object` | yes |  | The client |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nThe controller is being destroyed.\n\n### client.id\n\nType: `property`\n\nThe unique id of the connection.\n\nReturns: `String`\n\nA numeric string. It is also available as `client.ID` and is the key in `websocket.connections`. `client.online` is `true` while the connection is open, and `client.controller` (or `client.container`) is the WebSocket controller.\n\n### client.user\n\nType: `property`\n\nThe user accepted by `AUTH()`.\n\nReturns: `Object`\n\nYou can also assign a value. `client.session` and `client.sessionid` hold the session values from the request.\n\nExample: Private message\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nThe query string of the connection URL.\n\nReturns: `Object`\n\nThe values are strings. `client.get` is an alias.\n\nExample: Token in the URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nThe headers of the upgrade request.\n\nReturns: `Object`\n\nAlso available: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` and `client.req`. `client.protocol` is the array of sub-protocols from `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nThe latency of the last ping in ms.\n\nReturns: `Number`\n\nSet when the client answers a ping. Clients without an answer or with a higher latency than `CONF.default_websocket_maxlatency` are closed.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nSends a message to this client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | The message |\n| `raw` | `Boolean` | yes |  | Do not serialize (json routes) |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer; `true` uses the framework's replacer |\n\nReturns: `Object` The client\n\nIn a `json` route objects are serialized; with `raw` set to `true` the message is sent as it is (a JSON string you already have). In a `text` route objects are serialized and other values converted to strings. In a `binary` route the message must be a `Buffer`. Nothing happens if the client is closed.\n\nExample: Reply\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nCloses this connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Close reason |\n| `code` | `Number` | yes |  | Close code, default `1000` |\n\nReturns: `Object` The client\n\nSends a close frame with `code` (default `1000`) and `message`. The arguments can also be passed in the order `(code, message)`.\n\nExample: Kick a client\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nReads a cookie of the upgrade request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cookie name |\n\nReturns: `String`\n\nExample: Read a cookie\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nReturns the hostname with an optional path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Path to append |\n\nReturns: `String`\n\n`client.host()` is an alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nFinds a WebSocket controller by its id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Part of the id or a regular expression |\n\nReturns: `WebSocket` The controller or `undefined`\n\nReturns the first controller whose id contains `path` (or matches a `RegExp`). Controllers are kept in `F.connections`.\n\nExample: Send from an HTTP route\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nFinds WebSocket controllers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Part of the id or a regular expression |\n\nReturns: `Array`\n\nWithout `path` it returns all controllers.\n\nExample: All rooms\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nA client joined a WebSocket controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | The controller |\n| `client` | `Object` | yes |  | The client |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nA client left a WebSocket controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | The controller |\n| `client` | `Object` | yes |  | The client |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nThe default maximum message size in kB.\n\nReturns: `Number`\n\nDefault `2`. A route overrides it with its `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nThe maximum ping latency in ms.\n\nReturns: `Number`\n\nDefault `2000`. Clients with a higher latency, or without a pong, are closed. `0` turns the pinger off. The ping runs every `CONF.default_interval_websocket_ping` ms (default `20000`; values below `1000` use `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nEnables WebSocket routes.\n\nReturns: `Boolean`\n\nDefault `true`. `CONF.allow_websocket_compression` (default `true`) allows `permessage-deflate`, and `CONF.default_websocket_encodedecode` (default `false`) turns on URI encoding of messages.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCreates a WebSocket client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` is called at once with the new client (also as `this`). Set options, headers and events there, then call `client.connect()`.\n\nExample: Connect\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nOptions of the client.\n\nReturns: `Object`\n\n- `type` (`'json'`): `json`, `text`, `binary` or `buffer`.\n- `compress` (`true`): asks for `permessage-deflate`.\n- `reconnect` (`3000`): ms before reconnecting after a closed connection; `0` disables it.\n- `reconnectserver` (`false`): also reconnect after a connection error or an unexpected HTTP response.\n- `masking` (`false`): masks outgoing frames.\n- `encodedecode` (`false`): URI encoding of messages.\n- `encrypt`: a secret to encrypt and decrypt text messages.\n- `length`: maximum size of a decompressed message in bytes.\n- `rejectunauthorized` (`false`): rejects invalid TLS certificates.\n- `key`, `cert`, `dhparam`: TLS options.\n\nExample: Text client\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nExtra headers of the upgrade request.\n\nReturns: `Object`\n\n`websocketclient.cookies` is an object of cookies sent in the `Cookie` header.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true` when the client is not connected.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` counts the reconnections.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nThe latency of the last ping in ms.\n\nReturns: `Number`\n\nSet when the server answers `ping()`.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOpens the connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | Server URL |\n| `protocol` | `String` | yes |  | Sub-protocol |\n| `origin` | `String` | yes |  | Origin |\n\n`url` starts with `ws://` or `wss://`. It can also be an object `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` is sent in `Sec-WebSocket-Protocol` and `origin` in `Sec-WebSocket-Origin`. The connection starts on the next tick.\n\nExample: With a protocol\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nSends a message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | The message |\n| `raw` | `Boolean` | yes |  | Do not serialize (json) |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer |\n\nReturns: `Boolean` `true` when sent\n\nWith `type: 'json'` objects are serialized (unless `raw` is `true`). With `text` objects are serialized and other values converted to strings. With `binary` or `buffer` a non-`Buffer` message is converted to a `Buffer`. Returns `false` when the client is closed.\n\nExample: Send\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nCloses the connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Close reason, or `true` to reconnect |\n| `code` | `Number` | yes |  | Close code, default `1000` |\n\nReturns: `WebSocketClient`\n\nSends a close frame with `code` (default `1000`). It also stops reconnecting, unless `message` is `true`: then the connection closes and the client reconnects. The arguments can be passed as `(code, message)`.\n\nExample: Reconnect\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nFrees the client and stops reconnecting.\n\nEmits `destroy` and removes all event handlers.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nSends a ping to the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Default `3000` ms |\n\nReturns: `WebSocketClient`\n\nIf no pong arrives within `timeout` ms (default `3000`), the client emits `error` with `'Timeout'` and closes. The pong sets `latency`.\n\nExample: Measure latency\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nCalls the WebSocket API of a Total.js server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operation, e.g. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Payload |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Default `5000` ms |\n\nReturns: `WebSocketClient`\n\nSends `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` gets the answer; `err` is `408` after `timeout` ms (default `5000`). Without `schema` it only registers the handler for answers.\n\nExample: Call an operation\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nRegisters an event handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Event name |\n| `callback` | `Function` | yes |  | Handler |\n\nReturns: `WebSocketClient`\n\nEvents: `open()`, `message(data)`, `close(code, message)`, `error(err)` and `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` and `emit()` work as in the controller.\n\nExample: Events\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nThe session of the connection.\n\nReturns: `Object`\n\nThe session set by your `AUTH()` delegate for the upgrade request. `client.sessionid` is its id. It can be set.\n\nExample: Example\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nSends a ping frame to this client.\n\nReturns: `Object` The client.\n\nThe answer of the client updates `client.latency`. `websocket.ping()` pings all clients.\n\nExample: Ping one client\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nThe URL of the last `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` and `websocketclient.origin` keep the other arguments of `connect()`.\n\nExample: Example\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWc91e361f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"WebSockets","summary":"Die SOCKET-Route, der WebSocket-Controller, der verbundene Client und WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSockets\n\n> Die SOCKET-Route, der WebSocket-Controller, der verbundene Client und WEBSOCKETCLIENT().\n\nEine `SOCKET`-Route erzeugt einen WebSocket-Controller, den alle Clients einer URL teilen; jede Verbindung ist ein Client-Objekt, und `WEBSOCKETCLIENT()` verbindet sich vom Server aus mit anderen WebSocket-Servern. Die Anleitung [WebSockets](../../guides/websockets/) erklärt die Verwendung mit Beispielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDeklariert eine WebSocket-Route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, optional mit `+`/`-`, `{params}` und `@apiname` |\n| `action` | `Function` | yes |  | Initialisiert den WebSocket-Controller |\n| `flags` | `Array` | yes |  | Flags, Origins, Protokolle, Middleware, eine Länge oder ein Options-Objekt |\n| `length` | `Number` | yes |  | Maximale Nachrichtengröße in kB |\n\nReturns: `FrameworkRoute` Die Instanz der Route\n\nDie URL beginnt mit `SOCKET` (oder `WS`, `WSS`). Ein `+` oder `-` davor beschränkt die Route auf angemeldete oder anonyme Benutzer. `action` läuft einmal, wenn sich der erste Client mit der URL verbindet, mit dem WebSocket-Controller als `this` und den dynamischen URL-Parametern als Argumente. `length` ist die maximale Größe einer Nachricht in kB (Standard `CONF.default_websocket_maxlength`, `2`). Mit `@name` in der URL und ohne Action verarbeitet die Route die WebSocket-API `@name` und zerstört sich selbst, wenn der letzte Client geht.\n\nDie Flags sind im Eintrag **Flags von WebSocket-Routen** beschrieben.\n\nExample: Chat-Route\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: WebSocket-API ohne Action\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlags, die Datentyp, Zugriff, Origins und Protokolle einer WebSocket-Route festlegen.\n\n- `json` (Standard): Eingehende Nachrichten werden als JSON geparst (ungültiges JSON wird ignoriert) und ausgehende Objekte serialisiert.\n- `text`, `plain`: Nachrichten sind Strings; Objekte, die du sendest, werden als JSON serialisiert.\n- `binary`: Nachrichten sind `Buffer`-Objekte.\n- `raw`: schaltet `json` und `binary` ab (Textmodus).\n- `buffer`: Das Event `message` erhält immer den rohen `Buffer`.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: nur angemeldete bzw. anonyme Benutzer.\n- `@role`: ein Rollen-Flag; es macht die Route `authorize`.\n- `http://...`, `https://...`: erlaubte Origins; der `Origin` des Requests muss einen davon enthalten.\n- `#middleware`, `&middleware`: Namen von Middleware.\n- `id:name`: der Bezeichner der Route.\n- `get`, `csrf`, `http`, `https`, `debug`, `release`: Standard-Flags von Routen.\n- Jedes andere Wort ist ein erforderliches Subprotokoll. Jedes aufgeführte Protokoll muss im Header `Sec-WebSocket-Protocol` des Clients stehen, sonst wird die Verbindung mit `4001` geschlossen.\n- Eine Zahl ist die maximale Nachrichtengröße in kB; ein Objekt sind die Optionen der Middleware.\n\nExample: Binäre Route für einen Origin\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Erforderliches Subprotokoll\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nDie Anzahl der verbundenen Clients.\n\nReturns: `Number`\n\nWird aktualisiert, sobald sich ein Client verbindet oder trennt.\n\nExample: Die Anzahl an alle senden\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nAlle verbundenen Clients nach ihrer ID.\n\nReturns: `Object`\n\nEin Objekt, dessen Schlüssel Client-IDs und dessen Werte Client-Objekte sind. `websocket.keys` enthält dieselben IDs als Array. `websocket.id` ist der Schlüssel des Controllers in `F.connections`: die URL, gefolgt von `#` und den Flags der Route.\n\nExample: Einen Client lesen\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nDie URL der Verbindung.\n\nReturns: `String`\n\nDer Pfad, mit dem sich der erste Client verbunden hat, mit abschließendem Schrägstrich.\n\n### websocket.params\n\nType: `property`\n\nDie dynamischen Parameter der URL.\n\nReturns: `Object`\n\nJedes `{name}` der Route wird zu einem Schlüssel. Dieselben Werte kommen als Argumente der Action an.\n\nExample: Name des Raums\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nEin Objekt für deine eigenen Daten.\n\nReturns: `Object`\n\nWird beim ersten Zugriff erzeugt und bleibt für die Lebensdauer des Controllers erhalten.\n\nExample: Verlauf speichern\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nRegistriert einen Event-Handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Events |\n| `callback` | `Function` | yes |  | Handler |\n\nReturns: `WebSocket` Der Controller\n\nEvents: `open`, `close`, `message`, `error` und `destroy`. `this` im Handler ist der Controller. `once(name, fn)` registriert einen Handler für einen einzigen Aufruf, `removeListener(name, fn)` und `removeAllListeners([name])` entfernen Handler, und `emit(name, [args...])` ruft die Handler deiner eigenen Events auf.\n\nExample: Events\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nSendet eine Nachricht an alle Clients oder an die Clients, die du auswählst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Die Nachricht |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` gibt `true` zum Senden zurück |\n| `replacer` | `Function/Boolean` | yes |  | JSON-Replacer |\n| `params` | `Object` | yes |  | Wert, der an `comparer` übergeben wird |\n\nReturns: `WebSocket`\n\nIn einer `json`-Route wird die Nachricht einmal serialisiert und an jeden Client gesendet. `comparer(client, message, params)` gibt `true` für die Clients zurück, die die Nachricht erhalten. `replacer` wird an `JSON.stringify()` übergeben; `true` verwendet den JSON-Replacer des Frameworks. Ist das dritte Argument keine Funktion, wird es als `params` verwendet.\n\nExample: Alle außer dem Absender\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: Mit params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nFindet den ersten Client, auf den eine Funktion zutrifft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` gibt `true` für den gesuchten Client zurück |\n\nReturns: `Object` Der Client oder `undefined`\n\nGibt `undefined` zurück, wenn kein Client zutrifft.\n\nExample: Einen Benutzer finden\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nGibt alle verbundenen Clients als Array zurück.\n\nReturns: `Array`\n\nExample: Benutzer auflisten\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nSchließt alle verbundenen Clients.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Grund des Schließens |\n| `code` | `Number` | yes |  | Close-Code, Standard `1000` |\n\nReturns: `WebSocket`\n\nJeder Client erhält einen Close-Frame mit `code` (Standard `1000`) und `message`. Der Controller selbst bleibt bestehen; verwende `destroy()`, um ihn zu entfernen.\n\nExample: Alle schließen\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nSchließt alle Clients und entfernt den Controller.\n\nReturns: `WebSocket`\n\nLöst `destroy` aus, entfernt den Controller aus `F.connections` und gibt ihn frei. Der nächste Client der URL erzeugt einen neuen Controller.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nZerstört den Controller, wenn kein Client online ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Wird aufgerufen, bevor der Controller zerstört wird |\n\nReturns: `WebSocket`\n\nWenn sich der letzte Client trennt und sich innerhalb von 5 Sekunden niemand verbindet, wird `callback` aufgerufen (mit dem Controller als `this`) und der Controller zerstört. Ein erneuter Aufruf fügt einen weiteren Callback hinzu.\n\nExample: Automatisch zerstören\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nSendet einen Ping an alle Clients.\n\nReturns: `WebSocket`\n\nDas Framework ruft es selbst alle `CONF.default_interval_websocket_ping` ms auf. Die Pong-Antwort setzt `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nVerarbeitet Nachrichten der WebSocket-API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der API, mit oder ohne `@` |\n\nReturns: `WebSocket`\n\nRegistriert einen `message`-Handler, der `API`-Routen mit dem angegebenen `@name` für Nachrichten ausführt, deren `TYPE` gleich `api` ist. Das `data` der Nachricht ist `{ schema: 'operation/param', data: {} }`; die Antwort wird an den Client zurückgesendet, wenn die Nachricht `callbackid` hat, mit `success: true` und `data` oder mit `error: true` und den Fehlereinträgen.\n\nExample: Eine API verarbeiten\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nVerschlüsselt Nachrichten mit `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Standard `true` |\n\nReturns: `WebSocket`\n\nWenn aktiviert und `CONF.secret_encryption` gesetzt ist, werden ausgehende Textnachrichten verschlüsselt und eingehende entschlüsselt. Ohne Argument aktiviert es die Verschlüsselung.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nEin Client hat sich verbunden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Der neue Client |\n\nWird ausgelöst, nachdem der Client dem Controller beigetreten ist, daher zählt `this.online` ihn bereits mit.\n\nExample: Begrüßung\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nEin Client hat eine Nachricht gesendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Der Absender |\n| `message` | `Object/String/Buffer` | yes |  | Die Nachricht |\n\n`message` ist in `json`-Routen ein Objekt, in `text`-Routen ein String und in `binary`- oder `buffer`-Routen ein `Buffer`.\n\nExample: Echo\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nEin Client hat sich getrennt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Der Client |\n| `code` | `Number` | yes |  | Close-Code |\n| `message` | `String` | yes |  | Grund des Schließens |\n\n`code` und `message` stammen aus dem Close-Frame des Clients, sofern er einen gesendet hat.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nEin Socket-Fehler ist aufgetreten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | Der Fehler |\n| `client` | `Object` | yes |  | Der Client |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nDer Controller wird zerstört.\n\n### client.id\n\nType: `property`\n\nDie eindeutige ID der Verbindung.\n\nReturns: `String`\n\nEin numerischer String. Sie ist auch als `client.ID` verfügbar und ist der Schlüssel in `websocket.connections`. `client.online` ist `true`, solange die Verbindung offen ist, und `client.controller` (oder `client.container`) ist der WebSocket-Controller.\n\n### client.user\n\nType: `property`\n\nDer von `AUTH()` akzeptierte Benutzer.\n\nReturns: `Object`\n\nDu kannst auch einen Wert zuweisen. `client.session` und `client.sessionid` enthalten die Session-Werte aus dem Request.\n\nExample: Private Nachricht\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nDer Query-String der Verbindungs-URL.\n\nReturns: `Object`\n\nDie Werte sind Strings. `client.get` ist ein Alias.\n\nExample: Token in der URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nDie Header des Upgrade-Requests.\n\nReturns: `Object`\n\nAußerdem verfügbar: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` und `client.req`. `client.protocol` ist das Array der Subprotokolle aus `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nDie Latenz des letzten Pings in ms.\n\nReturns: `Number`\n\nWird gesetzt, wenn der Client einen Ping beantwortet. Clients ohne Antwort oder mit einer höheren Latenz als `CONF.default_websocket_maxlatency` werden geschlossen.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nSendet eine Nachricht an diesen Client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Die Nachricht |\n| `raw` | `Boolean` | yes |  | Nicht serialisieren (json-Routen) |\n| `replacer` | `Function/Boolean` | yes |  | JSON-Replacer; `true` verwendet den Replacer des Frameworks |\n\nReturns: `Object` Der Client\n\nIn einer `json`-Route werden Objekte serialisiert; mit `raw` auf `true` wird die Nachricht unverändert gesendet (ein JSON-String, den du bereits hast). In einer `text`-Route werden Objekte serialisiert und andere Werte in Strings umgewandelt. In einer `binary`-Route muss die Nachricht ein `Buffer` sein. Ist der Client geschlossen, passiert nichts.\n\nExample: Antworten\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nSchließt diese Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Grund des Schließens |\n| `code` | `Number` | yes |  | Close-Code, Standard `1000` |\n\nReturns: `Object` Der Client\n\nSendet einen Close-Frame mit `code` (Standard `1000`) und `message`. Die Argumente können auch in der Reihenfolge `(code, message)` übergeben werden.\n\nExample: Einen Client rauswerfen\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nLiest ein Cookie des Upgrade-Requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Cookies |\n\nReturns: `String`\n\nExample: Ein Cookie lesen\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nGibt den Hostnamen mit einem optionalen Pfad zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Anzuhängender Pfad |\n\nReturns: `String`\n\n`client.host()` ist ein Alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nFindet einen WebSocket-Controller anhand seiner ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Teil der ID oder ein regulärer Ausdruck |\n\nReturns: `WebSocket` Der Controller oder `undefined`\n\nGibt den ersten Controller zurück, dessen ID `path` enthält (oder auf eine `RegExp` passt). Controller werden in `F.connections` gehalten.\n\nExample: Aus einer HTTP-Route senden\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nFindet WebSocket-Controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Teil der ID oder ein regulärer Ausdruck |\n\nReturns: `Array`\n\nOhne `path` gibt es alle Controller zurück.\n\nExample: Alle Räume\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nEin Client ist einem WebSocket-Controller beigetreten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Der Controller |\n| `client` | `Object` | yes |  | Der Client |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nEin Client hat einen WebSocket-Controller verlassen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Der Controller |\n| `client` | `Object` | yes |  | Der Client |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nDie standardmäßige maximale Nachrichtengröße in kB.\n\nReturns: `Number`\n\nStandard `2`. Eine Route überschreibt sie mit ihrem `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nDie maximale Ping-Latenz in ms.\n\nReturns: `Number`\n\nStandard `2000`. Clients mit höherer Latenz oder ohne Pong werden geschlossen. `0` schaltet den Pinger ab. Der Ping läuft alle `CONF.default_interval_websocket_ping` ms (Standard `20000`; Werte unter `1000` verwenden `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nAktiviert WebSocket-Routen.\n\nReturns: `Boolean`\n\nStandard `true`. `CONF.allow_websocket_compression` (Standard `true`) erlaubt `permessage-deflate`, und `CONF.default_websocket_encodedecode` (Standard `false`) schaltet die URI-Kodierung von Nachrichten ein.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nErzeugt einen WebSocket-Client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` wird sofort mit dem neuen Client aufgerufen (auch als `this`). Setze dort Optionen, Header und Events und rufe dann `client.connect()` auf.\n\nExample: Verbinden\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nOptionen des Clients.\n\nReturns: `Object`\n\n- `type` (`'json'`): `json`, `text`, `binary` oder `buffer`.\n- `compress` (`true`): fordert `permessage-deflate` an.\n- `reconnect` (`3000`): ms bis zum Neuverbinden nach einer geschlossenen Verbindung; `0` deaktiviert es.\n- `reconnectserver` (`false`): auch nach einem Verbindungsfehler oder einer unerwarteten HTTP-Response neu verbinden.\n- `masking` (`false`): maskiert ausgehende Frames.\n- `encodedecode` (`false`): URI-Kodierung von Nachrichten.\n- `encrypt`: ein Secret zum Ver- und Entschlüsseln von Textnachrichten.\n- `length`: maximale Größe einer dekomprimierten Nachricht in Bytes.\n- `rejectunauthorized` (`false`): lehnt ungültige TLS-Zertifikate ab.\n- `key`, `cert`, `dhparam`: TLS-Optionen.\n\nExample: Text-Client\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nZusätzliche Header des Upgrade-Requests.\n\nReturns: `Object`\n\n`websocketclient.cookies` ist ein Objekt mit Cookies, die im Header `Cookie` gesendet werden.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true`, wenn der Client nicht verbunden ist.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` zählt die Neuverbindungen.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nDie Latenz des letzten Pings in ms.\n\nReturns: `Number`\n\nWird gesetzt, wenn der Server `ping()` beantwortet.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nÖffnet die Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | URL des Servers |\n| `protocol` | `String` | yes |  | Subprotokoll |\n| `origin` | `String` | yes |  | Origin |\n\n`url` beginnt mit `ws://` oder `wss://`. Es kann auch ein Objekt `{ socket: '/path/to/unix.socket', path: '/chat/' }` sein. `protocol` wird in `Sec-WebSocket-Protocol` gesendet und `origin` in `Sec-WebSocket-Origin`. Die Verbindung startet im nächsten Tick.\n\nExample: Mit einem Protokoll\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nSendet eine Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Die Nachricht |\n| `raw` | `Boolean` | yes |  | Nicht serialisieren (json) |\n| `replacer` | `Function/Boolean` | yes |  | JSON-Replacer |\n\nReturns: `Boolean` `true`, wenn gesendet\n\nMit `type: 'json'` werden Objekte serialisiert (außer `raw` ist `true`). Mit `text` werden Objekte serialisiert und andere Werte in Strings umgewandelt. Mit `binary` oder `buffer` wird eine Nachricht, die kein `Buffer` ist, in einen `Buffer` umgewandelt. Gibt `false` zurück, wenn der Client geschlossen ist.\n\nExample: Senden\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nSchließt die Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Grund des Schließens oder `true` zum Neuverbinden |\n| `code` | `Number` | yes |  | Close-Code, Standard `1000` |\n\nReturns: `WebSocketClient`\n\nSendet einen Close-Frame mit `code` (Standard `1000`). Außerdem beendet es das Neuverbinden, außer `message` ist `true`: Dann wird die Verbindung geschlossen und der Client verbindet sich neu. Die Argumente können als `(code, message)` übergeben werden.\n\nExample: Neu verbinden\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nGibt den Client frei und beendet das Neuverbinden.\n\nLöst `destroy` aus und entfernt alle Event-Handler.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nSendet einen Ping an den Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Standard `3000` ms |\n\nReturns: `WebSocketClient`\n\nKommt innerhalb von `timeout` ms (Standard `3000`) kein Pong, löst der Client `error` mit `'Timeout'` aus und schließt sich. Der Pong setzt `latency`.\n\nExample: Latenz messen\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nRuft die WebSocket-API eines Total.js-Servers auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operation, z. B. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Nutzdaten |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Standard `5000` ms |\n\nReturns: `WebSocketClient`\n\nSendet `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` erhält die Antwort; `err` ist `408` nach `timeout` ms (Standard `5000`). Ohne `schema` registriert es nur den Handler für Antworten.\n\nExample: Eine Operation aufrufen\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nRegistriert einen Event-Handler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Events |\n| `callback` | `Function` | yes |  | Handler |\n\nReturns: `WebSocketClient`\n\nEvents: `open()`, `message(data)`, `close(code, message)`, `error(err)` und `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` und `emit()` funktionieren wie im Controller.\n\nExample: Events\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nDie Session der Verbindung.\n\nReturns: `Object`\n\nDie Session, die dein `AUTH()`-Delegate für den Upgrade-Request gesetzt hat. `client.sessionid` ist ihre ID. Sie kann gesetzt werden.\n\nExample: Beispiel\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nSendet einen Ping-Frame an diesen Client.\n\nReturns: `Object` Der Client.\n\nDie Antwort des Clients aktualisiert `client.latency`. `websocket.ping()` pingt alle Clients.\n\nExample: Einen Client pingen\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nDie URL des letzten `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` und `websocketclient.origin` speichern die anderen Argumente von `connect()`.\n\nExample: Beispiel\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWc91e361f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"WebSockets","summary":"La ruta SOCKET, el controlador WebSocket, el cliente conectado y WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSockets\n\n> La ruta SOCKET, el controlador WebSocket, el cliente conectado y WEBSOCKETCLIENT().\n\nUna ruta `SOCKET` crea un controlador WebSocket compartido por todos los clientes de una URL; cada conexión es un objeto cliente, y `WEBSOCKETCLIENT()` se conecta desde el servidor a otros servidores WebSocket. La guía [WebSockets](../../guides/websockets/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDeclara una ruta WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, opcionalmente con `+`/`-`, `{params}` y `@apiname` |\n| `action` | `Function` | yes |  | Inicializa el controlador WebSocket |\n| `flags` | `Array` | yes |  | Flags, orígenes, protocolos, middleware, una longitud o un objeto de opciones |\n| `length` | `Number` | yes |  | Tamaño máximo del mensaje en kB |\n\nReturns: `FrameworkRoute` La instancia de la ruta\n\nLa URL empieza por `SOCKET` (o `WS`, `WSS`). Un `+` o `-` delante limita la ruta a usuarios con sesión iniciada o anónimos. `action` se ejecuta una vez, cuando el primer cliente se conecta a la URL, con el controlador WebSocket como `this` y los parámetros dinámicos de la URL como argumentos. `length` es el tamaño máximo de un mensaje en kB (por defecto `CONF.default_websocket_maxlength`, `2`). Con `@name` en la URL y sin acción, la ruta procesa la WebSocket API `@name` y se destruye cuando se va el último cliente.\n\nLos flags se describen en la entrada **Flags de rutas WebSocket**.\n\nExample: Ruta de chat\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: WebSocket API sin acción\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlags que definen el tipo de datos, el acceso, los orígenes y los protocolos de una ruta WebSocket.\n\n- `json` (por defecto): los mensajes entrantes se parsean como JSON (el JSON no válido se ignora) y los objetos salientes se serializan.\n- `text`, `plain`: los mensajes son cadenas; los objetos que envías se serializan como JSON.\n- `binary`: los mensajes son objetos `Buffer`.\n- `raw`: desactiva `json` y `binary` (modo texto).\n- `buffer`: el evento `message` siempre recibe el `Buffer` sin procesar.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: solo usuarios con sesión iniciada o anónimos.\n- `@role`: un flag de rol; convierte la ruta en `authorize`.\n- `http://...`, `https://...`: orígenes permitidos; el `Origin` de la petición debe contener uno de ellos.\n- `#middleware`, `&middleware`: nombres de middleware.\n- `id:name`: el identificador de la ruta.\n- `get`, `csrf`, `http`, `https`, `debug`, `release`: flags estándar de ruta.\n- Cualquier otra palabra es un sub-protocolo obligatorio. Cada protocolo indicado debe estar en la cabecera `Sec-WebSocket-Protocol` del cliente; si no, la conexión se cierra con `4001`.\n- Un número es el tamaño máximo del mensaje en kB; un objeto son las opciones del middleware.\n\nExample: Ruta binaria para un origen\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Sub-protocolo obligatorio\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nEl número de clientes conectados.\n\nReturns: `Number`\n\nSe actualiza cada vez que un cliente se conecta o se desconecta.\n\nExample: Difundir el número\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nTodos los clientes conectados por su id.\n\nReturns: `Object`\n\nUn objeto cuyas claves son los ids de cliente y cuyos valores son los objetos cliente. `websocket.keys` contiene los mismos ids como array. `websocket.id` es la clave del controlador en `F.connections`: la URL seguida de `#` y los flags de la ruta.\n\nExample: Leer un cliente\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nLa URL de la conexión.\n\nReturns: `String`\n\nLa ruta (path) a la que se conectó el primer cliente, con barra final.\n\n### websocket.params\n\nType: `property`\n\nLos parámetros dinámicos de la URL.\n\nReturns: `Object`\n\nCada `{name}` de la ruta se convierte en una clave. Los mismos valores llegan como argumentos de la acción.\n\nExample: Nombre de la sala\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nUn objeto para tus propios datos.\n\nReturns: `Object`\n\nSe crea en el primer acceso y se mantiene durante la vida del controlador.\n\nExample: Guardar el historial\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nRegistra un manejador de evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del evento |\n| `callback` | `Function` | yes |  | Manejador |\n\nReturns: `WebSocket` El controlador\n\nEventos: `open`, `close`, `message`, `error` y `destroy`. `this` en el manejador es el controlador. `once(name, fn)` registra un manejador para una sola llamada, `removeListener(name, fn)` y `removeAllListeners([name])` eliminan manejadores, y `emit(name, [args...])` llama a los manejadores de tus propios eventos.\n\nExample: Eventos\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nEnvía un mensaje a todos los clientes o a los clientes que selecciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | El mensaje |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` devuelve `true` para enviar |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n| `params` | `Object` | yes |  | Valor que se pasa a `comparer` |\n\nReturns: `WebSocket`\n\nEn una ruta `json` el mensaje se serializa una vez y se envía a cada cliente. `comparer(client, message, params)` devuelve `true` para los clientes que reciben el mensaje. `replacer` se pasa a `JSON.stringify()`; `true` usa el replacer JSON del framework. Cuando el tercer argumento no es una función, se usa como `params`.\n\nExample: Todos excepto el remitente\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: Con params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nBusca el primer cliente que cumple una función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` devuelve `true` para el cliente buscado |\n\nReturns: `Object` El cliente o `undefined`\n\nDevuelve `undefined` cuando ningún cliente coincide.\n\nExample: Buscar un usuario\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nDevuelve todos los clientes conectados como un array.\n\nReturns: `Array`\n\nExample: Listar usuarios\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nCierra todos los clientes conectados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motivo del cierre |\n| `code` | `Number` | yes |  | Código de cierre, por defecto `1000` |\n\nReturns: `WebSocket`\n\nCada cliente recibe un frame de cierre con `code` (por defecto `1000`) y `message`. El controlador en sí se mantiene; usa `destroy()` para eliminarlo.\n\nExample: Cerrar todos\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nCierra todos los clientes y elimina el controlador.\n\nReturns: `WebSocket`\n\nEmite `destroy`, elimina el controlador de `F.connections` y lo libera. El siguiente cliente de la URL crea un controlador nuevo.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDestruye el controlador cuando no hay ningún cliente conectado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Se llama antes de destruir el controlador |\n\nReturns: `WebSocket`\n\nCuando el último cliente se desconecta y nadie se conecta en 5 segundos, se llama a `callback` (con el controlador como `this`) y el controlador se destruye. Llamarlo de nuevo añade otro callback.\n\nExample: Autodestrucción\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nEnvía un ping a todos los clientes.\n\nReturns: `WebSocket`\n\nEl framework lo llama por su cuenta cada `CONF.default_interval_websocket_ping` ms. La respuesta pong asigna `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nProcesa mensajes de la WebSocket API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la API, con o sin `@` |\n\nReturns: `WebSocket`\n\nRegistra un manejador `message` que ejecuta las rutas `API` con el `@name` indicado para los mensajes cuyo `TYPE` es `api`. El `data` del mensaje es `{ schema: 'operation/param', data: {} }`; la respuesta se devuelve al cliente cuando el mensaje tiene `callbackid`, con `success: true` y `data`, o con `error: true` y los elementos de error.\n\nExample: Procesar una API\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nCifra los mensajes con `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Por defecto `true` |\n\nReturns: `WebSocket`\n\nCuando está activado y `CONF.secret_encryption` está definido, los mensajes de texto salientes se cifran y los entrantes se descifran. Sin argumento activa el cifrado.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nSe conectó un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | El nuevo cliente |\n\nSe emite después de que el cliente se una al controlador, así que `this.online` ya lo cuenta.\n\nExample: Bienvenida\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nUn cliente envió un mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | El remitente |\n| `message` | `Object/String/Buffer` | yes |  | El mensaje |\n\n`message` es un objeto en rutas `json`, una cadena en rutas `text` y un `Buffer` en rutas `binary` o `buffer`.\n\nExample: Eco\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nSe desconectó un cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | El cliente |\n| `code` | `Number` | yes |  | Código de cierre |\n| `message` | `String` | yes |  | Motivo del cierre |\n\n`code` y `message` vienen del frame de cierre del cliente, cuando envió uno.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nSe produjo un error en el socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | El error |\n| `client` | `Object` | yes |  | El cliente |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nEl controlador se está destruyendo.\n\n### client.id\n\nType: `property`\n\nEl id único de la conexión.\n\nReturns: `String`\n\nUna cadena numérica. También está disponible como `client.ID` y es la clave en `websocket.connections`. `client.online` es `true` mientras la conexión está abierta, y `client.controller` (o `client.container`) es el controlador WebSocket.\n\n### client.user\n\nType: `property`\n\nEl usuario aceptado por `AUTH()`.\n\nReturns: `Object`\n\nTambién puedes asignarle un valor. `client.session` y `client.sessionid` contienen los valores de sesión de la petición.\n\nExample: Mensaje privado\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nEl query string de la URL de conexión.\n\nReturns: `Object`\n\nLos valores son cadenas. `client.get` es un alias.\n\nExample: Token en la URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nLas cabeceras de la petición de upgrade.\n\nReturns: `Object`\n\nTambién están disponibles: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` y `client.req`. `client.protocol` es el array de sub-protocolos de `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nLa latencia del último ping en ms.\n\nReturns: `Number`\n\nSe asigna cuando el cliente responde a un ping. Los clientes sin respuesta o con una latencia mayor que `CONF.default_websocket_maxlatency` se cierran.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvía un mensaje a este cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | El mensaje |\n| `raw` | `Boolean` | yes |  | No serializar (rutas json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON; `true` usa el replacer del framework |\n\nReturns: `Object` El cliente\n\nEn una ruta `json` los objetos se serializan; con `raw` en `true` el mensaje se envía tal cual (una cadena JSON que ya tienes). En una ruta `text` los objetos se serializan y los demás valores se convierten en cadenas. En una ruta `binary` el mensaje debe ser un `Buffer`. No pasa nada si el cliente está cerrado.\n\nExample: Responder\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nCierra esta conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motivo del cierre |\n| `code` | `Number` | yes |  | Código de cierre, por defecto `1000` |\n\nReturns: `Object` El cliente\n\nEnvía un frame de cierre con `code` (por defecto `1000`) y `message`. Los argumentos también pueden pasarse en el orden `(code, message)`.\n\nExample: Expulsar a un cliente\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nLee una cookie de la petición de upgrade.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cookie |\n\nReturns: `String`\n\nExample: Leer una cookie\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nDevuelve el nombre de host con una ruta (path) opcional.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ruta (path) que se añade al final |\n\nReturns: `String`\n\n`client.host()` es un alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nBusca un controlador WebSocket por su id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Parte del id o una expresión regular |\n\nReturns: `WebSocket` El controlador o `undefined`\n\nDevuelve el primer controlador cuyo id contiene `path` (o coincide con una `RegExp`). Los controladores se guardan en `F.connections`.\n\nExample: Enviar desde una ruta HTTP\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nBusca controladores WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Parte del id o una expresión regular |\n\nReturns: `Array`\n\nSin `path` devuelve todos los controladores.\n\nExample: Todas las salas\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nUn cliente se unió a un controlador WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | El controlador |\n| `client` | `Object` | yes |  | El cliente |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nUn cliente salió de un controlador WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | El controlador |\n| `client` | `Object` | yes |  | El cliente |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nEl tamaño máximo por defecto de un mensaje en kB.\n\nReturns: `Number`\n\nPor defecto `2`. Una ruta lo sobrescribe con su `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nLa latencia máxima del ping en ms.\n\nReturns: `Number`\n\nPor defecto `2000`. Los clientes con una latencia mayor, o sin pong, se cierran. `0` desactiva el ping. El ping se ejecuta cada `CONF.default_interval_websocket_ping` ms (por defecto `20000`; los valores por debajo de `1000` usan `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nActiva las rutas WebSocket.\n\nReturns: `Boolean`\n\nPor defecto `true`. `CONF.allow_websocket_compression` (por defecto `true`) permite `permessage-deflate`, y `CONF.default_websocket_encodedecode` (por defecto `false`) activa la codificación URI de los mensajes.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrea un cliente WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` se llama al instante con el nuevo cliente (también como `this`). Define ahí las opciones, las cabeceras y los eventos, y luego llama a `client.connect()`.\n\nExample: Conectar\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nOpciones del cliente.\n\nReturns: `Object`\n\n- `type` (`'json'`): `json`, `text`, `binary` o `buffer`.\n- `compress` (`true`): solicita `permessage-deflate`.\n- `reconnect` (`3000`): ms antes de reconectar tras cerrarse la conexión; `0` lo desactiva.\n- `reconnectserver` (`false`): reconecta también tras un error de conexión o una respuesta HTTP inesperada.\n- `masking` (`false`): enmascara los frames salientes.\n- `encodedecode` (`false`): codificación URI de los mensajes.\n- `encrypt`: un secreto para cifrar y descifrar los mensajes de texto.\n- `length`: tamaño máximo de un mensaje descomprimido en bytes.\n- `rejectunauthorized` (`false`): rechaza certificados TLS no válidos.\n- `key`, `cert`, `dhparam`: opciones TLS.\n\nExample: Cliente de texto\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nCabeceras adicionales de la petición de upgrade.\n\nReturns: `Object`\n\n`websocketclient.cookies` es un objeto de cookies que se envían en la cabecera `Cookie`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true` cuando el cliente no está conectado.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` cuenta las reconexiones.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nLa latencia del último ping en ms.\n\nReturns: `Number`\n\nSe asigna cuando el servidor responde a `ping()`.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nAbre la conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | URL del servidor |\n| `protocol` | `String` | yes |  | Sub-protocolo |\n| `origin` | `String` | yes |  | Origen |\n\n`url` empieza por `ws://` o `wss://`. También puede ser un objeto `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` se envía en `Sec-WebSocket-Protocol` y `origin` en `Sec-WebSocket-Origin`. La conexión empieza en el siguiente tick.\n\nExample: Con un protocolo\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvía un mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | El mensaje |\n| `raw` | `Boolean` | yes |  | No serializar (json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n\nReturns: `Boolean` `true` cuando se envió\n\nCon `type: 'json'` los objetos se serializan (salvo que `raw` sea `true`). Con `text` los objetos se serializan y los demás valores se convierten en cadenas. Con `binary` o `buffer` un mensaje que no es `Buffer` se convierte en un `Buffer`. Devuelve `false` cuando el cliente está cerrado.\n\nExample: Enviar\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nCierra la conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Motivo del cierre, o `true` para reconectar |\n| `code` | `Number` | yes |  | Código de cierre, por defecto `1000` |\n\nReturns: `WebSocketClient`\n\nEnvía un frame de cierre con `code` (por defecto `1000`). También detiene la reconexión, salvo que `message` sea `true`: entonces la conexión se cierra y el cliente se reconecta. Los argumentos pueden pasarse como `(code, message)`.\n\nExample: Reconectar\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nLibera el cliente y detiene la reconexión.\n\nEmite `destroy` y elimina todos los manejadores de eventos.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nEnvía un ping al servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Por defecto `3000` ms |\n\nReturns: `WebSocketClient`\n\nSi no llega ningún pong en `timeout` ms (por defecto `3000`), el cliente emite `error` con `'Timeout'` y se cierra. El pong asigna `latency`.\n\nExample: Medir la latencia\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nLlama a la WebSocket API de un servidor Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operación, p. ej. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Datos |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Por defecto `5000` ms |\n\nReturns: `WebSocketClient`\n\nEnvía `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` recibe la respuesta; `err` es `408` después de `timeout` ms (por defecto `5000`). Sin `schema` solo registra el manejador de las respuestas.\n\nExample: Llamar a una operación\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nRegistra un manejador de evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del evento |\n| `callback` | `Function` | yes |  | Manejador |\n\nReturns: `WebSocketClient`\n\nEventos: `open()`, `message(data)`, `close(code, message)`, `error(err)` y `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` y `emit()` funcionan como en el controlador.\n\nExample: Eventos\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nLa sesión de la conexión.\n\nReturns: `Object`\n\nLa sesión que asigna tu delegado `AUTH()` para la petición de upgrade. `client.sessionid` es su id. Se puede asignar.\n\nExample: Ejemplo\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nEnvía un frame de ping a este cliente.\n\nReturns: `Object` El cliente.\n\nLa respuesta del cliente actualiza `client.latency`. `websocket.ping()` hace ping a todos los clientes.\n\nExample: Ping a un cliente\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nLa URL del último `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` y `websocketclient.origin` guardan los demás argumentos de `connect()`.\n\nExample: Ejemplo\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWc91e361f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"WebSockets","summary":"La route SOCKET, le contrôleur WebSocket, le client connecté et WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockets\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSockets\n\n> La route SOCKET, le contrôleur WebSocket, le client connecté et WEBSOCKETCLIENT().\n\nUne route `SOCKET` crée un contrôleur WebSocket partagé par tous les clients d'une URL ; chaque connexion est un objet client, et `WEBSOCKETCLIENT()` se connecte depuis le serveur à d'autres serveurs WebSocket. Le guide [WebSockets](../../guides/websockets/) explique comment les utiliser avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDéclare une route WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, éventuellement avec `+`/`-`, `{params}` et `@apiname` |\n| `action` | `Function` | yes |  | Initialise le contrôleur WebSocket |\n| `flags` | `Array` | yes |  | Flags, origines, protocoles, middleware, une longueur ou un objet d'options |\n| `length` | `Number` | yes |  | Taille maximale d'un message en ko |\n\nReturns: `FrameworkRoute` L'instance de la route\n\nL'URL commence par `SOCKET` (ou `WS`, `WSS`). Un `+` ou un `-` devant elle limite la route aux utilisateurs connectés ou anonymes. `action` s'exécute une seule fois, lorsque le premier client se connecte à l'URL, avec le contrôleur WebSocket comme `this` et les paramètres dynamiques de l'URL comme arguments. `length` est la taille maximale d'un message en ko (par défaut `CONF.default_websocket_maxlength`, `2`). Avec `@name` dans l'URL et sans action, la route traite l'API WebSocket `@name` et se détruit lorsque le dernier client part.\n\nLes flags sont décrits dans l'entrée **Flags des routes WebSocket**.\n\nExample: Route de chat\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: API WebSocket sans action\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlags qui définissent le type de données, l'accès, les origines et les protocoles d'une route WebSocket.\n\n- `json` (par défaut) : les messages entrants sont analysés comme du JSON (un JSON invalide est ignoré) et les objets sortants sont sérialisés.\n- `text`, `plain` : les messages sont des chaînes ; les objets que tu envoies sont sérialisés en JSON.\n- `binary` : les messages sont des objets `Buffer`.\n- `raw` : désactive `json` et `binary` (mode texte).\n- `buffer` : l'événement `message` reçoit toujours le `Buffer` brut.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged` : utilisateurs connectés ou anonymes uniquement.\n- `@role` : un flag de rôle ; il rend la route `authorize`.\n- `http://...`, `https://...` : origines autorisées ; l'en-tête `Origin` de la requête doit contenir l'une d'elles.\n- `#middleware`, `&middleware` : noms de middlewares.\n- `id:name` : l'identifiant de la route.\n- `get`, `csrf`, `http`, `https`, `debug`, `release` : flags de route standard.\n- Tout autre mot est un sous-protocole obligatoire. Chaque protocole listé doit figurer dans l'en-tête `Sec-WebSocket-Protocol` du client, sinon la connexion est fermée avec `4001`.\n- Un nombre est la taille maximale d'un message en ko ; un objet correspond aux options du middleware.\n\nExample: Route binaire pour une seule origine\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Sous-protocole obligatoire\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nLe nombre de clients connectés.\n\nReturns: `Number`\n\nMis à jour à chaque connexion ou déconnexion d'un client.\n\nExample: Diffuser le nombre\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nTous les clients connectés, par leur id.\n\nReturns: `Object`\n\nUn objet dont les clés sont les id des clients et les valeurs les objets client. `websocket.keys` contient les mêmes id sous forme de tableau. `websocket.id` est la clé du contrôleur dans `F.connections` : l'URL suivie de `#` et des flags de la route.\n\nExample: Lire un client\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nL'URL de la connexion.\n\nReturns: `String`\n\nLe chemin auquel le premier client s'est connecté, avec une barre oblique finale.\n\n### websocket.params\n\nType: `property`\n\nLes paramètres dynamiques de l'URL.\n\nReturns: `Object`\n\nChaque `{name}` de la route devient une clé. Les mêmes valeurs arrivent comme arguments de l'action.\n\nExample: Nom du salon\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nUn objet pour tes propres données.\n\nReturns: `Object`\n\nCréé au premier accès et conservé pendant toute la vie du contrôleur.\n\nExample: Conserver l'historique\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nEnregistre un gestionnaire d'événement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'événement |\n| `callback` | `Function` | yes |  | Gestionnaire |\n\nReturns: `WebSocket` Le contrôleur\n\nÉvénements : `open`, `close`, `message`, `error` et `destroy`. Dans le gestionnaire, `this` est le contrôleur. `once(name, fn)` enregistre un gestionnaire pour un seul appel, `removeListener(name, fn)` et `removeAllListeners([name])` suppriment des gestionnaires, et `emit(name, [args...])` appelle les gestionnaires de tes propres événements.\n\nExample: Événements\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nEnvoie un message à tous les clients ou aux clients que tu sélectionnes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Le message |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` retourne `true` pour envoyer |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n| `params` | `Object` | yes |  | Valeur passée à `comparer` |\n\nReturns: `WebSocket`\n\nDans une route `json`, le message est sérialisé une seule fois et envoyé à chaque client. `comparer(client, message, params)` retourne `true` pour les clients qui reçoivent le message. `replacer` est passé à `JSON.stringify()` ; `true` utilise le replacer JSON du framework. Lorsque le troisième argument n'est pas une fonction, il est utilisé comme `params`.\n\nExample: Tout le monde sauf l'expéditeur\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: Avec params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nTrouve le premier client qui correspond à une fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` retourne `true` pour le client recherché |\n\nReturns: `Object` Le client ou `undefined`\n\nRetourne `undefined` lorsqu'aucun client ne correspond.\n\nExample: Trouver un utilisateur\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nRetourne tous les clients connectés sous forme de tableau.\n\nReturns: `Array`\n\nExample: Lister les utilisateurs\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nFerme tous les clients connectés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motif de fermeture |\n| `code` | `Number` | yes |  | Code de fermeture, par défaut `1000` |\n\nReturns: `WebSocket`\n\nChaque client reçoit une trame de fermeture avec `code` (par défaut `1000`) et `message`. Le contrôleur lui-même reste ; utilise `destroy()` pour le supprimer.\n\nExample: Fermer tout le monde\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nFerme tous les clients et supprime le contrôleur.\n\nReturns: `WebSocket`\n\nÉmet `destroy`, retire le contrôleur de `F.connections` et le libère. Le client suivant de l'URL crée un nouveau contrôleur.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDétruit le contrôleur lorsqu'aucun client n'est en ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Appelé avant la destruction du contrôleur |\n\nReturns: `WebSocket`\n\nLorsque le dernier client se déconnecte et que personne ne se connecte dans les 5 secondes, `callback` est appelé (avec le contrôleur comme `this`) et le contrôleur est détruit. L'appeler de nouveau ajoute un autre callback.\n\nExample: Destruction automatique\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nEnvoie un ping à tous les clients.\n\nReturns: `WebSocket`\n\nLe framework l'appelle de lui-même toutes les `CONF.default_interval_websocket_ping` ms. La réponse pong définit `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nTraite les messages de l'API WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'API, avec ou sans `@` |\n\nReturns: `WebSocket`\n\nEnregistre un gestionnaire `message` qui exécute les routes `API` portant le `@name` indiqué pour les messages dont le `TYPE` est `api`. Le `data` du message est `{ schema: 'operation/param', data: {} }` ; la réponse est renvoyée au client lorsque le message contient `callbackid`, avec `success: true` et `data`, ou `error: true` et les éléments d'erreur.\n\nExample: Traiter une API\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nChiffre les messages avec `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Par défaut `true` |\n\nReturns: `WebSocket`\n\nLorsqu'il est activé et que `CONF.secret_encryption` est défini, les messages texte sortants sont chiffrés et les messages entrants déchiffrés. Sans argument, il active le chiffrement.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nUn client s'est connecté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Le nouveau client |\n\nÉmis après que le client a rejoint le contrôleur : `this.online` le compte donc déjà.\n\nExample: Bienvenue\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nUn client a envoyé un message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | L'expéditeur |\n| `message` | `Object/String/Buffer` | yes |  | Le message |\n\n`message` est un objet dans les routes `json`, une chaîne dans les routes `text` et un `Buffer` dans les routes `binary` ou `buffer`.\n\nExample: Écho\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nUn client s'est déconnecté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Le client |\n| `code` | `Number` | yes |  | Code de fermeture |\n| `message` | `String` | yes |  | Motif de fermeture |\n\n`code` et `message` proviennent de la trame de fermeture du client, lorsqu'il en a envoyé une.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nUne erreur de socket s'est produite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | L'erreur |\n| `client` | `Object` | yes |  | Le client |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nLe contrôleur est en cours de destruction.\n\n### client.id\n\nType: `property`\n\nL'id unique de la connexion.\n\nReturns: `String`\n\nUne chaîne numérique. Elle est aussi disponible sous `client.ID` et sert de clé dans `websocket.connections`. `client.online` vaut `true` tant que la connexion est ouverte, et `client.controller` (ou `client.container`) est le contrôleur WebSocket.\n\n### client.user\n\nType: `property`\n\nL'utilisateur accepté par `AUTH()`.\n\nReturns: `Object`\n\nTu peux aussi lui affecter une valeur. `client.session` et `client.sessionid` contiennent les valeurs de session issues de la requête.\n\nExample: Message privé\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nLa query string de l'URL de connexion.\n\nReturns: `Object`\n\nLes valeurs sont des chaînes. `client.get` est un alias.\n\nExample: Jeton dans l'URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nLes en-têtes de la requête d'upgrade.\n\nReturns: `Object`\n\nÉgalement disponibles : `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` et `client.req`. `client.protocol` est le tableau des sous-protocoles issus de `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nLa latence du dernier ping en ms.\n\nReturns: `Number`\n\nDéfinie lorsque le client répond à un ping. Les clients sans réponse ou dont la latence dépasse `CONF.default_websocket_maxlatency` sont fermés.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvoie un message à ce client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Le message |\n| `raw` | `Boolean` | yes |  | Ne pas sérialiser (routes json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON ; `true` utilise le replacer du framework |\n\nReturns: `Object` Le client\n\nDans une route `json`, les objets sont sérialisés ; avec `raw` à `true`, le message est envoyé tel quel (une chaîne JSON que tu as déjà). Dans une route `text`, les objets sont sérialisés et les autres valeurs converties en chaînes. Dans une route `binary`, le message doit être un `Buffer`. Rien ne se passe si le client est fermé.\n\nExample: Répondre\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nFerme cette connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motif de fermeture |\n| `code` | `Number` | yes |  | Code de fermeture, par défaut `1000` |\n\nReturns: `Object` Le client\n\nEnvoie une trame de fermeture avec `code` (par défaut `1000`) et `message`. Les arguments peuvent aussi être passés dans l'ordre `(code, message)`.\n\nExample: Expulser un client\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nLit un cookie de la requête d'upgrade.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du cookie |\n\nReturns: `String`\n\nExample: Lire un cookie\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nRetourne le nom d'hôte avec un chemin facultatif.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Chemin à ajouter |\n\nReturns: `String`\n\n`client.host()` est un alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nTrouve un contrôleur WebSocket par son id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Partie de l'id ou expression régulière |\n\nReturns: `WebSocket` Le contrôleur ou `undefined`\n\nRetourne le premier contrôleur dont l'id contient `path` (ou correspond à une `RegExp`). Les contrôleurs sont conservés dans `F.connections`.\n\nExample: Envoyer depuis une route HTTP\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nTrouve des contrôleurs WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Partie de l'id ou expression régulière |\n\nReturns: `Array`\n\nSans `path`, elle retourne tous les contrôleurs.\n\nExample: Tous les salons\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nUn client a rejoint un contrôleur WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Le contrôleur |\n| `client` | `Object` | yes |  | Le client |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nUn client a quitté un contrôleur WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Le contrôleur |\n| `client` | `Object` | yes |  | Le client |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nLa taille maximale par défaut d'un message en ko.\n\nReturns: `Number`\n\nPar défaut `2`. Une route la remplace par sa `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nLa latence maximale du ping en ms.\n\nReturns: `Number`\n\nPar défaut `2000`. Les clients dont la latence est plus élevée, ou sans pong, sont fermés. `0` désactive le ping. Le ping s'exécute toutes les `CONF.default_interval_websocket_ping` ms (par défaut `20000` ; les valeurs inférieures à `1000` utilisent `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nActive les routes WebSocket.\n\nReturns: `Boolean`\n\nPar défaut `true`. `CONF.allow_websocket_compression` (par défaut `true`) autorise `permessage-deflate`, et `CONF.default_websocket_encodedecode` (par défaut `false`) active l'encodage URI des messages.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrée un client WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` est appelé immédiatement avec le nouveau client (également comme `this`). Définis-y les options, les en-têtes et les événements, puis appelle `client.connect()`.\n\nExample: Se connecter\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nOptions du client.\n\nReturns: `Object`\n\n- `type` (`'json'`) : `json`, `text`, `binary` ou `buffer`.\n- `compress` (`true`) : demande `permessage-deflate`.\n- `reconnect` (`3000`) : ms avant la reconnexion après une connexion fermée ; `0` la désactive.\n- `reconnectserver` (`false`) : se reconnecte aussi après une erreur de connexion ou une réponse HTTP inattendue.\n- `masking` (`false`) : masque les trames sortantes.\n- `encodedecode` (`false`) : encodage URI des messages.\n- `encrypt` : un secret pour chiffrer et déchiffrer les messages texte.\n- `length` : taille maximale d'un message décompressé en octets.\n- `rejectunauthorized` (`false`) : rejette les certificats TLS invalides.\n- `key`, `cert`, `dhparam` : options TLS.\n\nExample: Client texte\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nEn-têtes supplémentaires de la requête d'upgrade.\n\nReturns: `Object`\n\n`websocketclient.cookies` est un objet de cookies envoyés dans l'en-tête `Cookie`.\n\nExample: Jeton\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true` lorsque le client n'est pas connecté.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` compte les reconnexions.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nLa latence du dernier ping en ms.\n\nReturns: `Number`\n\nDéfinie lorsque le serveur répond à `ping()`.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOuvre la connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | URL du serveur |\n| `protocol` | `String` | yes |  | Sous-protocole |\n| `origin` | `String` | yes |  | Origine |\n\n`url` commence par `ws://` ou `wss://`. Il peut aussi s'agir d'un objet `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` est envoyé dans `Sec-WebSocket-Protocol` et `origin` dans `Sec-WebSocket-Origin`. La connexion démarre au tick suivant.\n\nExample: Avec un protocole\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nEnvoie un message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Le message |\n| `raw` | `Boolean` | yes |  | Ne pas sérialiser (json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n\nReturns: `Boolean` `true` lorsque le message est envoyé\n\nAvec `type: 'json'`, les objets sont sérialisés (sauf si `raw` vaut `true`). Avec `text`, les objets sont sérialisés et les autres valeurs converties en chaînes. Avec `binary` ou `buffer`, un message qui n'est pas un `Buffer` est converti en `Buffer`. Retourne `false` lorsque le client est fermé.\n\nExample: Envoyer\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nFerme la connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Motif de fermeture, ou `true` pour se reconnecter |\n| `code` | `Number` | yes |  | Code de fermeture, par défaut `1000` |\n\nReturns: `WebSocketClient`\n\nEnvoie une trame de fermeture avec `code` (par défaut `1000`). Elle arrête aussi la reconnexion, sauf si `message` vaut `true` : la connexion se ferme alors et le client se reconnecte. Les arguments peuvent être passés sous la forme `(code, message)`.\n\nExample: Se reconnecter\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nLibère le client et arrête la reconnexion.\n\nÉmet `destroy` et supprime tous les gestionnaires d'événements.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nEnvoie un ping au serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Par défaut `3000` ms |\n\nReturns: `WebSocketClient`\n\nSi aucun pong n'arrive dans les `timeout` ms (par défaut `3000`), le client émet `error` avec `'Timeout'` et se ferme. Le pong définit `latency`.\n\nExample: Mesurer la latence\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nAppelle l'API WebSocket d'un serveur Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Opération, par ex. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Données envoyées |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Par défaut `5000` ms |\n\nReturns: `WebSocketClient`\n\nEnvoie `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` reçoit la réponse ; `err` vaut `408` après `timeout` ms (par défaut `5000`). Sans `schema`, elle enregistre uniquement le gestionnaire des réponses.\n\nExample: Appeler une opération\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nEnregistre un gestionnaire d'événement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'événement |\n| `callback` | `Function` | yes |  | Gestionnaire |\n\nReturns: `WebSocketClient`\n\nÉvénements : `open()`, `message(data)`, `close(code, message)`, `error(err)` et `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` et `emit()` fonctionnent comme dans le contrôleur.\n\nExample: Événements\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nLa session de la connexion.\n\nReturns: `Object`\n\nLa session définie par ton délégué `AUTH()` pour la requête d'upgrade. `client.sessionid` est son id. Elle peut être définie.\n\nExample: Exemple\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nEnvoie une trame ping à ce client.\n\nReturns: `Object` Le client.\n\nLa réponse du client met à jour `client.latency`. `websocket.ping()` envoie un ping à tous les clients.\n\nExample: Envoyer un ping à un client\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nL'URL du dernier `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` et `websocketclient.origin` conservent les autres arguments de `connect()`.\n\nExample: Exemple\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWc91e361f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"WebSocket","summary":"La route SOCKET, il controller WebSocket, il client connesso e WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSocket\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSocket\n\n> La route SOCKET, il controller WebSocket, il client connesso e WEBSOCKETCLIENT().\n\nUna route `SOCKET` crea un controller WebSocket condiviso da tutti i client di un URL; ogni connessione è un oggetto client, e `WEBSOCKETCLIENT()` si connette dal server ad altri server WebSocket. La guida [WebSocket](../../guides/websockets/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDichiara una route WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, facoltativamente con `+`/`-`, `{params}` e `@apiname` |\n| `action` | `Function` | yes |  | Inizializza il controller WebSocket |\n| `flags` | `Array` | yes |  | Flag, origini, protocolli, middleware, una lunghezza o un oggetto di opzioni |\n| `length` | `Number` | yes |  | Dimensione massima del messaggio in kB |\n\nReturns: `FrameworkRoute` L'istanza della route\n\nL'URL inizia con `SOCKET` (o `WS`, `WSS`). Un `+` o `-` davanti limita la route agli utenti autenticati o anonimi. `action` viene eseguita una sola volta, quando il primo client si connette all'URL, con il controller WebSocket come `this` e i parametri dinamici dell'URL come argomenti. `length` è la dimensione massima di un messaggio in kB (predefinito `CONF.default_websocket_maxlength`, `2`). Con `@name` nell'URL e senza azione, la route elabora la WebSocket API `@name` e si distrugge quando l'ultimo client se ne va.\n\nI flag sono descritti nella voce **WebSocket route flags**.\n\nExample: Route di chat\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: WebSocket API senza azione\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlag che impostano il tipo di dati, l'accesso, le origini e i protocolli di una route WebSocket.\n\n- `json` (predefinito): i messaggi in arrivo vengono analizzati come JSON (il JSON non valido viene ignorato) e gli oggetti in uscita vengono serializzati.\n- `text`, `plain`: i messaggi sono stringhe; gli oggetti che invii vengono serializzati come JSON.\n- `binary`: i messaggi sono oggetti `Buffer`.\n- `raw`: disattiva `json` e `binary` (modalità testo).\n- `buffer`: l'evento `message` riceve sempre il `Buffer` grezzo.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: solo utenti autenticati o anonimi.\n- `@role`: un flag di ruolo; rende la route `authorize`.\n- `http://...`, `https://...`: origini consentite; l'`Origin` della richiesta deve contenerne una.\n- `#middleware`, `&middleware`: nomi di middleware.\n- `id:name`: l'identificatore della route.\n- `get`, `csrf`, `http`, `https`, `debug`, `release`: flag standard delle route.\n- Qualsiasi altra parola è un sotto-protocollo obbligatorio. Ogni protocollo elencato deve essere nell'intestazione `Sec-WebSocket-Protocol` del client, altrimenti la connessione viene chiusa con `4001`.\n- Un numero è la dimensione massima del messaggio in kB; un oggetto sono le opzioni del middleware.\n\nExample: Route binaria per un'origine\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Sotto-protocollo obbligatorio\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nIl numero di client connessi.\n\nReturns: `Number`\n\nAggiornato ogni volta che un client si connette o si disconnette.\n\nExample: Trasmettere il conteggio\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nTutti i client connessi, per id.\n\nReturns: `Object`\n\nUn oggetto le cui chiavi sono gli id dei client e i cui valori sono gli oggetti client. `websocket.keys` contiene gli stessi id come array. `websocket.id` è la chiave del controller in `F.connections`: l'URL seguito da `#` e dai flag della route.\n\nExample: Leggere un client\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nL'URL della connessione.\n\nReturns: `String`\n\nIl percorso a cui si è connesso il primo client, con una barra finale.\n\n### websocket.params\n\nType: `property`\n\nI parametri dinamici dell'URL.\n\nReturns: `Object`\n\nOgni `{name}` della route diventa una chiave. Gli stessi valori arrivano come argomenti dell'azione.\n\nExample: Nome della stanza\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nUn oggetto per i tuoi dati.\n\nReturns: `Object`\n\nCreato al primo accesso e mantenuto per tutta la vita del controller.\n\nExample: Conservare la cronologia\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nRegistra un gestore di eventi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'evento |\n| `callback` | `Function` | yes |  | Gestore |\n\nReturns: `WebSocket` Il controller\n\nEventi: `open`, `close`, `message`, `error` e `destroy`. `this` nel gestore è il controller. `once(name, fn)` registra un gestore per una sola chiamata, `removeListener(name, fn)` e `removeAllListeners([name])` rimuovono i gestori, e `emit(name, [args...])` chiama i gestori dei tuoi eventi.\n\nExample: Eventi\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nInvia un messaggio a tutti i client o ai client che selezioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Il messaggio |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` restituisce `true` per inviare |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n| `params` | `Object` | yes |  | Valore passato a `comparer` |\n\nReturns: `WebSocket`\n\nIn una route `json` il messaggio viene serializzato una sola volta e inviato a ogni client. `comparer(client, message, params)` restituisce `true` per i client che ricevono il messaggio. `replacer` viene passato a `JSON.stringify()`; `true` usa il replacer JSON del framework. Quando il terzo argomento non è una funzione, viene usato come `params`.\n\nExample: Tutti tranne il mittente\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: Con params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nTrova il primo client che corrisponde a una funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` restituisce `true` per il client cercato |\n\nReturns: `Object` Il client o `undefined`\n\nRestituisce `undefined` quando nessun client corrisponde.\n\nExample: Trovare un utente\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nRestituisce tutti i client connessi come array.\n\nReturns: `Array`\n\nExample: Elencare gli utenti\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nChiude tutti i client connessi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motivo della chiusura |\n| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |\n\nReturns: `WebSocket`\n\nOgni client riceve un frame di chiusura con `code` (predefinito `1000`) e `message`. Il controller resta; usa `destroy()` per rimuoverlo.\n\nExample: Chiudere tutti\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nChiude tutti i client e rimuove il controller.\n\nReturns: `WebSocket`\n\nEmette `destroy`, rimuove il controller da `F.connections` e lo libera. Il client successivo dell'URL crea un nuovo controller.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nDistrugge il controller quando nessun client è online.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Chiamata prima che il controller venga distrutto |\n\nReturns: `WebSocket`\n\nQuando l'ultimo client si disconnette e nessuno si connette entro 5 secondi, viene chiamato `callback` (con il controller come `this`) e il controller viene distrutto. Chiamarlo di nuovo aggiunge un'altra callback.\n\nExample: Distruzione automatica\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nInvia un ping a tutti i client.\n\nReturns: `WebSocket`\n\nIl framework lo chiama da solo ogni `CONF.default_interval_websocket_ping` ms. La risposta pong imposta `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nElabora i messaggi della WebSocket API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'API, con o senza `@` |\n\nReturns: `WebSocket`\n\nRegistra un gestore `message` che esegue le route `API` con il `@name` indicato per i messaggi il cui `TYPE` è `api`. Il `data` del messaggio è `{ schema: 'operation/param', data: {} }`; la risposta viene rimandata al client quando il messaggio ha `callbackid`, con `success: true` e `data`, oppure `error: true` e gli elementi di errore.\n\nExample: Elaborare un'API\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nCifra i messaggi con `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Predefinito `true` |\n\nReturns: `WebSocket`\n\nQuando è abilitato e `CONF.secret_encryption` è impostato, i messaggi di testo in uscita vengono cifrati e quelli in arrivo decifrati. Senza argomento abilita la cifratura.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nUn client si è connesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Il nuovo client |\n\nEmesso dopo che il client si è unito al controller, quindi `this.online` lo conta già.\n\nExample: Benvenuto\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nUn client ha inviato un messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Il mittente |\n| `message` | `Object/String/Buffer` | yes |  | Il messaggio |\n\n`message` è un oggetto nelle route `json`, una stringa nelle route `text` e un `Buffer` nelle route `binary` o `buffer`.\n\nExample: Eco\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nUn client si è disconnesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Il client |\n| `code` | `Number` | yes |  | Codice di chiusura |\n| `message` | `String` | yes |  | Motivo della chiusura |\n\n`code` e `message` provengono dal frame di chiusura del client, quando ne ha inviato uno.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nSi è verificato un errore del socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | L'errore |\n| `client` | `Object` | yes |  | Il client |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nIl controller sta per essere distrutto.\n\n### client.id\n\nType: `property`\n\nL'id univoco della connessione.\n\nReturns: `String`\n\nUna stringa numerica. È disponibile anche come `client.ID` ed è la chiave in `websocket.connections`. `client.online` è `true` finché la connessione è aperta, e `client.controller` (o `client.container`) è il controller WebSocket.\n\n### client.user\n\nType: `property`\n\nL'utente accettato da `AUTH()`.\n\nReturns: `Object`\n\nPuoi anche assegnare un valore. `client.session` e `client.sessionid` contengono i valori di sessione della richiesta.\n\nExample: Messaggio privato\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nLa query string dell'URL della connessione.\n\nReturns: `Object`\n\nI valori sono stringhe. `client.get` è un alias.\n\nExample: Token nell'URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nLe intestazioni della richiesta di upgrade.\n\nReturns: `Object`\n\nDisponibili anche: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` e `client.req`. `client.protocol` è l'array dei sotto-protocolli da `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nLa latenza dell'ultimo ping in ms.\n\nReturns: `Number`\n\nImpostata quando il client risponde a un ping. I client senza risposta o con una latenza superiore a `CONF.default_websocket_maxlatency` vengono chiusi.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nInvia un messaggio a questo client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Il messaggio |\n| `raw` | `Boolean` | yes |  | Non serializzare (route json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON; `true` usa il replacer del framework |\n\nReturns: `Object` Il client\n\nIn una route `json` gli oggetti vengono serializzati; con `raw` impostato a `true` il messaggio viene inviato così com'è (una stringa JSON che hai già). In una route `text` gli oggetti vengono serializzati e gli altri valori convertiti in stringhe. In una route `binary` il messaggio deve essere un `Buffer`. Non succede nulla se il client è chiuso.\n\nExample: Rispondere\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nChiude questa connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Motivo della chiusura |\n| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |\n\nReturns: `Object` Il client\n\nInvia un frame di chiusura con `code` (predefinito `1000`) e `message`. Gli argomenti possono essere passati anche nell'ordine `(code, message)`.\n\nExample: Espellere un client\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nLegge un cookie della richiesta di upgrade.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del cookie |\n\nReturns: `String`\n\nExample: Leggere un cookie\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nRestituisce l'hostname con un percorso facoltativo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Percorso da aggiungere |\n\nReturns: `String`\n\n`client.host()` è un alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nTrova un controller WebSocket tramite il suo id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Parte dell'id o un'espressione regolare |\n\nReturns: `WebSocket` Il controller o `undefined`\n\nRestituisce il primo controller il cui id contiene `path` (o corrisponde a una `RegExp`). I controller sono tenuti in `F.connections`.\n\nExample: Inviare da una route HTTP\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nTrova controller WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Parte dell'id o un'espressione regolare |\n\nReturns: `Array`\n\nSenza `path` restituisce tutti i controller.\n\nExample: Tutte le stanze\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nUn client si è unito a un controller WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Il controller |\n| `client` | `Object` | yes |  | Il client |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nUn client ha lasciato un controller WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Il controller |\n| `client` | `Object` | yes |  | Il client |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nLa dimensione massima predefinita del messaggio in kB.\n\nReturns: `Number`\n\nPredefinito `2`. Una route lo sovrascrive con il suo `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nLa latenza massima del ping in ms.\n\nReturns: `Number`\n\nPredefinito `2000`. I client con una latenza superiore, o senza pong, vengono chiusi. `0` disattiva il ping. Il ping viene eseguito ogni `CONF.default_interval_websocket_ping` ms (predefinito `20000`; i valori inferiori a `1000` usano `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nAbilita le route WebSocket.\n\nReturns: `Boolean`\n\nPredefinito `true`. `CONF.allow_websocket_compression` (predefinito `true`) consente `permessage-deflate`, e `CONF.default_websocket_encodedecode` (predefinito `false`) attiva la codifica URI dei messaggi.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nCrea un client WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` viene chiamata subito con il nuovo client (anche come `this`). Imposta lì opzioni, intestazioni ed eventi, poi chiama `client.connect()`.\n\nExample: Connettersi\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nOpzioni del client.\n\nReturns: `Object`\n\n- `type` (`'json'`): `json`, `text`, `binary` o `buffer`.\n- `compress` (`true`): richiede `permessage-deflate`.\n- `reconnect` (`3000`): ms prima di riconnettersi dopo la chiusura della connessione; `0` lo disattiva.\n- `reconnectserver` (`false`): si riconnette anche dopo un errore di connessione o una risposta HTTP inattesa.\n- `masking` (`false`): applica il masking ai frame in uscita.\n- `encodedecode` (`false`): codifica URI dei messaggi.\n- `encrypt`: un segreto per cifrare e decifrare i messaggi di testo.\n- `length`: dimensione massima di un messaggio decompresso in byte.\n- `rejectunauthorized` (`false`): rifiuta i certificati TLS non validi.\n- `key`, `cert`, `dhparam`: opzioni TLS.\n\nExample: Client di testo\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nIntestazioni aggiuntive della richiesta di upgrade.\n\nReturns: `Object`\n\n`websocketclient.cookies` è un oggetto di cookie inviati nell'intestazione `Cookie`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true` quando il client non è connesso.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` conta le riconnessioni.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nLa latenza dell'ultimo ping in ms.\n\nReturns: `Number`\n\nImpostata quando il server risponde a `ping()`.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nApre la connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | URL del server |\n| `protocol` | `String` | yes |  | Sotto-protocollo |\n| `origin` | `String` | yes |  | Origine |\n\n`url` inizia con `ws://` o `wss://`. Può essere anche un oggetto `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` viene inviato in `Sec-WebSocket-Protocol` e `origin` in `Sec-WebSocket-Origin`. La connessione parte al tick successivo.\n\nExample: Con un protocollo\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nInvia un messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Il messaggio |\n| `raw` | `Boolean` | yes |  | Non serializzare (json) |\n| `replacer` | `Function/Boolean` | yes |  | Replacer JSON |\n\nReturns: `Boolean` `true` quando è stato inviato\n\nCon `type: 'json'` gli oggetti vengono serializzati (a meno che `raw` sia `true`). Con `text` gli oggetti vengono serializzati e gli altri valori convertiti in stringhe. Con `binary` o `buffer` un messaggio che non è un `Buffer` viene convertito in `Buffer`. Restituisce `false` quando il client è chiuso.\n\nExample: Inviare\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nChiude la connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Motivo della chiusura, o `true` per riconnettersi |\n| `code` | `Number` | yes |  | Codice di chiusura, predefinito `1000` |\n\nReturns: `WebSocketClient`\n\nInvia un frame di chiusura con `code` (predefinito `1000`). Interrompe anche la riconnessione, a meno che `message` sia `true`: in quel caso la connessione si chiude e il client si riconnette. Gli argomenti possono essere passati come `(code, message)`.\n\nExample: Riconnettersi\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nLibera il client e interrompe la riconnessione.\n\nEmette `destroy` e rimuove tutti i gestori di eventi.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nInvia un ping al server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Predefinito `3000` ms |\n\nReturns: `WebSocketClient`\n\nSe non arriva un pong entro `timeout` ms (predefinito `3000`), il client emette `error` con `'Timeout'` e si chiude. Il pong imposta `latency`.\n\nExample: Misurare la latenza\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nChiama la WebSocket API di un server Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operazione, ad es. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Payload |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Predefinito `5000` ms |\n\nReturns: `WebSocketClient`\n\nInvia `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` riceve la risposta; `err` è `408` dopo `timeout` ms (predefinito `5000`). Senza `schema` registra solo il gestore delle risposte.\n\nExample: Chiamare un'operazione\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nRegistra un gestore di eventi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'evento |\n| `callback` | `Function` | yes |  | Gestore |\n\nReturns: `WebSocketClient`\n\nEventi: `open()`, `message(data)`, `close(code, message)`, `error(err)` e `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` ed `emit()` funzionano come nel controller.\n\nExample: Eventi\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nLa sessione della connessione.\n\nReturns: `Object`\n\nLa sessione impostata dal tuo delegato `AUTH()` per la richiesta di upgrade. `client.sessionid` è il suo id. Può essere impostata.\n\nExample: Esempio\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nInvia un frame di ping a questo client.\n\nReturns: `Object` Il client.\n\nLa risposta del client aggiorna `client.latency`. `websocket.ping()` invia un ping a tutti i client.\n\nExample: Ping a un client\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nL'URL dell'ultimo `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` e `websocketclient.origin` conservano gli altri argomenti di `connect()`.\n\nExample: Esempio\n\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWc91e361f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/websockets/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"WebSockety","summary":"Routa SOCKET, WebSocket kontrolér, pripojený klient a WEBSOCKETCLIENT().","markdown":"---\ntitle: WebSockety\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/websockets/\nupdated: 2026-11-16T15:41:00.817Z\n---\n\n# WebSockety\n\n> Routa SOCKET, WebSocket kontrolér, pripojený klient a WEBSOCKETCLIENT().\n\nRouta `SOCKET` vytvorí WebSocket kontrolér zdieľaný všetkými klientmi jednej URL; každé spojenie je objekt klienta a `WEBSOCKETCLIENT()` sa zo servera pripája k iným WebSocket serverom. Príručka [WebSockety](../../guides/websockets/) vysvetľuje ich použitie s príkladmi; táto stránka je presná referencia.\n\n## API\n\n### ROUTE('SOCKET /url/', action, [flags], [length])\n\nType: `method`\n\nDeklaruje WebSocket routu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | `SOCKET /path/`, voliteľne s `+`/`-`, `{params}` a `@apiname` |\n| `action` | `Function` | yes |  | Inicializuje WebSocket kontrolér |\n| `flags` | `Array` | yes |  | Flagy, pôvody, protokoly, middleware, dĺžka alebo objekt možností |\n| `length` | `Number` | yes |  | Maximálna veľkosť správy v kB |\n\nReturns: `FrameworkRoute` Inštancia routy\n\nURL začína `SOCKET` (alebo `WS`, `WSS`). `+` alebo `-` pred ňou obmedzí routu na prihlásených alebo anonymných používateľov. `action` sa spustí raz, keď sa k URL pripojí prvý klient, s WebSocket kontrolérom ako `this` a dynamickými parametrami URL ako argumentmi. `length` je maximálna veľkosť jednej správy v kB (predvolene `CONF.default_websocket_maxlength`, `2`). S `@name` v URL a bez akcie routa spracúva WebSocket API `@name` a zničí sa, keď odíde posledný klient.\n\nFlagy sú opísané v položke **Flagy WebSocket routy**.\n\nExample: Routa pre chat\n```js\nexports.install = function() {\n\tROUTE('SOCKET /chat/{room}/', chat, ['json'], 32);\n};\n\nfunction chat(room) {\n\tvar self = this;\n\tself.autodestroy();\n\tself.on('message', function(client, message) {\n\t\tself.send({ room: room, body: message.body });\n\t});\n}\n```\n\nExample: WebSocket API bez akcie\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/ @chat');\n};\n```\n\n### ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])\n\nType: `config`\n\nFlagy, ktoré nastavujú dátový typ, prístup, pôvody a protokoly WebSocket routy.\n\n- `json` (predvolené): prichádzajúce správy sa parsujú ako JSON (neplatný JSON sa ignoruje) a odchádzajúce objekty sa serializujú.\n- `text`, `plain`: správy sú reťazce; objekty, ktoré posielaš, sa serializujú ako JSON.\n- `binary`: správy sú objekty `Buffer`.\n- `raw`: vypne `json` a `binary` (textový režim).\n- `buffer`: udalosť `message` vždy dostane nespracovaný `Buffer`.\n- `authorize`, `authorized`, `logged` / `unauthorize`, `unauthorized`, `unlogged`: iba prihlásení alebo iba anonymní používatelia.\n- `@role`: flag roly; urobí z routy `authorize`.\n- `http://...`, `https://...`: povolené pôvody; `Origin` požiadavky musí obsahovať jeden z nich.\n- `#middleware`, `&middleware`: názvy middlewarov.\n- `id:name`: identifikátor routy.\n- `get`, `csrf`, `http`, `https`, `debug`, `release`: štandardné flagy rout.\n- Akékoľvek iné slovo je povinný subprotokol. Každý uvedený protokol musí byť v hlavičke `Sec-WebSocket-Protocol` klienta, inak sa spojenie zatvorí s `4001`.\n- Číslo je maximálna veľkosť správy v kB; objekt sú možnosti middlewaru.\n\nExample: Binárna routa pre jeden pôvod\n```js\nROUTE('SOCKET /upload/', upload, ['binary', 'https://app.example.com'], 1024);\n\nfunction upload() {\n\tthis.on('message', function(client, buffer) {\n\t\t// buffer is a Buffer\n\t});\n}\n```\n\nExample: Povinný subprotokol\n```js\n// The browser: new WebSocket('wss://example.com/rpc/', 'rpc');\nROUTE('SOCKET /rpc/', rpc, ['rpc']);\n```\n\n### websocket.online\n\nType: `property`\n\nPočet pripojených klientov.\n\nReturns: `Number`\n\nAktualizuje sa vždy, keď sa klient pripojí alebo odpojí.\n\nExample: Rozoslanie počtu\n```js\nfunction counter() {\n\tvar self = this;\n\tself.on('open', function() {\n\t\tself.send({ online: self.online });\n\t});\n}\n```\n\n### websocket.connections\n\nType: `property`\n\nVšetci pripojení klienti podľa ich id.\n\nReturns: `Object`\n\nObjekt, ktorého kľúče sú id klientov a hodnoty sú objekty klientov. `websocket.keys` obsahuje tie isté id ako pole. `websocket.id` je kľúč kontroléra v `F.connections`: URL, za ňou `#` a flagy routy.\n\nExample: Načítanie klienta\n```js\nvar client = this.connections['15'];\n```\n\n### websocket.url\n\nType: `property`\n\nURL spojenia.\n\nReturns: `String`\n\nCesta, ku ktorej sa pripojil prvý klient, s lomkou na konci.\n\n### websocket.params\n\nType: `property`\n\nDynamické parametre URL.\n\nReturns: `Object`\n\nKaždé `{name}` routy sa stane kľúčom. Tie isté hodnoty prichádzajú ako argumenty akcie.\n\nExample: Názov miestnosti\n```js\nROUTE('SOCKET /rooms/{name}/', room);\n\nfunction room(name) {\n\t// name === this.params.name\n}\n```\n\n### websocket.repository\n\nType: `property`\n\nObjekt pre tvoje vlastné dáta.\n\nReturns: `Object`\n\nVytvorí sa pri prvom prístupe a existuje počas celej životnosti kontroléra.\n\nExample: Uchovanie histórie\n```js\nfunction chat() {\n\tvar self = this;\n\tself.repository.history = [];\n\tself.on('message', function(client, message) {\n\t\tself.repository.history.push(message);\n\t});\n}\n```\n\n### websocket.on(name, callback)\n\nType: `method`\n\nZaregistruje obsluhu udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti |\n| `callback` | `Function` | yes |  | Obsluha |\n\nReturns: `WebSocket` Kontrolér\n\nUdalosti: `open`, `close`, `message`, `error` a `destroy`. `this` v obsluhe je kontrolér. `once(name, fn)` zaregistruje obsluhu na jedno volanie, `removeListener(name, fn)` a `removeAllListeners([name])` obsluhy odstránia a `emit(name, [args...])` zavolá obsluhy tvojich vlastných udalostí.\n\nExample: Udalosti\n```js\nfunction chat() {\n\tthis.on('open', function(client) {});\n\tthis.on('message', function(client, message) {});\n\tthis.on('close', function(client, code, message) {});\n}\n```\n\n### websocket.send(message, [comparer], [replacer], [params])\n\nType: `method`\n\nPošle správu všetkým klientom alebo klientom, ktorých vyberieš.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Správa |\n| `comparer` | `Function` | yes |  | `function(client, message, params)` vráti `true` na odoslanie |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer |\n| `params` | `Object` | yes |  | Hodnota odovzdaná do `comparer` |\n\nReturns: `WebSocket`\n\nV route `json` sa správa serializuje raz a pošle každému klientovi. `comparer(client, message, params)` vráti `true` pre klientov, ktorí správu dostanú. `replacer` sa odovzdá do `JSON.stringify()`; `true` použije JSON replacer frameworku. Keď tretí argument nie je funkcia, použije sa ako `params`.\n\nExample: Všetkým okrem odosielateľa\n```js\nself.on('message', function(client, message) {\n\tself.send(message, function(c) {\n\t\treturn c !== client;\n\t});\n});\n```\n\nExample: S params\n```js\nself.send({ type: 'refresh' }, function(client, message, params) {\n\treturn client.user && client.user.role === params.role;\n}, { role: 'admin' });\n```\n\n### websocket.find(fn)\n\nType: `method`\n\nNájde prvého klienta, ktorý vyhovuje funkcii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(client)` vráti `true` pre hľadaného klienta |\n\nReturns: `Object` Klient alebo `undefined`\n\nVráti `undefined`, keď nevyhovuje žiadny klient.\n\nExample: Nájdenie používateľa\n```js\nvar client = this.find(function(client) {\n\treturn client.user && client.user.id === userid;\n});\nclient && client.send({ type: 'notify' });\n```\n\n### websocket.clients()\n\nType: `method`\n\nVráti všetkých pripojených klientov ako pole.\n\nReturns: `Array`\n\nExample: Zoznam používateľov\n```js\nvar users = this.clients().map(function(client) {\n\treturn client.user ? client.user.name : 'anonymous';\n});\n```\n\n### websocket.close([message], [code])\n\nType: `method`\n\nZatvorí všetkých pripojených klientov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Dôvod zatvorenia |\n| `code` | `Number` | yes |  | Kód zatvorenia, predvolene `1000` |\n\nReturns: `WebSocket`\n\nKaždý klient dostane zatvárací rámec s `code` (predvolene `1000`) a `message`. Samotný kontrolér zostane; na jeho odstránenie použi `destroy()`.\n\nExample: Zatvorenie všetkých\n```js\nthis.close('Server restart', 4000);\n```\n\n### websocket.destroy()\n\nType: `method`\n\nZatvorí všetkých klientov a odstráni kontrolér.\n\nReturns: `WebSocket`\n\nVyvolá `destroy`, odstráni kontrolér z `F.connections` a uvoľní ho. Ďalší klient URL vytvorí nový kontrolér.\n\n### websocket.autodestroy([callback])\n\nType: `method`\n\nZničí kontrolér, keď nie je online žiadny klient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | Zavolá sa pred zničením kontroléra |\n\nReturns: `WebSocket`\n\nKeď sa odpojí posledný klient a do 5 sekúnd sa nikto nepripojí, zavolá sa `callback` (s kontrolérom ako `this`) a kontrolér sa zničí. Ďalšie volanie pridá ďalší callback.\n\nExample: Automatické zničenie\n```js\nfunction room() {\n\tthis.autodestroy(function() {\n\t\tconsole.log('Destroyed', this.url);\n\t});\n}\n```\n\n### websocket.ping()\n\nType: `method`\n\nPošle ping všetkým klientom.\n\nReturns: `WebSocket`\n\nFramework ho volá sám každých `CONF.default_interval_websocket_ping` ms. Odpoveď pong nastaví `client.latency`.\n\n### websocket.api(name)\n\nType: `method` · Since: `0.0.44`\n\nSpracúva správy WebSocket API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov API, s `@` alebo bez neho |\n\nReturns: `WebSocket`\n\nZaregistruje obsluhu `message`, ktorá spúšťa routy `API` s daným `@name` pre správy, ktorých `TYPE` je `api`. `data` správy je `{ schema: 'operation/param', data: {} }`; odpoveď sa pošle späť klientovi, keď správa obsahuje `callbackid`, so `success: true` a `data`, alebo s `error: true` a položkami chýb.\n\nExample: Spracovanie API\n```js\nexports.install = function() {\n\tROUTE('API @chat -messages_list *Messages --> list');\n\tROUTE('SOCKET /chat/', chat);\n};\n\nfunction chat() {\n\tthis.api('@chat');\n\tthis.autodestroy();\n}\n```\n\n### websocket.encrypt([enable])\n\nType: `method`\n\nŠifruje správy pomocou `CONF.secret_encryption`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Predvolene `true` |\n\nReturns: `WebSocket`\n\nKeď je zapnuté a `CONF.secret_encryption` je nastavené, odchádzajúce textové správy sa šifrujú a prichádzajúce dešifrujú. Bez argumentu šifrovanie zapne.\n\n### websocket.on('open', function(client) {})\n\nType: `event`\n\nKlient sa pripojil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Nový klient |\n\nVyvolá sa po tom, čo sa klient pripojil ku kontroléru, takže `this.online` ho už započítava.\n\nExample: Privítanie\n```js\nthis.on('open', function(client) {\n\tclient.send({ type: 'welcome' });\n});\n```\n\n### websocket.on('message', function(client, message) {})\n\nType: `event`\n\nKlient poslal správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Odosielateľ |\n| `message` | `Object/String/Buffer` | yes |  | Správa |\n\n`message` je objekt v routách `json`, reťazec v routách `text` a `Buffer` v routách `binary` alebo `buffer`.\n\nExample: Echo\n```js\nthis.on('message', function(client, message) {\n\tclient.send(message);\n});\n```\n\n### websocket.on('close', function(client, code, message) {})\n\nType: `event`\n\nKlient sa odpojil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `client` | `Object` | yes |  | Klient |\n| `code` | `Number` | yes |  | Kód zatvorenia |\n| `message` | `String` | yes |  | Dôvod zatvorenia |\n\n`code` a `message` pochádzajú zo zatváracieho rámca klienta, ak nejaký poslal.\n\n### websocket.on('error', function(err, client) {})\n\nType: `event`\n\nNastala chyba socketu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error` | yes |  | Chyba |\n| `client` | `Object` | yes |  | Klient |\n\n### websocket.on('destroy', function() {})\n\nType: `event`\n\nKontrolér sa ničí.\n\n### client.id\n\nType: `property`\n\nJedinečné id spojenia.\n\nReturns: `String`\n\nČíselný reťazec. Je dostupný aj ako `client.ID` a je kľúčom vo `websocket.connections`. `client.online` je `true`, kým je spojenie otvorené, a `client.controller` (alebo `client.container`) je WebSocket kontrolér.\n\n### client.user\n\nType: `property`\n\nPoužívateľ prijatý cez `AUTH()`.\n\nReturns: `Object`\n\nMôžeš mu priradiť aj hodnotu. `client.session` a `client.sessionid` obsahujú hodnoty session z požiadavky.\n\nExample: Súkromná správa\n```js\nvar client = self.find(function(c) {\n\treturn c.user && c.user.id === message.to;\n});\n```\n\n### client.query\n\nType: `property`\n\nQuery string URL spojenia.\n\nReturns: `Object`\n\nHodnoty sú reťazce. `client.get` je alias.\n\nExample: Token v URL\n```js\n// new WebSocket('wss://example.com/live/?channel=sport')\nthis.on('open', function(client) {\n\tclient.channel = client.query.channel;\n});\n```\n\n### client.headers\n\nType: `property`\n\nHlavičky upgrade požiadavky.\n\nReturns: `Object`\n\nDostupné sú aj: `client.ip`, `client.ua`, `client.url`, `client.uri`, `client.mobile`, `client.language` a `client.req`. `client.protocol` je pole subprotokolov z `Sec-WebSocket-Protocol`.\n\n### client.latency\n\nType: `property`\n\nLatencia posledného pingu v ms.\n\nReturns: `Number`\n\nNastaví sa, keď klient odpovie na ping. Klienti bez odpovede alebo s vyššou latenciou ako `CONF.default_websocket_maxlatency` sa zatvoria.\n\n### client.send(message, [raw], [replacer])\n\nType: `method`\n\nPošle správu tomuto klientovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Správa |\n| `raw` | `Boolean` | yes |  | Neserializovať (routy json) |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer; `true` použije replacer frameworku |\n\nReturns: `Object` Klient\n\nV route `json` sa objekty serializujú; s `raw` nastaveným na `true` sa správa pošle tak, ako je (JSON reťazec, ktorý už máš). V route `text` sa objekty serializujú a ostatné hodnoty sa prevedú na reťazce. V route `binary` musí byť správa `Buffer`. Ak je klient zatvorený, nestane sa nič.\n\nExample: Odpoveď\n```js\nthis.on('message', function(client, message) {\n\tclient.send({ ok: true, id: message.id });\n});\n```\n\n### client.close([message], [code])\n\nType: `method`\n\nZatvorí toto spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Dôvod zatvorenia |\n| `code` | `Number` | yes |  | Kód zatvorenia, predvolene `1000` |\n\nReturns: `Object` Klient\n\nPošle zatvárací rámec s `code` (predvolene `1000`) a `message`. Argumenty môžeš odovzdať aj v poradí `(code, message)`.\n\nExample: Vyhodenie klienta\n```js\nclient.close('Kicked', 4100);\n```\n\n### client.cookie(name)\n\nType: `method`\n\nNačíta cookie z upgrade požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie |\n\nReturns: `String`\n\nExample: Načítanie cookie\n```js\nvar token = client.cookie('token');\n```\n\n### client.hostname([path])\n\nType: `method`\n\nVráti názov hostiteľa s voliteľnou cestou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta, ktorá sa pripojí |\n\nReturns: `String`\n\n`client.host()` je alias.\n\n### F.findConnection(path)\n\nType: `method`\n\nNájde WebSocket kontrolér podľa jeho id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Časť id alebo regulárny výraz |\n\nReturns: `WebSocket` Kontrolér alebo `undefined`\n\nVráti prvý kontrolér, ktorého id obsahuje `path` (alebo vyhovuje `RegExp`). Kontroléry sú uložené v `F.connections`.\n\nExample: Odoslanie z HTTP routy\n```js\nfunction notify() {\n\tvar ws = F.findConnection('/notifications/');\n\tws && ws.send({ type: 'refresh' });\n\tthis.success();\n}\n```\n\n### F.findConnections([path])\n\nType: `method`\n\nNájde WebSocket kontroléry.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String/RegExp` | yes |  | Časť id alebo regulárny výraz |\n\nReturns: `Array`\n\nBez `path` vráti všetky kontroléry.\n\nExample: Všetky miestnosti\n```js\nF.findConnections('/rooms/').forEach(function(ws) {\n\tws.send({ type: 'shutdown' });\n});\n```\n\n### ON('websocket_begin', function(controller, client) {})\n\nType: `event`\n\nKlient sa pripojil k WebSocket kontroléru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Kontrolér |\n| `client` | `Object` | yes |  | Klient |\n\n### ON('websocket_end', function(controller, client) {})\n\nType: `event`\n\nKlient opustil WebSocket kontrolér.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Kontrolér |\n| `client` | `Object` | yes |  | Klient |\n\n### CONF.default_websocket_maxlength\n\nType: `config`\n\nPredvolená maximálna veľkosť správy v kB.\n\nReturns: `Number`\n\nPredvolene `2`. Routa ju prepíše svojou hodnotou `length`.\n\n### CONF.default_websocket_maxlatency\n\nType: `config` · Since: `0.0.59`\n\nMaximálna latencia pingu v ms.\n\nReturns: `Number`\n\nPredvolene `2000`. Klienti s vyššou latenciou alebo bez pongu sa zatvoria. `0` ping vypne. Ping beží každých `CONF.default_interval_websocket_ping` ms (predvolene `20000`; hodnoty pod `1000` použijú `20000`).\n\n### CONF.allow_websocket\n\nType: `config`\n\nZapne WebSocket routy.\n\nReturns: `Boolean`\n\nPredvolene `true`. `CONF.allow_websocket_compression` (predvolene `true`) povolí `permessage-deflate` a `CONF.default_websocket_encodedecode` (predvolene `false`) zapne URI kódovanie správ.\n\n### WEBSOCKETCLIENT([callback])\n\nType: `method`\n\nVytvorí WebSocket klienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(client)` |\n\nReturns: `WebSocketClient`\n\n`callback(client)` sa zavolá okamžite s novým klientom (aj ako `this`). Tam nastav možnosti, hlavičky a udalosti a potom zavolaj `client.connect()`.\n\nExample: Pripojenie\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.on('open', function() {\n\t\tclient.send({ type: 'hello' });\n\t});\n\tclient.on('message', function(message) {\n\t\tconsole.log(message);\n\t});\n\tclient.connect('wss://example.com/chat/');\n});\n```\n\n### websocketclient.options\n\nType: `property`\n\nMožnosti klienta.\n\nReturns: `Object`\n\n- `type` (`'json'`): `json`, `text`, `binary` alebo `buffer`.\n- `compress` (`true`): požiada o `permessage-deflate`.\n- `reconnect` (`3000`): ms pred opätovným pripojením po zatvorení spojenia; `0` to vypne.\n- `reconnectserver` (`false`): pripojí sa znova aj po chybe spojenia alebo neočakávanej HTTP odpovedi.\n- `masking` (`false`): maskuje odchádzajúce rámce.\n- `encodedecode` (`false`): URI kódovanie správ.\n- `encrypt`: tajný kľúč na šifrovanie a dešifrovanie textových správ.\n- `length`: maximálna veľkosť dekomprimovanej správy v bajtoch.\n- `rejectunauthorized` (`false`): odmietne neplatné TLS certifikáty.\n- `key`, `cert`, `dhparam`: TLS možnosti.\n\nExample: Textový klient\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.options.type = 'text';\n\tclient.options.reconnect = 10000;\n\tclient.connect('ws://127.0.0.1:8000/log/');\n});\n```\n\n### websocketclient.headers\n\nType: `property`\n\nĎalšie hlavičky upgrade požiadavky.\n\nReturns: `Object`\n\n`websocketclient.cookies` je objekt cookies odoslaných v hlavičke `Cookie`.\n\nExample: Token\n```js\nclient.headers['x-token'] = 'secret';\nclient.cookies.session = 'abc';\n```\n\n### websocketclient.closed\n\nType: `property`\n\n`true`, keď klient nie je pripojený.\n\nReturns: `Boolean`\n\n`websocketclient.reconnect` počíta opätovné pripojenia.\n\n### websocketclient.latency\n\nType: `property` · Since: `0.0.44`\n\nLatencia posledného pingu v ms.\n\nReturns: `Number`\n\nNastaví sa, keď server odpovie na `ping()`.\n\n### websocketclient.connect(url, [protocol], [origin])\n\nType: `method`\n\nOtvorí spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String/Object` | yes |  | URL servera |\n| `protocol` | `String` | yes |  | Subprotokol |\n| `origin` | `String` | yes |  | Pôvod (origin) |\n\n`url` začína `ws://` alebo `wss://`. Môže to byť aj objekt `{ socket: '/path/to/unix.socket', path: '/chat/' }`. `protocol` sa pošle v `Sec-WebSocket-Protocol` a `origin` v `Sec-WebSocket-Origin`. Spojenie sa začne v ďalšom ticku.\n\nExample: S protokolom\n```js\nclient.connect('wss://example.com/rpc/', 'rpc');\n```\n\n### websocketclient.send(message, [raw], [replacer])\n\nType: `method`\n\nPošle správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object/String/Buffer` | yes |  | Správa |\n| `raw` | `Boolean` | yes |  | Neserializovať (json) |\n| `replacer` | `Function/Boolean` | yes |  | JSON replacer |\n\nReturns: `Boolean` `true`, keď bola odoslaná\n\nS `type: 'json'` sa objekty serializujú (pokiaľ `raw` nie je `true`). S `text` sa objekty serializujú a ostatné hodnoty sa prevedú na reťazce. S `binary` alebo `buffer` sa správa, ktorá nie je `Buffer`, prevedie na `Buffer`. Vráti `false`, keď je klient zatvorený.\n\nExample: Odoslanie\n```js\nif (!client.send({ type: 'ping' }))\n\tconsole.log('Not connected');\n```\n\n### websocketclient.close([message], [code])\n\nType: `method`\n\nZatvorí spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String/Boolean` | yes |  | Dôvod zatvorenia, alebo `true` pre opätovné pripojenie |\n| `code` | `Number` | yes |  | Kód zatvorenia, predvolene `1000` |\n\nReturns: `WebSocketClient`\n\nPošle zatvárací rámec s `code` (predvolene `1000`). Zároveň zastaví opätovné pripájanie, pokiaľ `message` nie je `true`: vtedy sa spojenie zatvorí a klient sa znova pripojí. Argumenty môžeš odovzdať ako `(code, message)`.\n\nExample: Opätovné pripojenie\n```js\n// Close and connect again after options.reconnect ms\nclient.close(true);\n```\n\n### websocketclient.destroy()\n\nType: `method` · Since: `0.0.42`\n\nUvoľní klienta a zastaví opätovné pripájanie.\n\nVyvolá `destroy` a odstráni všetky obsluhy udalostí.\n\n### websocketclient.ping([timeout])\n\nType: `method` · Since: `0.0.44`\n\nPošle ping serveru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Predvolene `3000` ms |\n\nReturns: `WebSocketClient`\n\nAk do `timeout` ms (predvolene `3000`) nepríde pong, klient vyvolá `error` s `'Timeout'` a zatvorí sa. Pong nastaví `latency`.\n\nExample: Meranie latencie\n```js\nsetInterval(function() {\n\tclient.ping(5000);\n}, 30000);\n```\n\n### websocketclient.api([schema], [data], [callback], [timeout])\n\nType: `method` · Since: `0.0.44`\n\nVolá WebSocket API Total.js servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Operácia, napr. `'messages_read/123'` |\n| `data` | `Object` | yes |  | Dáta |\n| `callback` | `Function` | yes |  | `function(err, response)` |\n| `timeout` | `Number` | yes |  | Predvolene `5000` ms |\n\nReturns: `WebSocketClient`\n\nPošle `{ TYPE: 'api', data: { schema, data } }`. `callback(err, response)` dostane odpoveď; `err` je `408` po uplynutí `timeout` ms (predvolene `5000`). Bez `schema` iba zaregistruje obsluhu odpovedí.\n\nExample: Volanie operácie\n```js\nclient.api('messages_list', { page: 1 }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err);\n\telse\n\t\tconsole.log(response);\n});\n```\n\n### websocketclient.on(name, callback)\n\nType: `method`\n\nZaregistruje obsluhu udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti |\n| `callback` | `Function` | yes |  | Obsluha |\n\nReturns: `WebSocketClient`\n\nUdalosti: `open()`, `message(data)`, `close(code, message)`, `error(err)` a `destroy()`. `once()`, `removeListener()`, `removeAllListeners()` a `emit()` fungujú rovnako ako v kontroléri.\n\nExample: Udalosti\n```js\nclient.on('open', function() {});\nclient.on('message', function(data) {});\nclient.on('close', function(code, message) {});\nclient.on('error', function(err) {});\n```\n\n### client.session\n\nType: `property`\n\nSession spojenia.\n\nReturns: `Object`\n\nSession, ktorú pre upgrade požiadavku nastavil tvoj delegát `AUTH()`. `client.sessionid` je jej id. Dá sa nastaviť.\n\nExample: Príklad\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tconsole.log(client.sessionid, client.session);\n\t});\n}\n```\n\n### client.ping()\n\nType: `method`\n\nPošle ping rámec tomuto klientovi.\n\nReturns: `Object` Klient.\n\nOdpoveď klienta aktualizuje `client.latency`. `websocket.ping()` pinguje všetkých klientov.\n\nExample: Ping jedného klienta\n```js\nfunction socket() {\n\tthis.on('open', function(client) {\n\t\tclient.ping();\n\t});\n}\n```\n\n### websocketclient.url\n\nType: `property`\n\nURL posledného `connect()`.\n\nReturns: `String`\n\n`websocketclient.protocol` a `websocketclient.origin` uchovávajú ostatné argumenty `connect()`.\n\nExample: Príklad\n```js\nWEBSOCKETCLIENT(function(client) {\n\tclient.connect('wss://example.com/live/');\n\tclient.on('open', function() {\n\t\tconsole.log('Connected to', client.url);\n\t});\n});\n```\n","entries":[{"type":"method","name":"ROUTE('SOCKET')","signature":"ROUTE('SOCKET /url/', action, [flags], [length])","since":"","deprecated":false},{"type":"config","name":"WebSocket route flags","signature":"ROUTE('SOCKET /url/', action, ['json', 'binary', 'text', ...])","since":"","deprecated":false},{"type":"property","name":"websocket.online","signature":"websocket.online","since":"","deprecated":false},{"type":"property","name":"websocket.connections","signature":"websocket.connections","since":"","deprecated":false},{"type":"property","name":"websocket.url","signature":"websocket.url","since":"","deprecated":false},{"type":"property","name":"websocket.params","signature":"websocket.params","since":"","deprecated":false},{"type":"property","name":"websocket.repository","signature":"websocket.repository","since":"","deprecated":false},{"type":"method","name":"websocket.on()","signature":"websocket.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"websocket.send()","signature":"websocket.send(message, [comparer], [replacer], [params])","since":"","deprecated":false},{"type":"method","name":"websocket.find()","signature":"websocket.find(fn)","since":"","deprecated":false},{"type":"method","name":"websocket.clients()","signature":"websocket.clients()","since":"","deprecated":false},{"type":"method","name":"websocket.close()","signature":"websocket.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocket.destroy()","signature":"websocket.destroy()","since":"","deprecated":false},{"type":"method","name":"websocket.autodestroy()","signature":"websocket.autodestroy([callback])","since":"","deprecated":false},{"type":"method","name":"websocket.ping()","signature":"websocket.ping()","since":"","deprecated":false},{"type":"method","name":"websocket.api()","signature":"websocket.api(name)","since":"0.0.44","deprecated":false},{"type":"method","name":"websocket.encrypt()","signature":"websocket.encrypt([enable])","since":"","deprecated":false},{"type":"event","name":"websocket.on('open')","signature":"websocket.on('open', function(client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('message')","signature":"websocket.on('message', function(client, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('close')","signature":"websocket.on('close', function(client, code, message) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('error')","signature":"websocket.on('error', function(err, client) {})","since":"","deprecated":false},{"type":"event","name":"websocket.on('destroy')","signature":"websocket.on('destroy', function() {})","since":"","deprecated":false},{"type":"property","name":"client.id","signature":"client.id","since":"","deprecated":false},{"type":"property","name":"client.user","signature":"client.user","since":"","deprecated":false},{"type":"property","name":"client.query","signature":"client.query","since":"","deprecated":false},{"type":"property","name":"client.headers","signature":"client.headers","since":"","deprecated":false},{"type":"property","name":"client.latency","signature":"client.latency","since":"","deprecated":false},{"type":"method","name":"client.send()","signature":"client.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"client.close()","signature":"client.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"client.cookie()","signature":"client.cookie(name)","since":"","deprecated":false},{"type":"method","name":"client.hostname()","signature":"client.hostname([path])","since":"","deprecated":false},{"type":"method","name":"F.findConnection()","signature":"F.findConnection(path)","since":"","deprecated":false},{"type":"method","name":"F.findConnections()","signature":"F.findConnections([path])","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client) {})","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client) {})","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlength","signature":"CONF.default_websocket_maxlength","since":"","deprecated":false},{"type":"config","name":"default_websocket_maxlatency","signature":"CONF.default_websocket_maxlatency","since":"0.0.59","deprecated":false},{"type":"config","name":"allow_websocket","signature":"CONF.allow_websocket","since":"","deprecated":false},{"type":"method","name":"WEBSOCKETCLIENT()","signature":"WEBSOCKETCLIENT([callback])","since":"","deprecated":false},{"type":"property","name":"websocketclient.options","signature":"websocketclient.options","since":"","deprecated":false},{"type":"property","name":"websocketclient.headers","signature":"websocketclient.headers","since":"","deprecated":false},{"type":"property","name":"websocketclient.closed","signature":"websocketclient.closed","since":"","deprecated":false},{"type":"property","name":"websocketclient.latency","signature":"websocketclient.latency","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.connect()","signature":"websocketclient.connect(url, [protocol], [origin])","since":"","deprecated":false},{"type":"method","name":"websocketclient.send()","signature":"websocketclient.send(message, [raw], [replacer])","since":"","deprecated":false},{"type":"method","name":"websocketclient.close()","signature":"websocketclient.close([message], [code])","since":"","deprecated":false},{"type":"method","name":"websocketclient.destroy()","signature":"websocketclient.destroy()","since":"0.0.42","deprecated":false},{"type":"method","name":"websocketclient.ping()","signature":"websocketclient.ping([timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.api()","signature":"websocketclient.api([schema], [data], [callback], [timeout])","since":"0.0.44","deprecated":false},{"type":"method","name":"websocketclient.on()","signature":"websocketclient.on(name, callback)","since":"","deprecated":false},{"type":"property","name":"client.session","signature":"client.session","since":"","deprecated":false},{"type":"method","name":"client.ping()","signature":"client.ping()","since":"","deprecated":false},{"type":"property","name":"websocketclient.url","signature":"websocketclient.url","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:00.817Z"}
{"id":"JabWvc2ah61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"NoSQL database","summary":"NOSQL(), TABLE(), database methods, the query builder and the config keys of the embedded database.","markdown":"---\ntitle: NoSQL database\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL database\n\n> NOSQL(), TABLE(), database methods, the query builder and the config keys of the embedded database.\n\n`NOSQL(name)` and `TABLE(name)` return a database stored in the `databases/` folder. Database methods start a query and return a query builder; builder methods add conditions, sorting, paging and the callback. In this reference `db` is a database returned by `NOSQL()` or `TABLE()` and `builder` the query builder. The guide [NoSQL database](../../guides/nosql/) explains how the parts work together.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nReturns a NoSQL database: JSON documents stored in a text file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the database, or `~` followed by an absolute path to the file. |\n\nReturns: `Database` The database instance.\n\nThe database is stored in `databases/{name}.nosql`, one JSON document per line. The instance is created on the first call and then reused. A name that starts with `~` is an absolute path to the file; such an instance is not cached.\n\nAll operations return a query builder and run asynchronously in a queue, one after another.\n\nExample: Insert and read\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: A file outside the databases folder\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nReturns a table database: rows with a fixed schema stored in a text file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the table, or `~` followed by an absolute path to the file. |\n\nReturns: `Database` The table instance.\n\nThe table is stored in `databases/{name}.table`. The first line holds the schema, each next line one row with values separated by `|`. The schema comes from the config key `table_{name}` or from `alter()`; until a table has a schema, its operations wait.\n\nColumn types: `string`, `string(length)`, `number`, `number(length)`, `boolean` (or `bool`), `date` and `object`. Columns can be separated with `|`, `,` or `;`. Fields that are not in the schema are not stored. When every column has a size, rows have a fixed width. A string longer than its size is cut.\n\nA table uses the same methods and query builder as `NOSQL()`. A name that starts with `~` is an absolute path to the file.\n\nExample: Schema in the config file\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Use the table\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nFolder for the NoSQL and table files.\n\nDefault `/databases/`, relative to the app directory. `NOSQL()` and `TABLE()` create the folder when they need it.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nSchema of the table `TABLE(name)`.\n\nColumns are `name:type`, separated by `|`, `,` or `;`. Types: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. When the schema in the config differs from the schema in the file, the table is rewritten to the new schema the first time it is used.\n\nExample: Config\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nKeeps small databases in memory for reading. Size in megabytes.\n\nDefault `0` (off). A database whose file is smaller than this number of megabytes is cached in memory after it is read, and later reads use the cache. Writes keep the cache in sync or reset it.\n\nExample: Cache databases up to 10 MB\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nRuns the NoSQL engine in a worker thread.\n\nDefault `false`. With `true`, and only while the web server is running, all `NOSQL()` and `TABLE()` operations run in a worker thread, so reading large files does not block the main thread. The `oninsert`, `onupdate` and `onremove` handlers are not called in this mode.\n\nExample: Config\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nFinds documents. The response is an array.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nAlias: `db.all()`. Add conditions, sorting and limits to the returned builder. The callback receives `(err, items, meta)`, where `meta` has `count` (matched documents), `counter`, `scanned` and `duration`.\n\nWithout sorting and pagination, reading stops as soon as `take()` documents are found.\n\nExample: Find documents\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nFinds documents, reading the file from the end.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nLike `find()`, but the newest documents come first, because new documents are appended to the end of the file.\n\nExample: The last ten log entries\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nReads one document. The response is the document or nothing.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nAlias: `db.one()`. Reads the file from the end and stops at the first match, so with several matches it returns the newest one.\n\nExample: Read by id\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nFinds documents and returns a page with paging data.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nThe response is `{ page, pages, limit, count, items }`. `count` is the number of all matching documents, so use it with `page()` or `paginate()`.\n\nExample: A page for a grid\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nCounts matching documents. The response is `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nExample: Count\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nComputes values over matching documents: min, max, sum, count or groups.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` or `sum`. With one argument it is the field name. |\n| `key` | `String` | no |  | Field to compute, or the field to group by when `key2` is given. |\n| `key2` | `String` | no |  | Field with the values, grouped by `key`. |\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\n- `scalar(type, key)` or `scalar(key)`: the response is `{ count, sum, min, max }` for the field `key`.\n- `scalar('group', key)`: counts documents by the values of `key`, e.g. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)`: sums `key2` by the values of `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)`: the highest / lowest value of `key2` for each value of `key`; any other type sums `key2`.\n\nExample: Statistics of a field\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Sum by group\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nGroups documents by a field and a period and returns min, max and count of a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Field to group by. |\n| `datefield` | `String` | yes |  | Field with a `Date`. |\n| `key` | `String` | yes |  | Field with the measured value. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` or `yearly`; anything else is daily. |\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nThe response is `{ [group]: { [period]: { min, max, count } } }`. The period key is the date formatted as `yyyyMMddHH` (`hourly`), `yyyyMMdd` (default, daily), `yyyyMM` (`monthly`) or `yyyy` (`yearly`). Only documents with a `Date` in `datefield` are used.\n\nExample: Monthly temperatures by sensor\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nInserts a document. The response is `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | The document. |\n| `check` | `Boolean` | no | `false` | Insert only when no document matches the conditions of the returned builder. |\n\nReturns: `QueryBuilder` Builder for the callback (and for conditions with `check`).\n\nThe document is appended to the end of the file. Key prefixes used by `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`) are removed from the keys.\n\nWith `check` set to `true` the method returns a builder for conditions: the document is inserted only when no document matches them, otherwise the response is `0`.\n\nExample: Insert\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Insert only a unique email\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nChanges fields of matching documents. The response is the number of changed documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Fields to change, with optional prefixes. |\n| `upsert` | `Boolean` | no | `false` | Insert the data when no document matches. |\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nAliases: `db.modify()`, `db.mod()`. Only the fields in `data` change; other fields stay. Keys with the value `undefined` are skipped. A prefix in the key performs an operation with the stored value:\n\n| Key | Operation |\n| --- | --- |\n| `field` | Set the value |\n| `+field` | Add (a missing value counts as `0`) |\n| `-field` | Subtract |\n| `*field` | Multiply |\n| `/field` | Divide |\n| `!field` | Toggle a boolean; the value is ignored |\n| `>field` | Keep the higher value |\n| `<field` | Keep the lower value |\n\nWith `upsert` the data (without the prefixes) is inserted as a new document when nothing matched; `builder.insert(fn)` can change it first.\n\nExample: Update by id\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Upsert a counter\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nRemoves matching documents. The response is the number of removed documents.\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nAlias: `db.rem()`. Removed documents are marked in the file; `clean()` frees the space. Without conditions all documents are removed.\n\nExample: Remove old documents\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nRemoves all documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called when the database is empty. |\n\nReturns: `QueryBuilder` A builder.\n\nA NoSQL database deletes its data file. A table keeps only its schema line.\n\nExample: Clear\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nCompacts the file: rewrites it without removed and outdated lines.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called when the file is rewritten. |\n\nReturns: `QueryBuilder` The database.\n\nRemoving a document, and updating one that grows, leaves unused lines in the file. Run `clean()` from time to time, e.g. once a day, to make the file smaller and reading faster.\n\nExample: Clean once a day\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nDeletes the database: the data file, its backups (`.bk`) and log (`.log`).\n\nReturns: `QueryBuilder` A builder.\n\nA callback set with `.callback()` is called when the drop is queued, with `{ success: true }` as its first argument.\n\nExample: Drop\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nReads the backups made by `builder.backup()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder for conditions and the callback.\n\nBackups are stored in `{file}.bk`, newest first. Each record has `date`, `body` (the original document as a JSON string) and the fields you passed to `builder.backup(data)`. You can filter the records with the returned builder.\n\nExample: Backups made by a user\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nReturns the number of documents and the file size.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` A builder.\n\nThe response is `{ documents, filesize }` (size in bytes). The values come from the last counting of the database; `db.recount()` counts the documents and measures the file again.\n\nExample: Usage\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nSets the read buffer of the database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Number of documents processed at once. |\n| `size` | `Number` | no | `32` | Size of the read buffer in kB. |\n\nLarger buffers read big files faster and use more memory.\n\nExample: Bigger buffers\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nRuns a function while no other operation of the database runs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)`; call `next()` to release the lock. |\n\nThe callback receives `next`. Queued operations wait until you call it.\n\nExample: Lock\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nSets or changes the schema of a table. Only for `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Columns as `name:type`, separated by `\\|`, `,` or `;`. |\n| `callback` | `Function` | no |  | Called when the schema is applied. |\n\nReturns: `Database` The table.\n\nA new table writes the schema line. When the schema differs from the current one, the file is rewritten and existing rows get the new columns. A column written as `newname=oldname:type` takes the values of the old column.\n\nExample: Declare a table\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Rename a column\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nCalled for every inserted document.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | The inserted document. |\n\nAssign it before the first operation of the database. Called only by `NOSQL()` databases and not when `textdb_worker` is on.\n\nExample: Log inserts\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nCalled for every changed document.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | The document after the change. |\n\nAssign it before the first operation of the database. Called by `NOSQL()` and `TABLE()`, not when `textdb_worker` is on.\n\nExample: Log updates\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nCalled for every removed document.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | The removed record as stored in the file. |\n\nAssign it before the first operation of the database. It receives the stored line of the document as a string (JSON for `NOSQL()`). Not called when `textdb_worker` is on.\n\nExample: Log removals\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nAdds a condition that compares a field with a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `operator` | `String` | no | `==` | Comparison operator. |\n| `value` | `Object` | yes |  | Value to compare with. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nOperators: `=` and `==` (equal), `!=` and `<>` (not equal), `>`, `<`, `>=`, `<=`. With two arguments the operator is `==`. A dotted name reads a nested field (`address.city`); a missing parent does not throw.\n\nExample: Conditions\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nAdds a condition for the field `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | The id or an array of ids. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAn array of ids works like `in('id', ids)`.\n\nExample: By id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Several ids\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nThe field value must be in the array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `value` | `Array` | yes |  | Allowed values. |\n| `key` | `String` | no |  | Property to read from objects in `value`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nWhen the field holds an array, it is enough that one of its items is in `value`. With `key`, `value` is an array of objects and their `key` property is used.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: Ids from other documents\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nThe field value must not be in the array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `value` | `Array` | yes |  | Excluded values. |\n| `key` | `String` | no |  | Property to read from objects in `value`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nThe opposite of `in()`. With `key`, `value` is an array of objects and their `key` property is used.\n\nExample: Not in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nThe field value must be between two values, both included.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `a` | `Number|Date|String` | yes |  | Lowest value. |\n| `b` | `Number|Date|String` | yes |  | Highest value. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nExample: Between\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nCase-insensitive text search in a field.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n| `value` | `String` | yes |  | Searched text. |\n| `where` | `String` | no |  | `beg` or `end`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nWithout `where` the field must contain the value. `beg` means it starts with the value, `end` that it ends with it. A field with an array matches when one of its items matches. An empty field or value never matches.\n\nExample: Search\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Starts with\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nThe field must not be empty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAn array must have items; any other value must be truthy.\n\nExample: With photos\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nThe field must be empty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field name. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAn empty array, `null`, `undefined`, an empty string, `0` or `false`.\n\nExample: Without a note\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nCompares the year of a date field. `month()` and `day()` compare the month (1-12) and the day of the month.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Field with a `Date`. |\n| `operator` | `String` | no | `=` | Comparison operator. |\n| `value` | `Number` | yes |  | Year, month (1-12) or day. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`builder.month(name, [operator], value)` and `builder.day(name, [operator], value)` work the same way. Operators are the same as in `where()`; the default is `=`. Fields without a date never match.\n\nExample: Orders from June 2022 on\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nJoins the conditions added inside the function with OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)` that adds conditions. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nThe function receives the builder (also as `this`). Conditions outside the function are still joined with AND.\n\nExample: Or\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nAdds a raw JavaScript condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | JavaScript expression, e.g. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Values for the expression. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\n`code` is an expression that returns a boolean. It sees `doc` (the document) and `arg` (your values; the keys of `arg` are copied to it). Code with the words `require` or `global` is rejected and matches nothing.\n\nExample: Rule\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nChooses the returned fields.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Fields, e.g. `id,name,email` or `-password`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nA comma-separated list. `-name` removes a field and keeps the others. `name as title` returns the field under another name.\n\nExample: Only some fields\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Without a field\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nSorts the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | E.g. `name`, `created_desc` or `country,name_desc`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAlias: `builder.gridsort()`. `name` or `name_asc` sorts ascending, `name_desc` descending. Several fields are separated with commas; dotted names sort by nested fields.\n\nExample: Sort\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nReturns at most `count` documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximum number of documents. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAlias: `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSkips the first `count` matching documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Number of documents to skip. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nReturns only the first matching document instead of an array.\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nIn a `join()` it makes the joined field one document (or `null`) instead of an array.\n\nExample: First\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSelects a page. The page number starts at `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Page index, starting at `0`. |\n| `limit` | `Number` | no |  | Documents per page. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nSets `skip` to `page * limit`. Without `limit` the value of an earlier `take()` is used. For page numbers from the query string, which start at `1`, use `paginate()`.\n\nExample: Second page\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSelects a page. The page number starts at `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Page number, starting at `1`. |\n| `limit` | `Number|String` | yes |  | Documents per page. |\n| `maxlimit` | `Number` | no |  | Highest allowed limit. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAccepts strings, so values from the query can be passed as they are. A page lower than `1` becomes `1`. `limit` is capped by `maxlimit`; without `limit`, `maxlimit` is used.\n\nExample: From the query\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nSets the function that receives the result, or connects the builder to an operation `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` or the `$` object of an operation. |\n| `error` | `String` | no |  | Error when nothing was found, e.g. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` The builder for a function; a promise for `$`.\n\nWith a function, it receives `(err, response, meta)`. With the `$` of a schema operation, an error is passed to `$.invalid()` and the method returns a promise with the response, so you can `await` it.\n\n`error` is used when the response is empty (nothing, `0` or an empty array): the function receives it as `err`, or `$.invalid(error)` is called.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await in an operation\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nReturns a promise with the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)` that returns the value for the promise. |\n\nReturns: `Promise` Promise with the response.\n\nThe promise rejects with the error. `fn` can transform the response before the promise resolves.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Transform\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nCalls `fn` with the response, or `$.invalid()` on an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` object of an operation. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Value passed to `fn` as the second argument. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nSets an error for an empty response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Error message or key. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nAlias: `builder.err()`. When the response is empty (nothing, `0` or an empty array), the callback receives this error, or `$.invalid()` is called when the builder is connected to `$`.\n\nExample: Not found\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nChanges the document that an upsert inserts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nOnly for `update(data, true)`. When nothing matched, `fn` receives the data that will be inserted and the builder.\n\nExample: Upsert with extra fields\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nSaves the original documents before an update or removal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Extra fields for the backup record, e.g. who made the change. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nEach changed or removed document is appended to `{file}.bk` as `{ ...data, date, body }`, where `body` is the original document as a JSON string. Read the backups with `db.backups()`.\n\nExample: Backup with the user\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nAdds documents from another database to each result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Field that receives the joined documents. |\n| `database` | `String` | yes |  | `name`, `nosql/name` or `table/name`. |\n| `type` | `String` | no | `left` | `inner`; anything else is a left join. |\n\nReturns: `QueryBuilder` Builder for the joined database.\n\nReturns a new builder for the joined database: set the link with `on()`, and use `where()`, `fields()`, `take()` or `first()` on it. A `callback()` on it sets the callback of the main query.\n\n`database` is a NoSQL name, `nosql/name` or `table/name`. By default (`left`) every document is kept and `field` is an array (or `null` with `first()`). With `inner`, documents without a match are left out.\n\nExample: Orders with their user\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nLinks a joined database to the main query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Field in the joined database. |\n| `parentfield` | `String` | yes |  | Field in the documents of the main query. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nUse it on the builder returned by `join()`. A joined document matches when its `field` equals `parentfield` of the main document.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nAdds a condition from a filter value typed by a user.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Key in `obj`. |\n| `obj` | `Object` | yes |  | The filter values, e.g. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` or `Boolean`. |\n| `field` | `String` | no |  | Field to filter when it differs from `name`. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nReads `obj[name]` and does nothing when it is empty. The value is converted with `type` (`String`, `Number`, `Date` or `Boolean`):\n\n- `a - b` adds `between()`.\n- `a, b` adds `in()`; for strings, `search()` for each value joined with OR.\n- A string adds `search()`; other types add `where()`.\n- For `Date`: `today`, `yesterday`, a year (`2022`), a month number, or a date for the whole day.\n\nExample: Filters from the query\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nSets fields, filters, sorting and paging from the query of an operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` object of a schema operation. |\n| `allowedfields` | `String` | no |  | Extra fields, e.g. `id,created:date`. |\n| `skipfields` | `String` | no |  | Schema fields to leave out, e.g. `password`. |\n| `defsort` | `String|Number` | no |  | Default sorting, e.g. `created_desc`. A number here is `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Highest page size. |\n\nReturns: `QueryBuilder` The same builder, for chaining.\n\nReads `$.query` and the schema of the operation:\n\n- `fields`: returned fields; only schema fields and `allowedfields`. Without it, all of them.\n- Any key with the name of a schema field adds a filter with `gridfilter()`.\n- `sort`: e.g. `name_desc`; unknown fields are ignored. Without it, `defsort`.\n- `page` and `limit`: `paginate()` with `maxlimit`.\n\n`allowedfields` adds fields that are not in the schema (`name:type`, where the type also adds a filter); `skipfields` hides schema fields.\n\nExample: Query operation\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvc2ah61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"NoSQL-Datenbank","summary":"NOSQL(), TABLE(), die Datenbankmethoden, der Query-Builder und die Konfigurationsschlüssel der eingebetteten Datenbank.","markdown":"---\ntitle: NoSQL-Datenbank\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL-Datenbank\n\n> NOSQL(), TABLE(), die Datenbankmethoden, der Query-Builder und die Konfigurationsschlüssel der eingebetteten Datenbank.\n\n`NOSQL(name)` und `TABLE(name)` geben eine Datenbank zurück, die im Ordner `databases/` gespeichert ist. Datenbankmethoden starten eine Abfrage und geben einen Query-Builder zurück; Builder-Methoden fügen Bedingungen, Sortierung, Paginierung und den Callback hinzu. In dieser Referenz ist `db` eine von `NOSQL()` oder `TABLE()` zurückgegebene Datenbank und `builder` der Query-Builder. Die Anleitung [NoSQL-Datenbank](../../guides/nosql/) erklärt, wie die Teile zusammenspielen.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nGibt eine NoSQL-Datenbank zurück: JSON-Dokumente, gespeichert in einer Textdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Datenbank oder `~`, gefolgt von einem absoluten Pfad zur Datei. |\n\nReturns: `Database` Die Instanz der Datenbank.\n\nDie Datenbank wird in `databases/{name}.nosql` gespeichert, ein JSON-Dokument pro Zeile. Die Instanz wird beim ersten Aufruf erzeugt und dann wiederverwendet. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad zur Datei; eine solche Instanz wird nicht gecacht.\n\nAlle Operationen geben einen Query-Builder zurück und laufen asynchron in einer Warteschlange, eine nach der anderen.\n\nExample: Einfügen und lesen\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: Eine Datei außerhalb des Ordners databases\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nGibt eine Tabellendatenbank zurück: Zeilen mit festem Schema, gespeichert in einer Textdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Tabelle oder `~`, gefolgt von einem absoluten Pfad zur Datei. |\n\nReturns: `Database` Die Instanz der Tabelle.\n\nDie Tabelle wird in `databases/{name}.table` gespeichert. Die erste Zeile enthält das Schema, jede weitere Zeile einen Datensatz mit Werten, getrennt durch `|`. Das Schema kommt aus dem Konfigurationsschlüssel `table_{name}` oder aus `alter()`; solange eine Tabelle kein Schema hat, warten ihre Operationen.\n\nSpaltentypen: `string`, `string(length)`, `number`, `number(length)`, `boolean` (oder `bool`), `date` und `object`. Spalten können mit `|`, `,` oder `;` getrennt werden. Felder, die nicht im Schema stehen, werden nicht gespeichert. Wenn jede Spalte eine Größe hat, haben Zeilen eine feste Breite. Ein String, der länger als seine Größe ist, wird abgeschnitten.\n\nEine Tabelle verwendet dieselben Methoden und denselben Query-Builder wie `NOSQL()`. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad zur Datei.\n\nExample: Schema in der Konfigurationsdatei\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Die Tabelle verwenden\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nOrdner für die NoSQL- und Tabellendateien.\n\nStandard `/databases/`, relativ zum Verzeichnis der App. `NOSQL()` und `TABLE()` legen den Ordner an, wenn sie ihn brauchen.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nSchema der Tabelle `TABLE(name)`.\n\nSpalten sind `name:type`, getrennt durch `|`, `,` oder `;`. Typen: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. Wenn sich das Schema in der Konfiguration vom Schema in der Datei unterscheidet, wird die Tabelle bei der ersten Verwendung auf das neue Schema umgeschrieben.\n\nExample: Konfiguration\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nHält kleine Datenbanken zum Lesen im Speicher. Größe in Megabyte.\n\nStandard `0` (aus). Eine Datenbank, deren Datei kleiner als diese Anzahl Megabyte ist, wird nach dem Lesen im Speicher gecacht, und spätere Lesevorgänge verwenden den Cache. Schreibvorgänge halten den Cache synchron oder setzen ihn zurück.\n\nExample: Datenbanken bis 10 MB cachen\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nFührt die NoSQL-Engine in einem Worker-Thread aus.\n\nStandard `false`. Mit `true`, und nur solange der Webserver läuft, laufen alle Operationen von `NOSQL()` und `TABLE()` in einem Worker-Thread, das Lesen großer Dateien blockiert also nicht den Haupt-Thread. Die Handler `oninsert`, `onupdate` und `onremove` werden in diesem Modus nicht aufgerufen.\n\nExample: Konfiguration\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nFindet Dokumente. Die Response ist ein Array.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nAlias: `db.all()`. Füge dem zurückgegebenen Builder Bedingungen, Sortierung und Limits hinzu. Der Callback erhält `(err, items, meta)`, wobei `meta` die Werte `count` (passende Dokumente), `counter`, `scanned` und `duration` hat.\n\nOhne Sortierung und Paginierung endet das Lesen, sobald `take()` Dokumente gefunden sind.\n\nExample: Dokumente finden\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nFindet Dokumente und liest die Datei vom Ende her.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nWie `find()`, aber die neuesten Dokumente kommen zuerst, weil neue Dokumente ans Ende der Datei angehängt werden.\n\nExample: Die letzten zehn Log-Einträge\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nLiest ein Dokument. Die Response ist das Dokument oder nichts.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nAlias: `db.one()`. Liest die Datei vom Ende her und stoppt beim ersten Treffer, bei mehreren Treffern gibt es also den neuesten zurück.\n\nExample: Nach id lesen\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nFindet Dokumente und gibt eine Seite mit Paginierungsdaten zurück.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nDie Response ist `{ page, pages, limit, count, items }`. `count` ist die Anzahl aller passenden Dokumente, verwende es also mit `page()` oder `paginate()`.\n\nExample: Eine Seite für ein Grid\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nZählt passende Dokumente. Die Response ist `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nExample: Zählen\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nBerechnet Werte über passende Dokumente: Minimum, Maximum, Summe, Anzahl oder Gruppen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` oder `sum`. Mit einem Argument ist es der Feldname. |\n| `key` | `String` | no |  | Zu berechnendes Feld oder das Feld, nach dem gruppiert wird, wenn `key2` angegeben ist. |\n| `key2` | `String` | no |  | Feld mit den Werten, gruppiert nach `key`. |\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\n- `scalar(type, key)` oder `scalar(key)`: Die Response ist `{ count, sum, min, max }` für das Feld `key`.\n- `scalar('group', key)`: zählt Dokumente nach den Werten von `key`, z. B. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)`: summiert `key2` nach den Werten von `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)`: der höchste / niedrigste Wert von `key2` für jeden Wert von `key`; jeder andere Typ summiert `key2`.\n\nExample: Statistik eines Feldes\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Summe pro Gruppe\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nGruppiert Dokumente nach einem Feld und einem Zeitraum und gibt Minimum, Maximum und Anzahl eines Wertes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Feld, nach dem gruppiert wird. |\n| `datefield` | `String` | yes |  | Feld mit einem `Date`. |\n| `key` | `String` | yes |  | Feld mit dem gemessenen Wert. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` oder `yearly`; alles andere ist täglich. |\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nDie Response ist `{ [group]: { [period]: { min, max, count } } }`. Der Schlüssel des Zeitraums ist das Datum im Format `yyyyMMddHH` (`hourly`), `yyyyMMdd` (Standard, täglich), `yyyyMM` (`monthly`) oder `yyyy` (`yearly`). Es werden nur Dokumente mit einem `Date` in `datefield` verwendet.\n\nExample: Monatliche Temperaturen pro Sensor\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nFügt ein Dokument ein. Die Response ist `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Das Dokument. |\n| `check` | `Boolean` | no | `false` | Nur einfügen, wenn kein Dokument auf die Bedingungen des zurückgegebenen Builders passt. |\n\nReturns: `QueryBuilder` Builder für den Callback (und mit `check` für Bedingungen).\n\nDas Dokument wird ans Ende der Datei angehängt. Schlüsselpräfixe, die `update()` verwendet (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`), werden aus den Schlüsseln entfernt.\n\nMit `check` auf `true` gibt die Methode einen Builder für Bedingungen zurück: Das Dokument wird nur eingefügt, wenn kein Dokument auf sie passt, sonst ist die Response `0`.\n\nExample: Einfügen\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Nur eine eindeutige E-Mail einfügen\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nÄndert Felder passender Dokumente. Die Response ist die Anzahl der geänderten Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Zu ändernde Felder, mit optionalen Präfixen. |\n| `upsert` | `Boolean` | no | `false` | Die Daten einfügen, wenn kein Dokument passt. |\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nAliase: `db.modify()`, `db.mod()`. Nur die Felder in `data` ändern sich; andere Felder bleiben. Schlüssel mit dem Wert `undefined` werden übersprungen. Ein Präfix im Schlüssel führt eine Operation mit dem gespeicherten Wert aus:\n\n| Schlüssel | Operation |\n| --- | --- |\n| `field` | Den Wert setzen |\n| `+field` | Addieren (ein fehlender Wert zählt als `0`) |\n| `-field` | Subtrahieren |\n| `*field` | Multiplizieren |\n| `/field` | Dividieren |\n| `!field` | Einen Boolean umschalten; der Wert wird ignoriert |\n| `>field` | Den höheren Wert behalten |\n| `<field` | Den niedrigeren Wert behalten |\n\nMit `upsert` werden die Daten (ohne die Präfixe) als neues Dokument eingefügt, wenn nichts gepasst hat; `builder.insert(fn)` kann sie vorher ändern.\n\nExample: Nach id aktualisieren\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Einen Zähler per Upsert setzen\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nEntfernt passende Dokumente. Die Response ist die Anzahl der entfernten Dokumente.\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nAlias: `db.rem()`. Entfernte Dokumente werden in der Datei markiert; `clean()` gibt den Platz frei. Ohne Bedingungen werden alle Dokumente entfernt.\n\nExample: Alte Dokumente entfernen\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nEntfernt alle Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn die Datenbank leer ist. |\n\nReturns: `QueryBuilder` Ein Builder.\n\nEine NoSQL-Datenbank löscht ihre Datendatei. Eine Tabelle behält nur ihre Schemazeile.\n\nExample: Leeren\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nVerdichtet die Datei: schreibt sie ohne entfernte und veraltete Zeilen neu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn die Datei neu geschrieben ist. |\n\nReturns: `QueryBuilder` Die Datenbank.\n\nDas Entfernen eines Dokuments und das Aktualisieren eines Dokuments, das größer wird, hinterlassen ungenutzte Zeilen in der Datei. Führe `clean()` von Zeit zu Zeit aus, z. B. einmal am Tag, um die Datei kleiner und das Lesen schneller zu machen.\n\nExample: Einmal am Tag aufräumen\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nLöscht die Datenbank: die Datendatei, ihre Backups (`.bk`) und ihr Log (`.log`).\n\nReturns: `QueryBuilder` Ein Builder.\n\nEin mit `.callback()` gesetzter Callback wird aufgerufen, wenn das Löschen in die Warteschlange gestellt ist, mit `{ success: true }` als erstem Argument.\n\nExample: Löschen\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nLiest die von `builder.backup()` erstellten Backups.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder für Bedingungen und den Callback.\n\nBackups werden in `{file}.bk` gespeichert, die neuesten zuerst. Jeder Datensatz hat `date`, `body` (das ursprüngliche Dokument als JSON-String) und die Felder, die du an `builder.backup(data)` übergeben hast. Du kannst die Datensätze mit dem zurückgegebenen Builder filtern.\n\nExample: Backups eines Benutzers\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nGibt die Anzahl der Dokumente und die Dateigröße zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` Ein Builder.\n\nDie Response ist `{ documents, filesize }` (Größe in Bytes). Die Werte stammen aus der letzten Zählung der Datenbank; `db.recount()` zählt die Dokumente und misst die Datei erneut.\n\nExample: Nutzung\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nLegt den Lesepuffer der Datenbank fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Anzahl der Dokumente, die auf einmal verarbeitet werden. |\n| `size` | `Number` | no | `32` | Größe des Lesepuffers in kB. |\n\nGrößere Puffer lesen große Dateien schneller und verbrauchen mehr Speicher.\n\nExample: Größere Puffer\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nFührt eine Funktion aus, während keine andere Operation der Datenbank läuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)`; rufe `next()` auf, um die Sperre freizugeben. |\n\nDer Callback erhält `next`. Wartende Operationen warten, bis du es aufrufst.\n\nExample: Sperren\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nSetzt oder ändert das Schema einer Tabelle. Nur für `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Spalten als `name:type`, getrennt durch `\\|`, `,` oder `;`. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn das Schema angewendet ist. |\n\nReturns: `Database` Die Tabelle.\n\nEine neue Tabelle schreibt die Schemazeile. Unterscheidet sich das Schema vom aktuellen, wird die Datei neu geschrieben und bestehende Zeilen erhalten die neuen Spalten. Eine als `newname=oldname:type` geschriebene Spalte übernimmt die Werte der alten Spalte.\n\nExample: Eine Tabelle deklarieren\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Eine Spalte umbenennen\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nWird für jedes eingefügte Dokument aufgerufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Das eingefügte Dokument. |\n\nWeise es vor der ersten Operation der Datenbank zu. Wird nur von `NOSQL()`-Datenbanken aufgerufen und nicht, wenn `textdb_worker` eingeschaltet ist.\n\nExample: Einfügungen protokollieren\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nWird für jedes geänderte Dokument aufgerufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Das Dokument nach der Änderung. |\n\nWeise es vor der ersten Operation der Datenbank zu. Wird von `NOSQL()` und `TABLE()` aufgerufen, nicht wenn `textdb_worker` eingeschaltet ist.\n\nExample: Aktualisierungen protokollieren\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nWird für jedes entfernte Dokument aufgerufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | Der entfernte Datensatz, wie er in der Datei gespeichert ist. |\n\nWeise es vor der ersten Operation der Datenbank zu. Es erhält die gespeicherte Zeile des Dokuments als String (JSON bei `NOSQL()`). Wird nicht aufgerufen, wenn `textdb_worker` eingeschaltet ist.\n\nExample: Entfernungen protokollieren\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nFügt eine Bedingung hinzu, die ein Feld mit einem Wert vergleicht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n| `operator` | `String` | no | `==` | Vergleichsoperator. |\n| `value` | `Object` | yes |  | Wert, mit dem verglichen wird. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nOperatoren: `=` und `==` (gleich), `!=` und `<>` (ungleich), `>`, `<`, `>=`, `<=`. Mit zwei Argumenten ist der Operator `==`. Ein Name mit Punkten liest ein verschachteltes Feld (`address.city`); ein fehlendes übergeordnetes Objekt wirft keinen Fehler.\n\nExample: Bedingungen\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFügt eine Bedingung für das Feld `id` hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Die ID oder ein Array aus IDs. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEin Array aus IDs funktioniert wie `in('id', ids)`.\n\nExample: Nach id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Mehrere IDs\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nDer Wert des Feldes muss im Array enthalten sein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n| `value` | `Array` | yes |  | Erlaubte Werte. |\n| `key` | `String` | no |  | Eigenschaft, die aus den Objekten in `value` gelesen wird. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEnthält das Feld ein Array, genügt es, dass eines seiner Elemente in `value` enthalten ist. Mit `key` ist `value` ein Array aus Objekten, und ihre Eigenschaft `key` wird verwendet.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: IDs aus anderen Dokumenten\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nDer Wert des Feldes darf nicht im Array enthalten sein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n| `value` | `Array` | yes |  | Ausgeschlossene Werte. |\n| `key` | `String` | no |  | Eigenschaft, die aus den Objekten in `value` gelesen wird. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDas Gegenteil von `in()`. Mit `key` ist `value` ein Array aus Objekten, und ihre Eigenschaft `key` wird verwendet.\n\nExample: Nicht in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nDer Wert des Feldes muss zwischen zwei Werten liegen, beide eingeschlossen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n| `a` | `Number|Date|String` | yes |  | Niedrigster Wert. |\n| `b` | `Number|Date|String` | yes |  | Höchster Wert. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nExample: Zwischen\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nTextsuche in einem Feld ohne Beachtung der Groß-/Kleinschreibung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n| `value` | `String` | yes |  | Gesuchter Text. |\n| `where` | `String` | no |  | `beg` oder `end`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nOhne `where` muss das Feld den Wert enthalten. `beg` bedeutet, dass es mit dem Wert beginnt, `end`, dass es damit endet. Ein Feld mit einem Array passt, wenn eines seiner Elemente passt. Ein leeres Feld oder ein leerer Wert passt nie.\n\nExample: Suchen\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Beginnt mit\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nDas Feld darf nicht leer sein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEin Array muss Elemente haben; jeder andere Wert muss truthy sein.\n\nExample: Mit Fotos\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nDas Feld muss leer sein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Feldes. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEin leeres Array, `null`, `undefined`, ein leerer String, `0` oder `false`.\n\nExample: Ohne Notiz\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nVergleicht das Jahr eines Datumsfeldes. `month()` und `day()` vergleichen den Monat (1-12) und den Tag des Monats.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Feld mit einem `Date`. |\n| `operator` | `String` | no | `=` | Vergleichsoperator. |\n| `value` | `Number` | yes |  | Jahr, Monat (1-12) oder Tag. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`builder.month(name, [operator], value)` und `builder.day(name, [operator], value)` funktionieren genauso. Die Operatoren sind dieselben wie in `where()`; der Standard ist `=`. Felder ohne Datum passen nie.\n\nExample: Bestellungen ab Juni 2022\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nVerknüpft die innerhalb der Funktion hinzugefügten Bedingungen mit OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`, die Bedingungen hinzufügt. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nDie Funktion erhält den Builder (auch als `this`). Bedingungen außerhalb der Funktion werden weiterhin mit AND verknüpft.\n\nExample: Oder\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nFügt eine rohe JavaScript-Bedingung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | JavaScript-Ausdruck, z. B. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Werte für den Ausdruck. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\n`code` ist ein Ausdruck, der einen Boolean zurückgibt. Er sieht `doc` (das Dokument) und `arg` (deine Werte; die Schlüssel von `arg` werden dorthin kopiert). Code mit den Wörtern `require` oder `global` wird abgelehnt und passt auf nichts.\n\nExample: Regel\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nWählt die zurückgegebenen Felder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Felder, z. B. `id,name,email` oder `-password`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nEine durch Kommas getrennte Liste. `-name` entfernt ein Feld und behält die anderen. `name as title` gibt das Feld unter einem anderen Namen zurück.\n\nExample: Nur einige Felder\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Ohne ein Feld\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nSortiert das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Z. B. `name`, `created_desc` oder `country,name_desc`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAlias: `builder.gridsort()`. `name` oder `name_asc` sortiert aufsteigend, `name_desc` absteigend. Mehrere Felder werden durch Kommas getrennt; Namen mit Punkten sortieren nach verschachtelten Feldern.\n\nExample: Sortieren\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nGibt höchstens `count` Dokumente zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximale Anzahl an Dokumenten. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAlias: `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nÜberspringt die ersten `count` passenden Dokumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Anzahl der zu überspringenden Dokumente. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nGibt statt eines Arrays nur das erste passende Dokument zurück.\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nIn einem `join()` macht es das verknüpfte Feld zu einem Dokument (oder `null`) statt zu einem Array.\n\nExample: Erstes\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nWählt eine Seite. Die Seitennummer beginnt bei `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Seitenindex, beginnend bei `0`. |\n| `limit` | `Number` | no |  | Dokumente pro Seite. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nSetzt `skip` auf `page * limit`. Ohne `limit` wird der Wert eines früheren `take()` verwendet. Für Seitennummern aus dem Query-String, die bei `1` beginnen, verwende `paginate()`.\n\nExample: Zweite Seite\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nWählt eine Seite. Die Seitennummer beginnt bei `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Seitennummer, beginnend bei `1`. |\n| `limit` | `Number|String` | yes |  | Dokumente pro Seite. |\n| `maxlimit` | `Number` | no |  | Höchstes erlaubtes Limit. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAkzeptiert Strings, Werte aus der Query können also unverändert übergeben werden. Eine Seite kleiner als `1` wird zu `1`. `limit` wird durch `maxlimit` begrenzt; ohne `limit` wird `maxlimit` verwendet.\n\nExample: Aus der Query\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nLegt die Funktion fest, die das Ergebnis erhält, oder verbindet den Builder mit einer Operation `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` oder das `$`-Objekt einer Operation. |\n| `error` | `String` | no |  | Fehler, wenn nichts gefunden wurde, z. B. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` Der Builder bei einer Funktion; eine Promise bei `$`.\n\nMit einer Funktion erhält diese `(err, response, meta)`. Mit dem `$` einer Schema-Operation wird ein Fehler an `$.invalid()` übergeben und die Methode gibt eine Promise mit der Response zurück, du kannst sie also mit `await` erwarten.\n\n`error` wird verwendet, wenn die Response leer ist (nichts, `0` oder ein leeres Array): Die Funktion erhält es als `err`, oder `$.invalid(error)` wird aufgerufen.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await in einer Operation\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nGibt eine Promise mit der Response zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)`, die den Wert für die Promise zurückgibt. |\n\nReturns: `Promise` Promise mit der Response.\n\nDie Promise wird mit dem Fehler abgelehnt. `fn` kann die Response umwandeln, bevor die Promise aufgelöst wird.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Umwandeln\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nRuft `fn` mit der Response auf oder bei einem Fehler `$.invalid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$`-Objekt einer Operation. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Wert, der als zweites Argument an `fn` übergeben wird. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nLegt einen Fehler für eine leere Response fest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Fehlermeldung oder Schlüssel. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nAlias: `builder.err()`. Ist die Response leer (nichts, `0` oder ein leeres Array), erhält der Callback diesen Fehler, oder `$.invalid()` wird aufgerufen, wenn der Builder mit `$` verbunden ist.\n\nExample: Nicht gefunden\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nÄndert das Dokument, das ein Upsert einfügt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nNur für `update(data, true)`. Wenn nichts gepasst hat, erhält `fn` die Daten, die eingefügt werden, und den Builder.\n\nExample: Upsert mit zusätzlichen Feldern\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nSpeichert die ursprünglichen Dokumente vor einer Aktualisierung oder Entfernung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Zusätzliche Felder für den Backup-Datensatz, z. B. wer die Änderung vorgenommen hat. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nJedes geänderte oder entfernte Dokument wird als `{ ...data, date, body }` an `{file}.bk` angehängt, wobei `body` das ursprüngliche Dokument als JSON-String ist. Lies die Backups mit `db.backups()`.\n\nExample: Backup mit dem Benutzer\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nFügt jedem Ergebnis Dokumente aus einer anderen Datenbank hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Feld, das die verknüpften Dokumente erhält. |\n| `database` | `String` | yes |  | `name`, `nosql/name` oder `table/name`. |\n| `type` | `String` | no | `left` | `inner`; alles andere ist ein Left Join. |\n\nReturns: `QueryBuilder` Builder für die verknüpfte Datenbank.\n\nGibt einen neuen Builder für die verknüpfte Datenbank zurück: Setze die Verknüpfung mit `on()` und verwende darauf `where()`, `fields()`, `take()` oder `first()`. Ein `callback()` darauf setzt den Callback der Hauptabfrage.\n\n`database` ist ein NoSQL-Name, `nosql/name` oder `table/name`. Standardmäßig (`left`) wird jedes Dokument behalten und `field` ist ein Array (oder `null` mit `first()`). Mit `inner` werden Dokumente ohne Treffer weggelassen.\n\nExample: Bestellungen mit ihrem Benutzer\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nVerknüpft eine verknüpfte Datenbank mit der Hauptabfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Feld in der verknüpften Datenbank. |\n| `parentfield` | `String` | yes |  | Feld in den Dokumenten der Hauptabfrage. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nVerwende es auf dem von `join()` zurückgegebenen Builder. Ein verknüpftes Dokument passt, wenn sein `field` gleich `parentfield` des Hauptdokuments ist.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nFügt eine Bedingung aus einem von einem Benutzer eingegebenen Filterwert hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Schlüssel in `obj`. |\n| `obj` | `Object` | yes |  | Die Filterwerte, z. B. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` oder `Boolean`. |\n| `field` | `String` | no |  | Zu filterndes Feld, wenn es sich von `name` unterscheidet. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nLiest `obj[name]` und tut nichts, wenn es leer ist. Der Wert wird mit `type` konvertiert (`String`, `Number`, `Date` oder `Boolean`):\n\n- `a - b` fügt `between()` hinzu.\n- `a, b` fügt `in()` hinzu; bei Strings `search()` für jeden Wert, mit OR verknüpft.\n- Ein String fügt `search()` hinzu; andere Typen fügen `where()` hinzu.\n- Für `Date`: `today`, `yesterday`, ein Jahr (`2022`), eine Monatsnummer oder ein Datum für den ganzen Tag.\n\nExample: Filter aus der Query\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nSetzt Felder, Filter, Sortierung und Paginierung aus der Query einer Operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$`-Objekt einer Schema-Operation. |\n| `allowedfields` | `String` | no |  | Zusätzliche Felder, z. B. `id,created:date`. |\n| `skipfields` | `String` | no |  | Wegzulassende Schemafelder, z. B. `password`. |\n| `defsort` | `String|Number` | no |  | Standardsortierung, z. B. `created_desc`. Eine Zahl an dieser Stelle ist `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Höchste Seitengröße. |\n\nReturns: `QueryBuilder` Derselbe Builder, zum Verketten.\n\nLiest `$.query` und das Schema der Operation:\n\n- `fields`: zurückgegebene Felder; nur Felder des Schemas und `allowedfields`. Ohne es alle.\n- Jeder Schlüssel mit dem Namen eines Schemafeldes fügt mit `gridfilter()` einen Filter hinzu.\n- `sort`: z. B. `name_desc`; unbekannte Felder werden ignoriert. Ohne es `defsort`.\n- `page` und `limit`: `paginate()` mit `maxlimit`.\n\n`allowedfields` fügt Felder hinzu, die nicht im Schema stehen (`name:type`, wobei der Typ auch einen Filter hinzufügt); `skipfields` blendet Schemafelder aus.\n\nExample: Query-Operation\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvc2ah61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Base de datos NoSQL","summary":"NOSQL(), TABLE(), los métodos de la base de datos, el query builder y las claves de configuración de la base de datos integrada.","markdown":"---\ntitle: Base de datos NoSQL\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Base de datos NoSQL\n\n> NOSQL(), TABLE(), los métodos de la base de datos, el query builder y las claves de configuración de la base de datos integrada.\n\n`NOSQL(name)` y `TABLE(name)` devuelven una base de datos guardada en la carpeta `databases/`. Los métodos de la base de datos inician una consulta y devuelven un query builder; los métodos del builder añaden condiciones, orden, paginación y el callback. En esta referencia, `db` es una base de datos devuelta por `NOSQL()` o `TABLE()` y `builder` el query builder. La guía [Base de datos NoSQL](../../guides/nosql/) explica cómo funcionan juntas las partes.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nDevuelve una base de datos NoSQL: documentos JSON guardados en un archivo de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la base de datos, o `~` seguido de una ruta absoluta al archivo. |\n\nReturns: `Database` La instancia de la base de datos.\n\nLa base de datos se guarda en `databases/{name}.nosql`, un documento JSON por línea. La instancia se crea en la primera llamada y luego se reutiliza. Un nombre que empieza por `~` es una ruta absoluta al archivo; esa instancia no se guarda en caché.\n\nTodas las operaciones devuelven un query builder y se ejecutan de forma asíncrona en una cola, una tras otra.\n\nExample: Insertar y leer\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: Un archivo fuera de la carpeta databases\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nDevuelve una base de datos de tabla: filas con un esquema fijo guardadas en un archivo de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la tabla, o `~` seguido de una ruta absoluta al archivo. |\n\nReturns: `Database` La instancia de la tabla.\n\nLa tabla se guarda en `databases/{name}.table`. La primera línea contiene el esquema y cada línea siguiente una fila con los valores separados por `|`. El esquema viene de la clave de configuración `table_{name}` o de `alter()`; hasta que una tabla tiene esquema, sus operaciones esperan.\n\nTipos de columna: `string`, `string(length)`, `number`, `number(length)`, `boolean` (o `bool`), `date` y `object`. Las columnas pueden separarse con `|`, `,` o `;`. Los campos que no están en el esquema no se guardan. Cuando todas las columnas tienen tamaño, las filas tienen ancho fijo. Una cadena más larga que su tamaño se recorta.\n\nUna tabla usa los mismos métodos y el mismo query builder que `NOSQL()`. Un nombre que empieza por `~` es una ruta absoluta al archivo.\n\nExample: Esquema en el archivo de configuración\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Usar la tabla\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nCarpeta para los archivos NoSQL y de tabla.\n\nPor defecto `/databases/`, relativa al directorio de la aplicación. `NOSQL()` y `TABLE()` crean la carpeta cuando la necesitan.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nEsquema de la tabla `TABLE(name)`.\n\nLas columnas son `name:type`, separadas por `|`, `,` o `;`. Tipos: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. Cuando el esquema de la configuración difiere del esquema del archivo, la tabla se reescribe con el nuevo esquema la primera vez que se usa.\n\nExample: Configuración\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nMantiene en memoria, para lectura, las bases de datos pequeñas. Tamaño en megabytes.\n\nPor defecto `0` (desactivado). Una base de datos cuyo archivo es menor que este número de megabytes se guarda en caché en memoria después de leerla, y las lecturas posteriores usan la caché. Las escrituras mantienen la caché sincronizada o la reinician.\n\nExample: Caché de bases de datos de hasta 10 MB\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nEjecuta el motor NoSQL en un hilo worker.\n\nPor defecto `false`. Con `true`, y solo mientras el servidor web está en marcha, todas las operaciones de `NOSQL()` y `TABLE()` se ejecutan en un hilo worker, así que leer archivos grandes no bloquea el hilo principal. Los manejadores `oninsert`, `onupdate` y `onremove` no se llaman en este modo.\n\nExample: Configuración\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nBusca documentos. La respuesta es un array.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nAlias: `db.all()`. Añade condiciones, orden y límites al builder devuelto. El callback recibe `(err, items, meta)`, donde `meta` tiene `count` (documentos coincidentes), `counter`, `scanned` y `duration`.\n\nSin orden ni paginación, la lectura se detiene en cuanto se encuentran `take()` documentos.\n\nExample: Buscar documentos\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nBusca documentos leyendo el archivo desde el final.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nComo `find()`, pero los documentos más recientes van primero, porque los documentos nuevos se añaden al final del archivo.\n\nExample: Las diez últimas entradas del log\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nLee un documento. La respuesta es el documento o nada.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nAlias: `db.one()`. Lee el archivo desde el final y se detiene en la primera coincidencia, así que con varias coincidencias devuelve la más reciente.\n\nExample: Leer por id\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nBusca documentos y devuelve una página con datos de paginación.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nLa respuesta es `{ page, pages, limit, count, items }`. `count` es el número de todos los documentos coincidentes, así que úsalo con `page()` o `paginate()`.\n\nExample: Una página para un grid\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nCuenta los documentos coincidentes. La respuesta es `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nExample: Contar\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nCalcula valores sobre los documentos coincidentes: mínimo, máximo, suma, número o grupos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` o `sum`. Con un solo argumento es el nombre del campo. |\n| `key` | `String` | no |  | Campo que se calcula, o el campo por el que se agrupa cuando se indica `key2`. |\n| `key2` | `String` | no |  | Campo con los valores, agrupados por `key`. |\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\n- `scalar(type, key)` o `scalar(key)`: la respuesta es `{ count, sum, min, max }` para el campo `key`.\n- `scalar('group', key)`: cuenta los documentos por los valores de `key`, p. ej. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)`: suma `key2` por los valores de `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)`: el valor mayor / menor de `key2` para cada valor de `key`; cualquier otro tipo suma `key2`.\n\nExample: Estadísticas de un campo\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Suma por grupo\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nAgrupa los documentos por un campo y un periodo y devuelve el mínimo, el máximo y el número de un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Campo por el que se agrupa. |\n| `datefield` | `String` | yes |  | Campo con un `Date`. |\n| `key` | `String` | yes |  | Campo con el valor medido. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` o `yearly`; cualquier otro valor es diario. |\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nLa respuesta es `{ [group]: { [period]: { min, max, count } } }`. La clave del periodo es la fecha con formato `yyyyMMddHH` (`hourly`), `yyyyMMdd` (por defecto, diario), `yyyyMM` (`monthly`) o `yyyy` (`yearly`). Solo se usan los documentos con un `Date` en `datefield`.\n\nExample: Temperaturas mensuales por sensor\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nInserta un documento. La respuesta es `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | El documento. |\n| `check` | `Boolean` | no | `false` | Insertar solo cuando ningún documento cumple las condiciones del builder devuelto. |\n\nReturns: `QueryBuilder` Builder para el callback (y para las condiciones con `check`).\n\nEl documento se añade al final del archivo. Los prefijos de clave que usa `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`) se eliminan de las claves.\n\nCon `check` en `true`, el método devuelve un builder para condiciones: el documento se inserta solo cuando ningún documento las cumple; si no, la respuesta es `0`.\n\nExample: Insertar\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Insertar solo un email único\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nCambia campos de los documentos coincidentes. La respuesta es el número de documentos cambiados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campos que se cambian, con prefijos opcionales. |\n| `upsert` | `Boolean` | no | `false` | Insertar los datos cuando ningún documento coincide. |\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nAlias: `db.modify()`, `db.mod()`. Solo cambian los campos de `data`; los demás campos se mantienen. Las claves con el valor `undefined` se omiten. Un prefijo en la clave realiza una operación con el valor guardado:\n\n| Clave | Operación |\n| --- | --- |\n| `field` | Asigna el valor |\n| `+field` | Suma (un valor ausente cuenta como `0`) |\n| `-field` | Resta |\n| `*field` | Multiplica |\n| `/field` | Divide |\n| `!field` | Invierte un booleano; el valor se ignora |\n| `>field` | Conserva el valor mayor |\n| `<field` | Conserva el valor menor |\n\nCon `upsert`, los datos (sin los prefijos) se insertan como un documento nuevo cuando no hubo coincidencias; `builder.insert(fn)` puede modificarlos antes.\n\nExample: Actualizar por id\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Upsert de un contador\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nElimina los documentos coincidentes. La respuesta es el número de documentos eliminados.\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nAlias: `db.rem()`. Los documentos eliminados se marcan en el archivo; `clean()` libera el espacio. Sin condiciones se eliminan todos los documentos.\n\nExample: Eliminar documentos antiguos\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nElimina todos los documentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama cuando la base de datos está vacía. |\n\nReturns: `QueryBuilder` Un builder.\n\nUna base de datos NoSQL borra su archivo de datos. Una tabla conserva solo su línea de esquema.\n\nExample: Vaciar\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nCompacta el archivo: lo reescribe sin las líneas eliminadas ni obsoletas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama cuando el archivo se ha reescrito. |\n\nReturns: `QueryBuilder` La base de datos.\n\nEliminar un documento, y actualizar uno que crece, deja líneas sin usar en el archivo. Ejecuta `clean()` de vez en cuando, p. ej. una vez al día, para que el archivo sea más pequeño y la lectura más rápida.\n\nExample: Limpiar una vez al día\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nBorra la base de datos: el archivo de datos, sus copias de seguridad (`.bk`) y su log (`.log`).\n\nReturns: `QueryBuilder` Un builder.\n\nUn callback definido con `.callback()` se llama cuando el borrado se pone en cola, con `{ success: true }` como primer argumento.\n\nExample: Borrar\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nLee las copias de seguridad hechas por `builder.backup()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder para las condiciones y el callback.\n\nLas copias de seguridad se guardan en `{file}.bk`, las más recientes primero. Cada registro tiene `date`, `body` (el documento original como cadena JSON) y los campos que pasaste a `builder.backup(data)`. Puedes filtrar los registros con el builder devuelto.\n\nExample: Copias de seguridad hechas por un usuario\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nDevuelve el número de documentos y el tamaño del archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` Un builder.\n\nLa respuesta es `{ documents, filesize }` (tamaño en bytes). Los valores vienen del último recuento de la base de datos; `db.recount()` vuelve a contar los documentos y a medir el archivo.\n\nExample: Uso\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nDefine el buffer de lectura de la base de datos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Número de documentos procesados a la vez. |\n| `size` | `Number` | no | `32` | Tamaño del buffer de lectura en kB. |\n\nLos buffers más grandes leen los archivos grandes más rápido y usan más memoria.\n\nExample: Buffers más grandes\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nEjecuta una función mientras no se ejecuta ninguna otra operación de la base de datos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)`; llama a `next()` para liberar el bloqueo. |\n\nEl callback recibe `next`. Las operaciones en cola esperan hasta que lo llames.\n\nExample: Bloqueo\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nDefine o cambia el esquema de una tabla. Solo para `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Columnas como `name:type`, separadas por `\\|`, `,` o `;`. |\n| `callback` | `Function` | no |  | Se llama cuando se aplica el esquema. |\n\nReturns: `Database` La tabla.\n\nUna tabla nueva escribe la línea de esquema. Cuando el esquema difiere del actual, el archivo se reescribe y las filas existentes reciben las columnas nuevas. Una columna escrita como `newname=oldname:type` toma los valores de la columna antigua.\n\nExample: Declarar una tabla\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Renombrar una columna\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nSe llama para cada documento insertado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | El documento insertado. |\n\nAsígnalo antes de la primera operación de la base de datos. Solo lo llaman las bases de datos `NOSQL()`, y no cuando `textdb_worker` está activado.\n\nExample: Registrar inserciones\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nSe llama para cada documento cambiado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | El documento después del cambio. |\n\nAsígnalo antes de la primera operación de la base de datos. Lo llaman `NOSQL()` y `TABLE()`, pero no cuando `textdb_worker` está activado.\n\nExample: Registrar actualizaciones\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nSe llama para cada documento eliminado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | El registro eliminado tal como estaba guardado en el archivo. |\n\nAsígnalo antes de la primera operación de la base de datos. Recibe la línea guardada del documento como cadena (JSON para `NOSQL()`). No se llama cuando `textdb_worker` está activado.\n\nExample: Registrar eliminaciones\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nAñade una condición que compara un campo con un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `operator` | `String` | no | `==` | Operador de comparación. |\n| `value` | `Object` | yes |  | Valor con el que se compara. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nOperadores: `=` y `==` (igual), `!=` y `<>` (distinto), `>`, `<`, `>=`, `<=`. Con dos argumentos el operador es `==`. Un nombre con puntos lee un campo anidado (`address.city`); si falta el padre, no se lanza ningún error.\n\nExample: Condiciones\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nAñade una condición para el campo `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | El id o un array de ids. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUn array de ids funciona como `in('id', ids)`.\n\nExample: Por id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Varios ids\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nEl valor del campo debe estar en el array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `value` | `Array` | yes |  | Valores permitidos. |\n| `key` | `String` | no |  | Propiedad que se lee de los objetos de `value`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nCuando el campo contiene un array, basta con que uno de sus elementos esté en `value`. Con `key`, `value` es un array de objetos y se usa su propiedad `key`.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: Ids de otros documentos\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nEl valor del campo no debe estar en el array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `value` | `Array` | yes |  | Valores excluidos. |\n| `key` | `String` | no |  | Propiedad que se lee de los objetos de `value`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLo contrario de `in()`. Con `key`, `value` es un array de objetos y se usa su propiedad `key`.\n\nExample: Not in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nEl valor del campo debe estar entre dos valores, ambos incluidos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `a` | `Number|Date|String` | yes |  | Valor más bajo. |\n| `b` | `Number|Date|String` | yes |  | Valor más alto. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nExample: Between\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nBúsqueda de texto sin distinguir mayúsculas y minúsculas en un campo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n| `value` | `String` | yes |  | Texto buscado. |\n| `where` | `String` | no |  | `beg` o `end`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSin `where`, el campo debe contener el valor. `beg` significa que empieza por el valor y `end` que termina con él. Un campo con un array coincide cuando uno de sus elementos coincide. Un campo o un valor vacío nunca coincide.\n\nExample: Búsqueda\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Empieza por\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nEl campo no debe estar vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUn array debe tener elementos; cualquier otro valor debe ser truthy.\n\nExample: Con fotos\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nEl campo debe estar vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del campo. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUn array vacío, `null`, `undefined`, una cadena vacía, `0` o `false`.\n\nExample: Sin nota\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nCompara el año de un campo de fecha. `month()` y `day()` comparan el mes (1-12) y el día del mes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo con un `Date`. |\n| `operator` | `String` | no | `=` | Operador de comparación. |\n| `value` | `Number` | yes |  | Año, mes (1-12) o día. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\n`builder.month(name, [operator], value)` y `builder.day(name, [operator], value)` funcionan igual. Los operadores son los mismos que en `where()`; por defecto es `=`. Los campos sin fecha nunca coinciden.\n\nExample: Pedidos desde junio de 2022\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUne con OR las condiciones añadidas dentro de la función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)` que añade condiciones. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLa función recibe el builder (también como `this`). Las condiciones fuera de la función se siguen uniendo con AND.\n\nExample: Or\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nAñade una condición en JavaScript puro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Expresión JavaScript, p. ej. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Valores para la expresión. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\n`code` es una expresión que devuelve un booleano. Ve `doc` (el documento) y `arg` (tus valores; las claves de `arg` se copian en él). El código con las palabras `require` o `global` se rechaza y no coincide con nada.\n\nExample: Regla\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nElige los campos devueltos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Campos, p. ej. `id,name,email` o `-password`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nUna lista separada por comas. `-name` quita un campo y conserva los demás. `name as title` devuelve el campo con otro nombre.\n\nExample: Solo algunos campos\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Sin un campo\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nOrdena el resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | P. ej. `name`, `created_desc` o `country,name_desc`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAlias: `builder.gridsort()`. `name` o `name_asc` ordena de forma ascendente y `name_desc` de forma descendente. Varios campos se separan con comas; los nombres con puntos ordenan por campos anidados.\n\nExample: Ordenar\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nDevuelve como máximo `count` documentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Número máximo de documentos. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAlias: `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSalta los primeros `count` documentos coincidentes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Número de documentos que se saltan. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nDevuelve solo el primer documento coincidente en lugar de un array.\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nEn un `join()`, hace que el campo unido sea un documento (o `null`) en lugar de un array.\n\nExample: First\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSelecciona una página. El número de página empieza en `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Índice de la página, empezando en `0`. |\n| `limit` | `Number` | no |  | Documentos por página. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAsigna a `skip` el valor `page * limit`. Sin `limit` se usa el valor de un `take()` anterior. Para números de página del query string, que empiezan en `1`, usa `paginate()`.\n\nExample: Segunda página\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSelecciona una página. El número de página empieza en `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Número de página, empezando en `1`. |\n| `limit` | `Number|String` | yes |  | Documentos por página. |\n| `maxlimit` | `Number` | no |  | Límite máximo permitido. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAcepta cadenas, así que los valores del query se pueden pasar tal cual. Una página menor que `1` se convierte en `1`. `limit` está limitado por `maxlimit`; sin `limit`, se usa `maxlimit`.\n\nExample: Desde el query\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nDefine la función que recibe el resultado, o conecta el builder con una operación `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` o el objeto `$` de una operación. |\n| `error` | `String` | no |  | Error cuando no se encontró nada, p. ej. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` El builder para una función; una promesa para `$`.\n\nCon una función, esta recibe `(err, response, meta)`. Con el `$` de una operación de esquema, un error se pasa a `$.invalid()` y el método devuelve una promesa con la respuesta, así que puedes usar `await` con ella.\n\n`error` se usa cuando la respuesta está vacía (nada, `0` o un array vacío): la función lo recibe como `err`, o se llama a `$.invalid(error)`.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await en una operación\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nDevuelve una promesa con la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)` que devuelve el valor para la promesa. |\n\nReturns: `Promise` Promesa con la respuesta.\n\nLa promesa se rechaza con el error. `fn` puede transformar la respuesta antes de que se resuelva la promesa.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Transformar\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nLlama a `fn` con la respuesta, o a `$.invalid()` si hay un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El objeto `$` de una operación. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Valor que se pasa a `fn` como segundo argumento. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nDefine un error para una respuesta vacía.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Mensaje o clave del error. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nAlias: `builder.err()`. Cuando la respuesta está vacía (nada, `0` o un array vacío), el callback recibe este error, o se llama a `$.invalid()` cuando el builder está conectado a `$`.\n\nExample: No encontrado\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nModifica el documento que inserta un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nSolo para `update(data, true)`. Cuando no hubo coincidencias, `fn` recibe los datos que se van a insertar y el builder.\n\nExample: Upsert con campos adicionales\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nGuarda los documentos originales antes de una actualización o eliminación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Campos adicionales para el registro de la copia de seguridad, p. ej. quién hizo el cambio. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nCada documento cambiado o eliminado se añade a `{file}.bk` como `{ ...data, date, body }`, donde `body` es el documento original como cadena JSON. Lee las copias de seguridad con `db.backups()`.\n\nExample: Copia de seguridad con el usuario\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nAñade a cada resultado documentos de otra base de datos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Campo que recibe los documentos unidos. |\n| `database` | `String` | yes |  | `name`, `nosql/name` o `table/name`. |\n| `type` | `String` | no | `left` | `inner`; cualquier otro valor es un left join. |\n\nReturns: `QueryBuilder` Builder para la base de datos unida.\n\nDevuelve un builder nuevo para la base de datos unida: define el enlace con `on()` y usa en él `where()`, `fields()`, `take()` o `first()`. Un `callback()` en él define el callback de la consulta principal.\n\n`database` es un nombre NoSQL, `nosql/name` o `table/name`. Por defecto (`left`) se conserva cada documento y `field` es un array (o `null` con `first()`). Con `inner`, los documentos sin coincidencia se dejan fuera.\n\nExample: Pedidos con su usuario\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nEnlaza una base de datos unida con la consulta principal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Campo en la base de datos unida. |\n| `parentfield` | `String` | yes |  | Campo en los documentos de la consulta principal. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nÚsalo en el builder que devuelve `join()`. Un documento unido coincide cuando su `field` es igual a `parentfield` del documento principal.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nAñade una condición a partir de un valor de filtro escrito por un usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Clave en `obj`. |\n| `obj` | `Object` | yes |  | Los valores de filtro, p. ej. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` o `Boolean`. |\n| `field` | `String` | no |  | Campo que se filtra cuando es distinto de `name`. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLee `obj[name]` y no hace nada cuando está vacío. El valor se convierte con `type` (`String`, `Number`, `Date` o `Boolean`):\n\n- `a - b` añade `between()`.\n- `a, b` añade `in()`; para cadenas, `search()` para cada valor, unidos con OR.\n- Una cadena añade `search()`; los demás tipos añaden `where()`.\n- Para `Date`: `today`, `yesterday`, un año (`2022`), un número de mes, o una fecha para el día completo.\n\nExample: Filtros desde el query\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nDefine campos, filtros, orden y paginación a partir del query de una operación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El objeto `$` de una operación de esquema. |\n| `allowedfields` | `String` | no |  | Campos adicionales, p. ej. `id,created:date`. |\n| `skipfields` | `String` | no |  | Campos del esquema que se dejan fuera, p. ej. `password`. |\n| `defsort` | `String|Number` | no |  | Orden por defecto, p. ej. `created_desc`. Un número aquí es `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Tamaño máximo de página. |\n\nReturns: `QueryBuilder` El mismo builder, para encadenar.\n\nLee `$.query` y el esquema de la operación:\n\n- `fields`: campos devueltos; solo los campos del esquema y `allowedfields`. Sin él, todos.\n- Cualquier clave con el nombre de un campo del esquema añade un filtro con `gridfilter()`.\n- `sort`: p. ej. `name_desc`; los campos desconocidos se ignoran. Sin él, `defsort`.\n- `page` y `limit`: `paginate()` con `maxlimit`.\n\n`allowedfields` añade campos que no están en el esquema (`name:type`, donde el tipo también añade un filtro); `skipfields` oculta campos del esquema.\n\nExample: Operación de consulta\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvc2ah61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Base de données NoSQL","summary":"NOSQL(), TABLE(), les méthodes de base de données, le query builder et les clés de configuration de la base de données embarquée.","markdown":"---\ntitle: \"Base de données NoSQL\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Base de données NoSQL\n\n> NOSQL(), TABLE(), les méthodes de base de données, le query builder et les clés de configuration de la base de données embarquée.\n\n`NOSQL(name)` et `TABLE(name)` retournent une base de données stockée dans le dossier `databases/`. Les méthodes de base de données lancent une requête et retournent un query builder ; les méthodes du builder ajoutent les conditions, le tri, la pagination et le callback. Dans cette référence, `db` est une base de données retournée par `NOSQL()` ou `TABLE()` et `builder` le query builder. Le guide [Base de données NoSQL](../../guides/nosql/) explique comment les différentes parties fonctionnent ensemble.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nRetourne une base de données NoSQL : des documents JSON stockés dans un fichier texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la base de données, ou `~` suivi d'un chemin absolu vers le fichier. |\n\nReturns: `Database` L'instance de la base de données.\n\nLa base de données est stockée dans `databases/{name}.nosql`, un document JSON par ligne. L'instance est créée au premier appel, puis réutilisée. Un nom qui commence par `~` est un chemin absolu vers le fichier ; une telle instance n'est pas mise en cache.\n\nToutes les opérations retournent un query builder et s'exécutent de manière asynchrone dans une file d'attente, l'une après l'autre.\n\nExample: Insérer et lire\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: Un fichier en dehors du dossier databases\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nRetourne une base de données de type table : des lignes avec un schéma fixe stockées dans un fichier texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la table, ou `~` suivi d'un chemin absolu vers le fichier. |\n\nReturns: `Database` L'instance de la table.\n\nLa table est stockée dans `databases/{name}.table`. La première ligne contient le schéma, chaque ligne suivante un enregistrement avec des valeurs séparées par `|`. Le schéma provient de la clé de configuration `table_{name}` ou de `alter()` ; tant qu'une table n'a pas de schéma, ses opérations attendent.\n\nTypes de colonnes : `string`, `string(length)`, `number`, `number(length)`, `boolean` (ou `bool`), `date` et `object`. Les colonnes peuvent être séparées par `|`, `,` ou `;`. Les champs absents du schéma ne sont pas stockés. Lorsque chaque colonne a une taille, les lignes ont une largeur fixe. Une chaîne plus longue que sa taille est tronquée.\n\nUne table utilise les mêmes méthodes et le même query builder que `NOSQL()`. Un nom qui commence par `~` est un chemin absolu vers le fichier.\n\nExample: Schéma dans le fichier de configuration\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Utiliser la table\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nDossier des fichiers NoSQL et des tables.\n\nPar défaut `/databases/`, relatif au répertoire de l'application. `NOSQL()` et `TABLE()` créent le dossier lorsqu'ils en ont besoin.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nSchéma de la table `TABLE(name)`.\n\nLes colonnes s'écrivent `name:type`, séparées par `|`, `,` ou `;`. Types : `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. Lorsque le schéma de la configuration diffère de celui du fichier, la table est réécrite selon le nouveau schéma lors de sa première utilisation.\n\nExample: Configuration\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nConserve les petites bases de données en mémoire pour la lecture. Taille en mégaoctets.\n\nPar défaut `0` (désactivé). Une base de données dont le fichier est plus petit que ce nombre de mégaoctets est mise en cache en mémoire après sa lecture, et les lectures suivantes utilisent le cache. Les écritures maintiennent le cache synchronisé ou le réinitialisent.\n\nExample: Mettre en cache les bases de données jusqu'à 10 Mo\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nExécute le moteur NoSQL dans un worker thread.\n\nPar défaut `false`. Avec `true`, et uniquement pendant que le serveur web tourne, toutes les opérations `NOSQL()` et `TABLE()` s'exécutent dans un worker thread : la lecture de gros fichiers ne bloque donc pas le thread principal. Les gestionnaires `oninsert`, `onupdate` et `onremove` ne sont pas appelés dans ce mode.\n\nExample: Configuration\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nTrouve des documents. La réponse est un tableau.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nAlias : `db.all()`. Ajoute des conditions, un tri et des limites au builder retourné. Le callback reçoit `(err, items, meta)`, où `meta` contient `count` (documents correspondants), `counter`, `scanned` et `duration`.\n\nSans tri ni pagination, la lecture s'arrête dès que `take()` documents sont trouvés.\n\nExample: Trouver des documents\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nTrouve des documents en lisant le fichier à partir de la fin.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nComme `find()`, mais les documents les plus récents viennent en premier, car les nouveaux documents sont ajoutés à la fin du fichier.\n\nExample: Les dix dernières entrées du journal\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nLit un seul document. La réponse est le document ou rien.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nAlias : `db.one()`. Lit le fichier à partir de la fin et s'arrête à la première correspondance : s'il y a plusieurs correspondances, il retourne donc la plus récente.\n\nExample: Lire par id\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nTrouve des documents et retourne une page avec les données de pagination.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nLa réponse est `{ page, pages, limit, count, items }`. `count` est le nombre total de documents correspondants : utilise-la donc avec `page()` ou `paginate()`.\n\nExample: Une page pour une grille\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nCompte les documents correspondants. La réponse est `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nExample: Compter\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nCalcule des valeurs sur les documents correspondants : min, max, somme, nombre ou groupes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` ou `sum`. Avec un seul argument, il s'agit du nom du champ. |\n| `key` | `String` | no |  | Champ à calculer, ou champ de regroupement lorsque `key2` est indiqué. |\n| `key2` | `String` | no |  | Champ contenant les valeurs, regroupées selon `key`. |\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\n- `scalar(type, key)` ou `scalar(key)` : la réponse est `{ count, sum, min, max }` pour le champ `key`.\n- `scalar('group', key)` : compte les documents selon les valeurs de `key`, par ex. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)` : additionne `key2` selon les valeurs de `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)` : la valeur la plus élevée / la plus basse de `key2` pour chaque valeur de `key` ; tout autre type additionne `key2`.\n\nExample: Statistiques d'un champ\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Somme par groupe\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nRegroupe les documents selon un champ et une période et retourne le min, le max et le nombre d'une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Champ de regroupement. |\n| `datefield` | `String` | yes |  | Champ contenant une `Date`. |\n| `key` | `String` | yes |  | Champ contenant la valeur mesurée. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` ou `yearly` ; toute autre valeur correspond à un regroupement quotidien. |\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nLa réponse est `{ [group]: { [period]: { min, max, count } } }`. La clé de période est la date formatée en `yyyyMMddHH` (`hourly`), `yyyyMMdd` (par défaut, quotidien), `yyyyMM` (`monthly`) ou `yyyy` (`yearly`). Seuls les documents ayant une `Date` dans `datefield` sont utilisés.\n\nExample: Températures mensuelles par capteur\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nInsère un document. La réponse est `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Le document. |\n| `check` | `Boolean` | no | `false` | Insérer uniquement lorsqu'aucun document ne correspond aux conditions du builder retourné. |\n\nReturns: `QueryBuilder` Builder pour le callback (et pour les conditions avec `check`).\n\nLe document est ajouté à la fin du fichier. Les préfixes de clés utilisés par `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`) sont retirés des clés.\n\nAvec `check` à `true`, la méthode retourne un builder pour les conditions : le document n'est inséré que si aucun document ne leur correspond, sinon la réponse est `0`.\n\nExample: Insérer\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Insérer uniquement un e-mail unique\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nModifie des champs des documents correspondants. La réponse est le nombre de documents modifiés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Champs à modifier, avec des préfixes facultatifs. |\n| `upsert` | `Boolean` | no | `false` | Insérer les données lorsqu'aucun document ne correspond. |\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nAlias : `db.modify()`, `db.mod()`. Seuls les champs de `data` changent ; les autres champs restent inchangés. Les clés dont la valeur est `undefined` sont ignorées. Un préfixe dans la clé effectue une opération avec la valeur stockée :\n\n| Clé | Opération |\n| --- | --- |\n| `field` | Définir la valeur |\n| `+field` | Additionner (une valeur manquante compte comme `0`) |\n| `-field` | Soustraire |\n| `*field` | Multiplier |\n| `/field` | Diviser |\n| `!field` | Inverser un booléen ; la valeur est ignorée |\n| `>field` | Conserver la valeur la plus élevée |\n| `<field` | Conserver la valeur la plus basse |\n\nAvec `upsert`, les données (sans les préfixes) sont insérées comme nouveau document lorsque rien ne correspond ; `builder.insert(fn)` peut d'abord les modifier.\n\nExample: Mettre à jour par id\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Upsert d'un compteur\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nSupprime les documents correspondants. La réponse est le nombre de documents supprimés.\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nAlias : `db.rem()`. Les documents supprimés sont marqués dans le fichier ; `clean()` libère l'espace. Sans conditions, tous les documents sont supprimés.\n\nExample: Supprimer les anciens documents\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nSupprime tous les documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé lorsque la base de données est vide. |\n\nReturns: `QueryBuilder` Un builder.\n\nUne base de données NoSQL supprime son fichier de données. Une table ne conserve que sa ligne de schéma.\n\nExample: Vider\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nCompacte le fichier : le réécrit sans les lignes supprimées et obsolètes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelé lorsque le fichier est réécrit. |\n\nReturns: `QueryBuilder` La base de données.\n\nSupprimer un document, ou mettre à jour un document qui grossit, laisse des lignes inutilisées dans le fichier. Exécute `clean()` de temps en temps, par ex. une fois par jour, pour réduire la taille du fichier et accélérer la lecture.\n\nExample: Nettoyer une fois par jour\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nSupprime la base de données : le fichier de données, ses sauvegardes (`.bk`) et son journal (`.log`).\n\nReturns: `QueryBuilder` Un builder.\n\nUn callback défini avec `.callback()` est appelé lorsque la suppression est mise en file d'attente, avec `{ success: true }` comme premier argument.\n\nExample: Supprimer\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nLit les sauvegardes créées par `builder.backup()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder pour les conditions et le callback.\n\nLes sauvegardes sont stockées dans `{file}.bk`, les plus récentes en premier. Chaque enregistrement contient `date`, `body` (le document original sous forme de chaîne JSON) et les champs que tu as passés à `builder.backup(data)`. Tu peux filtrer les enregistrements avec le builder retourné.\n\nExample: Sauvegardes créées par un utilisateur\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nRetourne le nombre de documents et la taille du fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` Un builder.\n\nLa réponse est `{ documents, filesize }` (taille en octets). Les valeurs proviennent du dernier comptage de la base de données ; `db.recount()` recompte les documents et mesure de nouveau le fichier.\n\nExample: Utilisation\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nDéfinit le tampon de lecture de la base de données.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Nombre de documents traités à la fois. |\n| `size` | `Number` | no | `32` | Taille du tampon de lecture en ko. |\n\nDes tampons plus grands lisent plus vite les gros fichiers et utilisent plus de mémoire.\n\nExample: Tampons plus grands\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nExécute une fonction pendant qu'aucune autre opération de la base de données ne s'exécute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)` ; appelle `next()` pour libérer le verrou. |\n\nLe callback reçoit `next`. Les opérations en file d'attente patientent jusqu'à ce que tu l'appelles.\n\nExample: Verrou\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nDéfinit ou modifie le schéma d'une table. Uniquement pour `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Colonnes sous la forme `name:type`, séparées par `\\|`, `,` ou `;`. |\n| `callback` | `Function` | no |  | Appelé lorsque le schéma est appliqué. |\n\nReturns: `Database` La table.\n\nUne nouvelle table écrit la ligne de schéma. Lorsque le schéma diffère du schéma actuel, le fichier est réécrit et les lignes existantes reçoivent les nouvelles colonnes. Une colonne écrite sous la forme `newname=oldname:type` reprend les valeurs de l'ancienne colonne.\n\nExample: Déclarer une table\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Renommer une colonne\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nAppelé pour chaque document inséré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Le document inséré. |\n\nAffecte-le avant la première opération de la base de données. Appelé uniquement par les bases de données `NOSQL()` et pas lorsque `textdb_worker` est activé.\n\nExample: Journaliser les insertions\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nAppelé pour chaque document modifié.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Le document après la modification. |\n\nAffecte-le avant la première opération de la base de données. Appelé par `NOSQL()` et `TABLE()`, pas lorsque `textdb_worker` est activé.\n\nExample: Journaliser les mises à jour\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nAppelé pour chaque document supprimé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | L'enregistrement supprimé, tel que stocké dans le fichier. |\n\nAffecte-le avant la première opération de la base de données. Il reçoit la ligne stockée du document sous forme de chaîne (du JSON pour `NOSQL()`). Non appelé lorsque `textdb_worker` est activé.\n\nExample: Journaliser les suppressions\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nAjoute une condition qui compare un champ à une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n| `operator` | `String` | no | `==` | Opérateur de comparaison. |\n| `value` | `Object` | yes |  | Valeur à comparer. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nOpérateurs : `=` et `==` (égal), `!=` et `<>` (différent), `>`, `<`, `>=`, `<=`. Avec deux arguments, l'opérateur est `==`. Un nom avec des points lit un champ imbriqué (`address.city`) ; un parent manquant ne lève pas d'erreur.\n\nExample: Conditions\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nAjoute une condition sur le champ `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | L'id ou un tableau d'id. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUn tableau d'id fonctionne comme `in('id', ids)`.\n\nExample: Par id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Plusieurs id\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nLa valeur du champ doit figurer dans le tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n| `value` | `Array` | yes |  | Valeurs autorisées. |\n| `key` | `String` | no |  | Propriété à lire dans les objets de `value`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLorsque le champ contient un tableau, il suffit que l'un de ses éléments figure dans `value`. Avec `key`, `value` est un tableau d'objets dont la propriété `key` est utilisée.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: Id issus d'autres documents\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nLa valeur du champ ne doit pas figurer dans le tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n| `value` | `Array` | yes |  | Valeurs exclues. |\n| `key` | `String` | no |  | Propriété à lire dans les objets de `value`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nL'inverse de `in()`. Avec `key`, `value` est un tableau d'objets dont la propriété `key` est utilisée.\n\nExample: Not in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nLa valeur du champ doit être comprise entre deux valeurs, bornes incluses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n| `a` | `Number|Date|String` | yes |  | Valeur la plus basse. |\n| `b` | `Number|Date|String` | yes |  | Valeur la plus élevée. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nExample: Between\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nRecherche de texte insensible à la casse dans un champ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n| `value` | `String` | yes |  | Texte recherché. |\n| `where` | `String` | no |  | `beg` ou `end`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nSans `where`, le champ doit contenir la valeur. `beg` signifie qu'il commence par la valeur, `end` qu'il se termine par elle. Un champ contenant un tableau correspond lorsque l'un de ses éléments correspond. Un champ ou une valeur vide ne correspond jamais.\n\nExample: Recherche\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Commence par\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nLe champ ne doit pas être vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUn tableau doit contenir des éléments ; toute autre valeur doit être vraie.\n\nExample: Avec des photos\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nLe champ doit être vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du champ. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUn tableau vide, `null`, `undefined`, une chaîne vide, `0` ou `false`.\n\nExample: Sans note\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nCompare l'année d'un champ date. `month()` et `day()` comparent le mois (1-12) et le jour du mois.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Champ contenant une `Date`. |\n| `operator` | `String` | no | `=` | Opérateur de comparaison. |\n| `value` | `Number` | yes |  | Année, mois (1-12) ou jour. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`builder.month(name, [operator], value)` et `builder.day(name, [operator], value)` fonctionnent de la même façon. Les opérateurs sont les mêmes que dans `where()` ; la valeur par défaut est `=`. Les champs sans date ne correspondent jamais.\n\nExample: Commandes à partir de juin 2022\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nCombine avec OR les conditions ajoutées à l'intérieur de la fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)` qui ajoute des conditions. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLa fonction reçoit le builder (également comme `this`). Les conditions en dehors de la fonction restent combinées avec AND.\n\nExample: Or\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nAjoute une condition JavaScript brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Expression JavaScript, par ex. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Valeurs pour l'expression. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\n`code` est une expression qui retourne un booléen. Elle voit `doc` (le document) et `arg` (tes valeurs ; les clés de `arg` y sont copiées). Un code contenant les mots `require` ou `global` est rejeté et ne correspond à rien.\n\nExample: Règle\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nChoisit les champs retournés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Champs, par ex. `id,name,email` ou `-password`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUne liste séparée par des virgules. `-name` retire un champ et conserve les autres. `name as title` retourne le champ sous un autre nom.\n\nExample: Seulement certains champs\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Sans un champ\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nTrie le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Par ex. `name`, `created_desc` ou `country,name_desc`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAlias : `builder.gridsort()`. `name` ou `name_asc` trie par ordre croissant, `name_desc` par ordre décroissant. Plusieurs champs sont séparés par des virgules ; les noms avec des points trient selon des champs imbriqués.\n\nExample: Tri\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nRetourne au plus `count` documents.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Nombre maximal de documents. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAlias : `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSaute les `count` premiers documents correspondants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Nombre de documents à sauter. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nRetourne uniquement le premier document correspondant au lieu d'un tableau.\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nDans un `join()`, elle fait du champ joint un seul document (ou `null`) au lieu d'un tableau.\n\nExample: First\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSélectionne une page. Le numéro de page commence à `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Index de la page, à partir de `0`. |\n| `limit` | `Number` | no |  | Documents par page. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nDéfinit `skip` à `page * limit`. Sans `limit`, la valeur d'un `take()` précédent est utilisée. Pour les numéros de page issus de la query string, qui commencent à `1`, utilise `paginate()`.\n\nExample: Deuxième page\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSélectionne une page. Le numéro de page commence à `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Numéro de page, à partir de `1`. |\n| `limit` | `Number|String` | yes |  | Documents par page. |\n| `maxlimit` | `Number` | no |  | Limite la plus élevée autorisée. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAccepte des chaînes : les valeurs de la query string peuvent donc être passées telles quelles. Une page inférieure à `1` devient `1`. `limit` est plafonné par `maxlimit` ; sans `limit`, `maxlimit` est utilisé.\n\nExample: Depuis la query string\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nDéfinit la fonction qui reçoit le résultat, ou relie le builder à une opération `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` ou l'objet `$` d'une opération. |\n| `error` | `String` | no |  | Erreur lorsque rien n'a été trouvé, par ex. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` Le builder pour une fonction ; une promesse pour `$`.\n\nAvec une fonction, celle-ci reçoit `(err, response, meta)`. Avec le `$` d'une opération de schéma, une erreur est transmise à `$.invalid()` et la méthode retourne une promesse avec la réponse : tu peux donc utiliser `await`.\n\n`error` est utilisé lorsque la réponse est vide (rien, `0` ou un tableau vide) : la fonction le reçoit comme `err`, ou `$.invalid(error)` est appelé.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await dans une opération\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nRetourne une promesse avec la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)` qui retourne la valeur de la promesse. |\n\nReturns: `Promise` Promesse avec la réponse.\n\nLa promesse est rejetée avec l'erreur. `fn` peut transformer la réponse avant la résolution de la promesse.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Transformer\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nAppelle `fn` avec la réponse, ou `$.invalid()` en cas d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | L'objet `$` d'une opération. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Valeur passée à `fn` comme deuxième argument. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nDéfinit une erreur pour une réponse vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Message ou clé d'erreur. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nAlias : `builder.err()`. Lorsque la réponse est vide (rien, `0` ou un tableau vide), le callback reçoit cette erreur, ou `$.invalid()` est appelé lorsque le builder est relié à `$`.\n\nExample: Introuvable\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nModifie le document qu'insère un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUniquement pour `update(data, true)`. Lorsque rien ne correspond, `fn` reçoit les données qui seront insérées et le builder.\n\nExample: Upsert avec des champs supplémentaires\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nSauvegarde les documents originaux avant une mise à jour ou une suppression.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Champs supplémentaires de l'enregistrement de sauvegarde, par ex. l'auteur de la modification. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nChaque document modifié ou supprimé est ajouté à `{file}.bk` sous la forme `{ ...data, date, body }`, où `body` est le document original sous forme de chaîne JSON. Lis les sauvegardes avec `db.backups()`.\n\nExample: Sauvegarde avec l'utilisateur\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nAjoute à chaque résultat des documents issus d'une autre base de données.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Champ qui reçoit les documents joints. |\n| `database` | `String` | yes |  | `name`, `nosql/name` ou `table/name`. |\n| `type` | `String` | no | `left` | `inner` ; toute autre valeur donne une jointure gauche. |\n\nReturns: `QueryBuilder` Builder pour la base de données jointe.\n\nRetourne un nouveau builder pour la base de données jointe : définis le lien avec `on()`, et utilises-y `where()`, `fields()`, `take()` ou `first()`. Un `callback()` sur ce builder définit le callback de la requête principale.\n\n`database` est un nom NoSQL, `nosql/name` ou `table/name`. Par défaut (`left`), chaque document est conservé et `field` est un tableau (ou `null` avec `first()`). Avec `inner`, les documents sans correspondance sont exclus.\n\nExample: Commandes avec leur utilisateur\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nRelie une base de données jointe à la requête principale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Champ de la base de données jointe. |\n| `parentfield` | `String` | yes |  | Champ des documents de la requête principale. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nUtilise-la sur le builder retourné par `join()`. Un document joint correspond lorsque son `field` est égal au `parentfield` du document principal.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nAjoute une condition à partir d'une valeur de filtre saisie par un utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Clé dans `obj`. |\n| `obj` | `Object` | yes |  | Les valeurs du filtre, par ex. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` ou `Boolean`. |\n| `field` | `String` | no |  | Champ à filtrer lorsqu'il diffère de `name`. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLit `obj[name]` et ne fait rien lorsque la valeur est vide. La valeur est convertie avec `type` (`String`, `Number`, `Date` ou `Boolean`) :\n\n- `a - b` ajoute `between()`.\n- `a, b` ajoute `in()` ; pour les chaînes, un `search()` pour chaque valeur, combinés avec OR.\n- Une chaîne ajoute `search()` ; les autres types ajoutent `where()`.\n- Pour `Date` : `today`, `yesterday`, une année (`2022`), un numéro de mois, ou une date pour la journée entière.\n\nExample: Filtres issus de la query string\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nDéfinit les champs, les filtres, le tri et la pagination à partir de la query string d'une opération.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | L'objet `$` d'une opération de schéma. |\n| `allowedfields` | `String` | no |  | Champs supplémentaires, par ex. `id,created:date`. |\n| `skipfields` | `String` | no |  | Champs du schéma à exclure, par ex. `password`. |\n| `defsort` | `String|Number` | no |  | Tri par défaut, par ex. `created_desc`. Un nombre ici correspond à `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Taille de page la plus élevée. |\n\nReturns: `QueryBuilder` Le même builder, pour le chaînage.\n\nLit `$.query` et le schéma de l'opération :\n\n- `fields` : champs retournés ; uniquement les champs du schéma et `allowedfields`. Sans lui, tous les champs.\n- Toute clé portant le nom d'un champ du schéma ajoute un filtre avec `gridfilter()`.\n- `sort` : par ex. `name_desc` ; les champs inconnus sont ignorés. Sans lui, `defsort`.\n- `page` et `limit` : `paginate()` avec `maxlimit`.\n\n`allowedfields` ajoute des champs absents du schéma (`name:type`, où le type ajoute aussi un filtre) ; `skipfields` masque des champs du schéma.\n\nExample: Opération de requête\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvc2ah61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Database NoSQL","summary":"NOSQL(), TABLE(), i metodi del database, il query builder e le chiavi di configurazione del database integrato.","markdown":"---\ntitle: Database NoSQL\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Database NoSQL\n\n> NOSQL(), TABLE(), i metodi del database, il query builder e le chiavi di configurazione del database integrato.\n\n`NOSQL(name)` e `TABLE(name)` restituiscono un database salvato nella cartella `databases/`. I metodi del database avviano una query e restituiscono un query builder; i metodi del builder aggiungono condizioni, ordinamento, paginazione e la callback. In questo riferimento `db` è un database restituito da `NOSQL()` o `TABLE()` e `builder` il query builder. La guida [Database NoSQL](../../guides/nosql/) spiega come le parti funzionano insieme.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nRestituisce un database NoSQL: documenti JSON salvati in un file di testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del database, o `~` seguito da un percorso assoluto del file. |\n\nReturns: `Database` L'istanza del database.\n\nIl database è salvato in `databases/{name}.nosql`, un documento JSON per riga. L'istanza viene creata alla prima chiamata e poi riutilizzata. Un nome che inizia con `~` è un percorso assoluto del file; un'istanza di questo tipo non viene messa in cache.\n\nTutte le operazioni restituiscono un query builder e vengono eseguite in modo asincrono in una coda, una dopo l'altra.\n\nExample: Inserire e leggere\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: Un file al di fuori della cartella databases\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nRestituisce un database a tabella: righe con uno schema fisso salvate in un file di testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della tabella, o `~` seguito da un percorso assoluto del file. |\n\nReturns: `Database` L'istanza della tabella.\n\nLa tabella è salvata in `databases/{name}.table`. La prima riga contiene lo schema, ogni riga successiva un record con valori separati da `|`. Lo schema proviene dalla chiave di configurazione `table_{name}` o da `alter()`; finché una tabella non ha uno schema, le sue operazioni restano in attesa.\n\nTipi di colonna: `string`, `string(length)`, `number`, `number(length)`, `boolean` (o `bool`), `date` e `object`. Le colonne possono essere separate con `|`, `,` o `;`. I campi che non sono nello schema non vengono memorizzati. Quando ogni colonna ha una dimensione, le righe hanno una larghezza fissa. Una stringa più lunga della sua dimensione viene troncata.\n\nUna tabella usa gli stessi metodi e lo stesso query builder di `NOSQL()`. Un nome che inizia con `~` è un percorso assoluto del file.\n\nExample: Schema nel file di configurazione\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Usare la tabella\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nCartella per i file NoSQL e delle tabelle.\n\nPredefinito `/databases/`, relativo alla directory dell'app. `NOSQL()` e `TABLE()` creano la cartella quando serve.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nSchema della tabella `TABLE(name)`.\n\nLe colonne sono `name:type`, separate da `|`, `,` o `;`. Tipi: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. Quando lo schema nella configurazione è diverso dallo schema nel file, la tabella viene riscritta con il nuovo schema la prima volta che viene usata.\n\nExample: Configurazione\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nTiene in memoria i database piccoli per la lettura. Dimensione in megabyte.\n\nPredefinito `0` (disattivato). Un database il cui file è più piccolo di questo numero di megabyte viene messo in cache in memoria dopo essere stato letto, e le letture successive usano la cache. Le scritture mantengono la cache sincronizzata o la azzerano.\n\nExample: Cache dei database fino a 10 MB\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nEsegue il motore NoSQL in un worker thread.\n\nPredefinito `false`. Con `true`, e solo mentre il server web è in esecuzione, tutte le operazioni di `NOSQL()` e `TABLE()` vengono eseguite in un worker thread, così la lettura di file grandi non blocca il thread principale. I gestori `oninsert`, `onupdate` e `onremove` non vengono chiamati in questa modalità.\n\nExample: Configurazione\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nTrova documenti. La risposta è un array.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nAlias: `db.all()`. Aggiungi condizioni, ordinamento e limiti al builder restituito. La callback riceve `(err, items, meta)`, dove `meta` ha `count` (documenti corrispondenti), `counter`, `scanned` e `duration`.\n\nSenza ordinamento e paginazione, la lettura si ferma non appena vengono trovati `take()` documenti.\n\nExample: Trovare documenti\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nTrova documenti, leggendo il file dalla fine.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nCome `find()`, ma i documenti più recenti vengono per primi, perché i nuovi documenti vengono aggiunti alla fine del file.\n\nExample: Le ultime dieci voci del log\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nLegge un documento. La risposta è il documento o niente.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nAlias: `db.one()`. Legge il file dalla fine e si ferma alla prima corrispondenza, quindi con più corrispondenze restituisce quella più recente.\n\nExample: Leggere per id\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nTrova documenti e restituisce una pagina con i dati di paginazione.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nLa risposta è `{ page, pages, limit, count, items }`. `count` è il numero di tutti i documenti corrispondenti, quindi usalo con `page()` o `paginate()`.\n\nExample: Una pagina per una griglia\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nConta i documenti corrispondenti. La risposta è `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nExample: Contare\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nCalcola valori sui documenti corrispondenti: min, max, somma, conteggio o gruppi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` o `sum`. Con un solo argomento è il nome del campo. |\n| `key` | `String` | no |  | Campo da calcolare, o il campo per cui raggruppare quando è indicato `key2`. |\n| `key2` | `String` | no |  | Campo con i valori, raggruppati per `key`. |\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\n- `scalar(type, key)` o `scalar(key)`: la risposta è `{ count, sum, min, max }` per il campo `key`.\n- `scalar('group', key)`: conta i documenti per i valori di `key`, ad es. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)`: somma `key2` per i valori di `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)`: il valore più alto / più basso di `key2` per ogni valore di `key`; qualsiasi altro tipo somma `key2`.\n\nExample: Statistiche di un campo\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Somma per gruppo\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nRaggruppa i documenti per un campo e un periodo e restituisce min, max e conteggio di un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Campo per cui raggruppare. |\n| `datefield` | `String` | yes |  | Campo con una `Date`. |\n| `key` | `String` | yes |  | Campo con il valore misurato. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` o `yearly`; qualsiasi altro valore è giornaliero. |\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nLa risposta è `{ [group]: { [period]: { min, max, count } } }`. La chiave del periodo è la data formattata come `yyyyMMddHH` (`hourly`), `yyyyMMdd` (predefinito, giornaliero), `yyyyMM` (`monthly`) o `yyyy` (`yearly`). Vengono usati solo i documenti con una `Date` in `datefield`.\n\nExample: Temperature mensili per sensore\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nInserisce un documento. La risposta è `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Il documento. |\n| `check` | `Boolean` | no | `false` | Inserisce solo quando nessun documento corrisponde alle condizioni del builder restituito. |\n\nReturns: `QueryBuilder` Builder per la callback (e per le condizioni con `check`).\n\nIl documento viene aggiunto alla fine del file. I prefissi delle chiavi usati da `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`) vengono rimossi dalle chiavi.\n\nCon `check` impostato a `true` il metodo restituisce un builder per le condizioni: il documento viene inserito solo quando nessun documento vi corrisponde, altrimenti la risposta è `0`.\n\nExample: Inserire\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Inserire solo un'email univoca\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nModifica i campi dei documenti corrispondenti. La risposta è il numero di documenti modificati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Campi da modificare, con prefissi facoltativi. |\n| `upsert` | `Boolean` | no | `false` | Inserisce i dati quando nessun documento corrisponde. |\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nAlias: `db.modify()`, `db.mod()`. Cambiano solo i campi in `data`; gli altri campi restano. Le chiavi con valore `undefined` vengono saltate. Un prefisso nella chiave esegue un'operazione con il valore memorizzato:\n\n| Chiave | Operazione |\n| --- | --- |\n| `field` | Imposta il valore |\n| `+field` | Somma (un valore mancante vale `0`) |\n| `-field` | Sottrae |\n| `*field` | Moltiplica |\n| `/field` | Divide |\n| `!field` | Inverte un booleano; il valore viene ignorato |\n| `>field` | Mantiene il valore più alto |\n| `<field` | Mantiene il valore più basso |\n\nCon `upsert` i dati (senza i prefissi) vengono inseriti come nuovo documento quando non c'è stata alcuna corrispondenza; `builder.insert(fn)` può modificarli prima.\n\nExample: Aggiornare per id\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Upsert di un contatore\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nRimuove i documenti corrispondenti. La risposta è il numero di documenti rimossi.\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nAlias: `db.rem()`. I documenti rimossi vengono contrassegnati nel file; `clean()` libera lo spazio. Senza condizioni vengono rimossi tutti i documenti.\n\nExample: Rimuovere i documenti vecchi\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nRimuove tutti i documenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata quando il database è vuoto. |\n\nReturns: `QueryBuilder` Un builder.\n\nUn database NoSQL elimina il suo file dei dati. Una tabella mantiene solo la riga dello schema.\n\nExample: Svuotare\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nCompatta il file: lo riscrive senza le righe rimosse e obsolete.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata quando il file è stato riscritto. |\n\nReturns: `QueryBuilder` Il database.\n\nRimuovere un documento, e aggiornarne uno che cresce, lascia righe inutilizzate nel file. Esegui `clean()` di tanto in tanto, ad es. una volta al giorno, per rendere il file più piccolo e la lettura più veloce.\n\nExample: Pulire una volta al giorno\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nElimina il database: il file dei dati, i suoi backup (`.bk`) e il log (`.log`).\n\nReturns: `QueryBuilder` Un builder.\n\nUna callback impostata con `.callback()` viene chiamata quando l'eliminazione è messa in coda, con `{ success: true }` come primo argomento.\n\nExample: Eliminare\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nLegge i backup creati da `builder.backup()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder per le condizioni e la callback.\n\nI backup sono salvati in `{file}.bk`, dal più recente. Ogni record ha `date`, `body` (il documento originale come stringa JSON) e i campi che hai passato a `builder.backup(data)`. Puoi filtrare i record con il builder restituito.\n\nExample: Backup creati da un utente\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nRestituisce il numero di documenti e la dimensione del file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` Un builder.\n\nLa risposta è `{ documents, filesize }` (dimensione in byte). I valori provengono dall'ultimo conteggio del database; `db.recount()` conta di nuovo i documenti e misura di nuovo il file.\n\nExample: Utilizzo\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nImposta il buffer di lettura del database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Numero di documenti elaborati alla volta. |\n| `size` | `Number` | no | `32` | Dimensione del buffer di lettura in kB. |\n\nBuffer più grandi leggono i file grandi più velocemente e usano più memoria.\n\nExample: Buffer più grandi\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nEsegue una funzione mentre nessun'altra operazione del database è in esecuzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)`; chiama `next()` per rilasciare il lock. |\n\nLa callback riceve `next`. Le operazioni in coda aspettano finché non lo chiami.\n\nExample: Lock\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nImposta o modifica lo schema di una tabella. Solo per `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Colonne come `name:type`, separate da `\\|`, `,` o `;`. |\n| `callback` | `Function` | no |  | Chiamata quando lo schema è stato applicato. |\n\nReturns: `Database` La tabella.\n\nUna nuova tabella scrive la riga dello schema. Quando lo schema è diverso da quello corrente, il file viene riscritto e le righe esistenti ricevono le nuove colonne. Una colonna scritta come `newname=oldname:type` prende i valori della vecchia colonna.\n\nExample: Dichiarare una tabella\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Rinominare una colonna\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nChiamata per ogni documento inserito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Il documento inserito. |\n\nAssegnala prima della prima operazione del database. Viene chiamata solo dai database `NOSQL()` e non quando `textdb_worker` è attivo.\n\nExample: Registrare gli inserimenti\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nChiamata per ogni documento modificato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Il documento dopo la modifica. |\n\nAssegnala prima della prima operazione del database. Viene chiamata da `NOSQL()` e `TABLE()`, non quando `textdb_worker` è attivo.\n\nExample: Registrare gli aggiornamenti\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nChiamata per ogni documento rimosso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | Il record rimosso così come è memorizzato nel file. |\n\nAssegnala prima della prima operazione del database. Riceve la riga memorizzata del documento come stringa (JSON per `NOSQL()`). Non viene chiamata quando `textdb_worker` è attivo.\n\nExample: Registrare le rimozioni\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nAggiunge una condizione che confronta un campo con un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `operator` | `String` | no | `==` | Operatore di confronto. |\n| `value` | `Object` | yes |  | Valore con cui confrontare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nOperatori: `=` e `==` (uguale), `!=` e `<>` (diverso), `>`, `<`, `>=`, `<=`. Con due argomenti l'operatore è `==`. Un nome con punti legge un campo annidato (`address.city`); un genitore mancante non genera eccezioni.\n\nExample: Condizioni\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nAggiunge una condizione per il campo `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | L'id o un array di id. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn array di id funziona come `in('id', ids)`.\n\nExample: Per id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Più id\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nIl valore del campo deve essere nell'array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `value` | `Array` | yes |  | Valori consentiti. |\n| `key` | `String` | no |  | Proprietà da leggere dagli oggetti in `value`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nQuando il campo contiene un array, basta che uno dei suoi elementi sia in `value`. Con `key`, `value` è un array di oggetti e viene usata la loro proprietà `key`.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: Id da altri documenti\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nIl valore del campo non deve essere nell'array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `value` | `Array` | yes |  | Valori esclusi. |\n| `key` | `String` | no |  | Proprietà da leggere dagli oggetti in `value`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nL'opposto di `in()`. Con `key`, `value` è un array di oggetti e viene usata la loro proprietà `key`.\n\nExample: Not in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nIl valore del campo deve essere compreso tra due valori, entrambi inclusi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `a` | `Number|Date|String` | yes |  | Valore minimo. |\n| `b` | `Number|Date|String` | yes |  | Valore massimo. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nExample: Between\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nRicerca di testo in un campo, senza distinzione tra maiuscole e minuscole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n| `value` | `String` | yes |  | Testo cercato. |\n| `where` | `String` | no |  | `beg` o `end`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nSenza `where` il campo deve contenere il valore. `beg` significa che inizia con il valore, `end` che termina con esso. Un campo con un array corrisponde quando uno dei suoi elementi corrisponde. Un campo o un valore vuoto non corrisponde mai.\n\nExample: Ricerca\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Inizia con\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nIl campo non deve essere vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn array deve avere elementi; qualsiasi altro valore deve essere truthy.\n\nExample: Con foto\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nIl campo deve essere vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del campo. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn array vuoto, `null`, `undefined`, una stringa vuota, `0` o `false`.\n\nExample: Senza nota\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nConfronta l'anno di un campo data. `month()` e `day()` confrontano il mese (1-12) e il giorno del mese.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Campo con una `Date`. |\n| `operator` | `String` | no | `=` | Operatore di confronto. |\n| `value` | `Number` | yes |  | Anno, mese (1-12) o giorno. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`builder.month(name, [operator], value)` e `builder.day(name, [operator], value)` funzionano allo stesso modo. Gli operatori sono gli stessi di `where()`; il predefinito è `=`. I campi senza una data non corrispondono mai.\n\nExample: Ordini da giugno 2022 in poi\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nUnisce con OR le condizioni aggiunte all'interno della funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)` che aggiunge condizioni. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLa funzione riceve il builder (anche come `this`). Le condizioni al di fuori della funzione restano unite con AND.\n\nExample: Or\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nAggiunge una condizione JavaScript grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Espressione JavaScript, ad es. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Valori per l'espressione. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\n`code` è un'espressione che restituisce un booleano. Vede `doc` (il documento) e `arg` (i tuoi valori; le chiavi di `arg` vengono copiate in esso). Il codice con le parole `require` o `global` viene rifiutato e non corrisponde a nulla.\n\nExample: Regola\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nSceglie i campi restituiti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Campi, ad es. `id,name,email` o `-password`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUn elenco separato da virgole. `-name` rimuove un campo e mantiene gli altri. `name as title` restituisce il campo con un altro nome.\n\nExample: Solo alcuni campi\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Senza un campo\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nOrdina il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Ad es. `name`, `created_desc` o `country,name_desc`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAlias: `builder.gridsort()`. `name` o `name_asc` ordina in modo crescente, `name_desc` decrescente. Più campi si separano con virgole; i nomi con punti ordinano per campi annidati.\n\nExample: Ordinare\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nRestituisce al massimo `count` documenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Numero massimo di documenti. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAlias: `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nSalta i primi `count` documenti corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Numero di documenti da saltare. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nRestituisce solo il primo documento corrispondente invece di un array.\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nIn un `join()` fa sì che il campo unito sia un documento (o `null`) invece di un array.\n\nExample: First\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSeleziona una pagina. Il numero di pagina parte da `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Indice della pagina, a partire da `0`. |\n| `limit` | `Number` | no |  | Documenti per pagina. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nImposta `skip` a `page * limit`. Senza `limit` viene usato il valore di un `take()` precedente. Per i numeri di pagina della query string, che partono da `1`, usa `paginate()`.\n\nExample: Seconda pagina\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSeleziona una pagina. Il numero di pagina parte da `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Numero di pagina, a partire da `1`. |\n| `limit` | `Number|String` | yes |  | Documenti per pagina. |\n| `maxlimit` | `Number` | no |  | Limite massimo consentito. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAccetta stringhe, quindi i valori della query possono essere passati così come sono. Una pagina inferiore a `1` diventa `1`. `limit` è limitato da `maxlimit`; senza `limit`, viene usato `maxlimit`.\n\nExample: Dalla query\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nImposta la funzione che riceve il risultato, o collega il builder a un'operazione `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` o l'oggetto `$` di un'operazione. |\n| `error` | `String` | no |  | Errore quando non è stato trovato nulla, ad es. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` Il builder per una funzione; una promessa per `$`.\n\nCon una funzione, questa riceve `(err, response, meta)`. Con il `$` di un'operazione dello schema, un errore viene passato a `$.invalid()` e il metodo restituisce una promessa con la risposta, quindi puoi usare `await`.\n\n`error` viene usato quando la risposta è vuota (niente, `0` o un array vuoto): la funzione lo riceve come `err`, oppure viene chiamato `$.invalid(error)`.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await in un'operazione\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nRestituisce una promessa con la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)` che restituisce il valore per la promessa. |\n\nReturns: `Promise` Promessa con la risposta.\n\nLa promessa viene rifiutata con l'errore. `fn` può trasformare la risposta prima che la promessa venga risolta.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Trasformare\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nChiama `fn` con la risposta, o `$.invalid()` in caso di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | L'oggetto `$` di un'operazione. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Valore passato a `fn` come secondo argomento. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nImposta un errore per una risposta vuota.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Messaggio o chiave dell'errore. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nAlias: `builder.err()`. Quando la risposta è vuota (niente, `0` o un array vuoto), la callback riceve questo errore, oppure viene chiamato `$.invalid()` quando il builder è collegato a `$`.\n\nExample: Non trovato\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nModifica il documento che un upsert inserisce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nSolo per `update(data, true)`. Quando non c'è stata alcuna corrispondenza, `fn` riceve i dati che verranno inseriti e il builder.\n\nExample: Upsert con campi aggiuntivi\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nSalva i documenti originali prima di un aggiornamento o di una rimozione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Campi aggiuntivi per il record di backup, ad es. chi ha fatto la modifica. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nOgni documento modificato o rimosso viene aggiunto a `{file}.bk` come `{ ...data, date, body }`, dove `body` è il documento originale come stringa JSON. Leggi i backup con `db.backups()`.\n\nExample: Backup con l'utente\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nAggiunge a ogni risultato documenti da un altro database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Campo che riceve i documenti uniti. |\n| `database` | `String` | yes |  | `name`, `nosql/name` o `table/name`. |\n| `type` | `String` | no | `left` | `inner`; qualsiasi altro valore è un left join. |\n\nReturns: `QueryBuilder` Builder per il database unito.\n\nRestituisce un nuovo builder per il database unito: imposta il collegamento con `on()`, e usa su di esso `where()`, `fields()`, `take()` o `first()`. Una `callback()` su di esso imposta la callback della query principale.\n\n`database` è un nome NoSQL, `nosql/name` o `table/name`. Per impostazione predefinita (`left`) ogni documento viene mantenuto e `field` è un array (o `null` con `first()`). Con `inner`, i documenti senza corrispondenza vengono esclusi.\n\nExample: Ordini con il loro utente\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nCollega un database unito alla query principale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Campo nel database unito. |\n| `parentfield` | `String` | yes |  | Campo nei documenti della query principale. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nUsalo sul builder restituito da `join()`. Un documento unito corrisponde quando il suo `field` è uguale a `parentfield` del documento principale.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nAggiunge una condizione da un valore di filtro digitato da un utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Chiave in `obj`. |\n| `obj` | `Object` | yes |  | I valori del filtro, ad es. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` o `Boolean`. |\n| `field` | `String` | no |  | Campo da filtrare quando è diverso da `name`. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLegge `obj[name]` e non fa nulla quando è vuoto. Il valore viene convertito con `type` (`String`, `Number`, `Date` o `Boolean`):\n\n- `a - b` aggiunge `between()`.\n- `a, b` aggiunge `in()`; per le stringhe, `search()` per ogni valore, uniti con OR.\n- Una stringa aggiunge `search()`; gli altri tipi aggiungono `where()`.\n- Per `Date`: `today`, `yesterday`, un anno (`2022`), un numero di mese, o una data per l'intera giornata.\n\nExample: Filtri dalla query\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nImposta campi, filtri, ordinamento e paginazione dalla query di un'operazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | L'oggetto `$` di un'operazione dello schema. |\n| `allowedfields` | `String` | no |  | Campi aggiuntivi, ad es. `id,created:date`. |\n| `skipfields` | `String` | no |  | Campi dello schema da escludere, ad es. `password`. |\n| `defsort` | `String|Number` | no |  | Ordinamento predefinito, ad es. `created_desc`. Un numero qui è `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Dimensione massima della pagina. |\n\nReturns: `QueryBuilder` Lo stesso builder, per il concatenamento.\n\nLegge `$.query` e lo schema dell'operazione:\n\n- `fields`: campi restituiti; solo campi dello schema e `allowedfields`. Senza di esso, tutti.\n- Qualsiasi chiave con il nome di un campo dello schema aggiunge un filtro con `gridfilter()`.\n- `sort`: ad es. `name_desc`; i campi sconosciuti vengono ignorati. Senza di esso, `defsort`.\n- `page` e `limit`: `paginate()` con `maxlimit`.\n\n`allowedfields` aggiunge campi che non sono nello schema (`name:type`, dove il tipo aggiunge anche un filtro); `skipfields` nasconde campi dello schema.\n\nExample: Operazione di query\n\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabWvc2ah61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/nosql/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"NoSQL databáza","summary":"NOSQL(), TABLE(), metódy databázy, query builder a konfiguračné kľúče vstavanej databázy.","markdown":"---\ntitle: \"NoSQL databáza\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/nosql/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# NoSQL databáza\n\n> NOSQL(), TABLE(), metódy databázy, query builder a konfiguračné kľúče vstavanej databázy.\n\n`NOSQL(name)` a `TABLE(name)` vrátia databázu uloženú v priečinku `databases/`. Metódy databázy začnú dopyt a vrátia query builder; metódy buildera pridávajú podmienky, triedenie, stránkovanie a callback. V tejto referencii je `db` databáza vrátená z `NOSQL()` alebo `TABLE()` a `builder` je query builder. Príručka [NoSQL databáza](../../guides/nosql/) vysvetľuje, ako jednotlivé časti spolupracujú.\n\n## API\n\n### NOSQL(name)\n\nType: `method`\n\nVráti NoSQL databázu: JSON dokumenty uložené v textovom súbore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy, alebo `~` a za ním absolútna cesta k súboru. |\n\nReturns: `Database` Inštancia databázy.\n\nDatabáza je uložená v `databases/{name}.nosql`, jeden JSON dokument na riadok. Inštancia sa vytvorí pri prvom volaní a potom sa opakovane používa. Názov, ktorý začína `~`, je absolútna cesta k súboru; takáto inštancia sa neukladá do cache.\n\nVšetky operácie vracajú query builder a bežia asynchrónne vo fronte, jedna po druhej.\n\nExample: Vloženie a čítanie\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW });\n\nNOSQL('users').find().where('name', 'Peter').callback(function(err, items) {\n\tconsole.log(items);\n});\n```\n\nExample: Súbor mimo priečinka databases\n```js\nNOSQL('~/www/backup/orders.nosql').find().callback(console.log);\n```\n\n### TABLE(name)\n\nType: `method`\n\nVráti tabuľkovú databázu: riadky s pevnou schémou uložené v textovom súbore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov tabuľky, alebo `~` a za ním absolútna cesta k súboru. |\n\nReturns: `Database` Inštancia tabuľky.\n\nTabuľka je uložená v `databases/{name}.table`. Prvý riadok obsahuje schému, každý ďalší riadok jeden záznam s hodnotami oddelenými `|`. Schéma pochádza z konfiguračného kľúča `table_{name}` alebo z `alter()`; kým tabuľka nemá schému, jej operácie čakajú.\n\nTypy stĺpcov: `string`, `string(length)`, `number`, `number(length)`, `boolean` (alebo `bool`), `date` a `object`. Stĺpce môžeš oddeliť pomocou `|`, `,` alebo `;`. Polia, ktoré nie sú v schéme, sa neukladajú. Keď má každý stĺpec veľkosť, riadky majú pevnú šírku. Reťazec dlhší ako jeho veľkosť sa oreže.\n\nTabuľka používa rovnaké metódy a query builder ako `NOSQL()`. Názov, ktorý začína `~`, je absolútna cesta k súboru.\n\nExample: Schéma v konfiguračnom súbore\n```js\n// config\ntable_products  : id:string(20)|name:string(50)|price:number|stock:number|created:date\n```\n\nExample: Použitie tabuľky\n```js\nTABLE('products').insert({ id: UID(), name: 'Book', price: 12, stock: 5, created: NOW });\nTABLE('products').find().where('price', '<', 20).sort('name').callback(console.log);\n```\n\n### directory_databases : /databases/\n\nType: `config`\n\nPriečinok pre NoSQL a tabuľkové súbory.\n\nPredvolene `/databases/`, relatívne k adresáru aplikácie. `NOSQL()` a `TABLE()` vytvoria priečinok, keď ho potrebujú.\n\n### table_{name} : column:type|column:type\n\nType: `config`\n\nSchéma tabuľky `TABLE(name)`.\n\nStĺpce sú `name:type`, oddelené `|`, `,` alebo `;`. Typy: `string`, `string(length)`, `number`, `number(length)`, `boolean`, `bool`, `date`, `object`. Keď sa schéma v konfigurácii líši od schémy v súbore, tabuľka sa pri prvom použití prepíše na novú schému.\n\nExample: Konfigurácia\n```js\ntable_users     : id:string(20)|name:string(50)|email:string(120)|age:number|active:boolean|created:date\n```\n\n### textdb_inmemory : 0\n\nType: `config`\n\nDrží malé databázy v pamäti na čítanie. Veľkosť v megabajtoch.\n\nPredvolene `0` (vypnuté). Databáza, ktorej súbor je menší ako tento počet megabajtov, sa po načítaní uloží do cache v pamäti a ďalšie čítania použijú cache. Zápisy udržiavajú cache synchronizovanú alebo ju resetujú.\n\nExample: Cache pre databázy do 10 MB\n```js\n// config\ntextdb_inmemory : 10\n```\n\n### textdb_worker : false\n\nType: `config`\n\nSpustí NoSQL engine vo worker vlákne.\n\nPredvolene `false`. S `true`, a iba kým beží webový server, bežia všetky operácie `NOSQL()` a `TABLE()` vo worker vlákne, takže čítanie veľkých súborov neblokuje hlavné vlákno. Obsluhy `oninsert`, `onupdate` a `onremove` sa v tomto režime nevolajú.\n\nExample: Konfigurácia\n```js\ntextdb_worker : true\n```\n\n### db.find()\n\nType: `method`\n\nNájde dokumenty. Odpoveďou je pole.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nAlias: `db.all()`. Do vráteného buildera pridaj podmienky, triedenie a limity. Callback dostane `(err, items, meta)`, kde `meta` obsahuje `count` (vyhovujúce dokumenty), `counter`, `scanned` a `duration`.\n\nBez triedenia a stránkovania sa čítanie zastaví, hneď ako sa nájde `take()` dokumentov.\n\nExample: Hľadanie dokumentov\n```js\nNOSQL('users').find().where('active', true).sort('name').take(50).callback(function(err, items, meta) {\n\tconsole.log(items.length, meta.duration);\n});\n```\n\n### db.find2()\n\nType: `method`\n\nNájde dokumenty, pričom číta súbor od konca.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nAko `find()`, ale najnovšie dokumenty sú prvé, pretože nové dokumenty sa pripájajú na koniec súboru.\n\nExample: Posledných desať záznamov logu\n```js\nNOSQL('logs').find2().take(10).callback(console.log);\n```\n\n### db.read()\n\nType: `method`\n\nNačíta jeden dokument. Odpoveďou je dokument alebo nič.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nAlias: `db.one()`. Číta súbor od konca a zastaví sa pri prvej zhode, takže pri viacerých zhodách vráti najnovší.\n\nExample: Čítanie podľa id\n```js\nNOSQL('users').read().id(id).fields('-password').callback(function(err, user) {\n\tif (user)\n\t\tconsole.log(user.name);\n});\n```\n\n### db.list()\n\nType: `method`\n\nNájde dokumenty a vráti stránku s údajmi o stránkovaní.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nOdpoveďou je `{ page, pages, limit, count, items }`. `count` je počet všetkých vyhovujúcich dokumentov, preto ho používaj s `page()` alebo `paginate()`.\n\nExample: Stránka pre tabuľku (grid)\n```js\nNOSQL('users').list().search('name', $.query.q).sort('name').paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t// response.items, response.count, response.pages\n});\n```\n\n### db.count()\n\nType: `method`\n\nSpočíta vyhovujúce dokumenty. Odpoveďou je `{ count: Number }`.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nExample: Počet\n```js\nNOSQL('users').count().where('active', true).callback(function(err, response) {\n\tconsole.log(response.count);\n});\n```\n\n### db.scalar(type, key, [key2])\n\nType: `method`\n\nVypočíta hodnoty nad vyhovujúcimi dokumentmi: min, max, súčet, počet alebo skupiny.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `group`, `min`, `max` alebo `sum`. S jedným argumentom je to názov poľa. |\n| `key` | `String` | no |  | Pole na výpočet, alebo pole na zoskupenie, keď je zadané `key2`. |\n| `key2` | `String` | no |  | Pole s hodnotami, zoskupené podľa `key`. |\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\n- `scalar(type, key)` alebo `scalar(key)`: odpoveďou je `{ count, sum, min, max }` pre pole `key`.\n- `scalar('group', key)`: spočíta dokumenty podľa hodnôt `key`, napr. `{ admin: 2, user: 10 }`.\n- `scalar('group', key, key2)`: sčíta `key2` podľa hodnôt `key`.\n- `scalar('max', key, key2)`, `scalar('min', key, key2)`: najvyššia / najnižšia hodnota `key2` pre každú hodnotu `key`; akýkoľvek iný typ sčíta `key2`.\n\nExample: Štatistiky poľa\n```js\nNOSQL('orders').scalar('price').where('paid', true).callback(function(err, response) {\n\t// response: { count, sum, min, max }\n});\n```\n\nExample: Súčet podľa skupiny\n```js\nNOSQL('orders').scalar('group', 'country', 'price').callback(function(err, response) {\n\t// { SK: 1200, CZ: 800 }\n});\n```\n\n### db.stats(groupfield, datefield, key, [type])\n\nType: `method`\n\nZoskupí dokumenty podľa poľa a obdobia a vráti min, max a počet hodnoty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `groupfield` | `String` | yes |  | Pole na zoskupenie. |\n| `datefield` | `String` | yes |  | Pole s `Date`. |\n| `key` | `String` | yes |  | Pole s nameranou hodnotou. |\n| `type` | `String` | no | `daily` | `hourly`, `monthly` alebo `yearly`; čokoľvek iné je denne. |\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nOdpoveďou je `{ [group]: { [period]: { min, max, count } } }`. Kľúč obdobia je dátum naformátovaný ako `yyyyMMddHH` (`hourly`), `yyyyMMdd` (predvolené, denne), `yyyyMM` (`monthly`) alebo `yyyy` (`yearly`). Použijú sa iba dokumenty s `Date` v `datefield`.\n\nExample: Mesačné teploty podľa senzora\n```js\nNOSQL('measurements').stats('sensor', 'created', 'temperature', 'monthly').callback(function(err, response) {\n\t// { sensor1: { '202201': { min: -4, max: 8, count: 744 } } }\n});\n```\n\n### db.insert(doc, [check])\n\nType: `method`\n\nVloží dokument. Odpoveďou je `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Dokument. |\n| `check` | `Boolean` | no | `false` | Vloží iba vtedy, keď podmienkam vráteného buildera nevyhovuje žiadny dokument. |\n\nReturns: `QueryBuilder` Builder pre callback (a pre podmienky s `check`).\n\nDokument sa pripojí na koniec súboru. Prefixy kľúčov, ktoré používa `update()` (`+`, `-`, `*`, `/`, `!`, `=`, `<`, `>`), sa z kľúčov odstránia.\n\nS `check` nastaveným na `true` metóda vráti builder pre podmienky: dokument sa vloží, iba keď im nevyhovuje žiadny dokument, inak je odpoveďou `0`.\n\nExample: Vloženie\n```js\nNOSQL('users').insert({ id: UID(), name: 'Peter', created: NOW }).callback(function(err) {\n\tconsole.log('Inserted');\n});\n```\n\nExample: Vloženie iba jedinečného e-mailu\n```js\nNOSQL('users').insert(model, true).where('email', model.email).callback(function(err, count) {\n\tif (!count)\n\t\tconsole.log('Exists');\n});\n```\n\n### db.update(data, [upsert])\n\nType: `method`\n\nZmení polia vyhovujúcich dokumentov. Odpoveďou je počet zmenených dokumentov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Polia na zmenu, s voliteľnými prefixmi. |\n| `upsert` | `Boolean` | no | `false` | Vloží dáta, keď nevyhovuje žiadny dokument. |\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nAliasy: `db.modify()`, `db.mod()`. Zmenia sa iba polia v `data`; ostatné polia zostanú. Kľúče s hodnotou `undefined` sa preskočia. Prefix v kľúči vykoná operáciu s uloženou hodnotou:\n\n| Kľúč | Operácia |\n| --- | --- |\n| `field` | Nastaví hodnotu |\n| `+field` | Pripočíta (chýbajúca hodnota sa počíta ako `0`) |\n| `-field` | Odpočíta |\n| `*field` | Vynásobí |\n| `/field` | Vydelí |\n| `!field` | Prepne boolovskú hodnotu; hodnota sa ignoruje |\n| `>field` | Ponechá vyššiu hodnotu |\n| `<field` | Ponechá nižšiu hodnotu |\n\nS `upsert` sa dáta (bez prefixov) vložia ako nový dokument, keď nič nevyhovelo; `builder.insert(fn)` ich môže predtým upraviť.\n\nExample: Aktualizácia podľa id\n```js\nNOSQL('products').update({ price: 15, '+version': 1, updated: NOW }).id(id).callback(function(err, count) {\n\tconsole.log('Updated:', count);\n});\n```\n\nExample: Upsert počítadla\n```js\nNOSQL('visits').update({ id: url, '+count': 1 }, true).id(url);\n```\n\n### db.remove()\n\nType: `method`\n\nOdstráni vyhovujúce dokumenty. Odpoveďou je počet odstránených dokumentov.\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nAlias: `db.rem()`. Odstránené dokumenty sa v súbore označia; `clean()` uvoľní miesto. Bez podmienok sa odstránia všetky dokumenty.\n\nExample: Odstránenie starých dokumentov\n```js\nNOSQL('sessions').remove().where('expire', '<', NOW).callback(function(err, count) {\n\tconsole.log('Removed:', count);\n});\n```\n\n### db.clear([callback])\n\nType: `method`\n\nOdstráni všetky dokumenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Zavolá sa, keď je databáza prázdna. |\n\nReturns: `QueryBuilder` Builder.\n\nNoSQL databáza vymaže svoj dátový súbor. Tabuľka ponechá iba riadok so schémou.\n\nExample: Vyprázdnenie\n```js\nNOSQL('cache').clear(function() {\n\tconsole.log('Empty');\n});\n```\n\n### db.clean([callback])\n\nType: `method`\n\nZhustí súbor: prepíše ho bez odstránených a zastaraných riadkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Zavolá sa, keď je súbor prepísaný. |\n\nReturns: `QueryBuilder` Databáza.\n\nOdstránenie dokumentu a aktualizácia dokumentu, ktorý sa zväčší, nechávajú v súbore nepoužívané riadky. Spúšťaj `clean()` z času na čas, napr. raz denne, aby bol súbor menší a čítanie rýchlejšie.\n\nExample: Čistenie raz denne\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tNOSQL('logs').clean();\n});\n```\n\n### db.drop()\n\nType: `method`\n\nVymaže databázu: dátový súbor, jeho zálohy (`.bk`) a log (`.log`).\n\nReturns: `QueryBuilder` Builder.\n\nCallback nastavený cez `.callback()` sa zavolá, keď je vymazanie zaradené do fronty, so `{ success: true }` ako prvým argumentom.\n\nExample: Vymazanie\n```js\nNOSQL('temporary').drop();\n```\n\n### db.backups([callback])\n\nType: `method`\n\nNačíta zálohy vytvorené cez `builder.backup()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Builder pre podmienky a callback.\n\nZálohy sa ukladajú do `{file}.bk`, najnovšie ako prvé. Každý záznam má `date`, `body` (pôvodný dokument ako JSON reťazec) a polia, ktoré si odovzdal do `builder.backup(data)`. Záznamy môžeš filtrovať vráteným builderom.\n\nExample: Zálohy vytvorené používateľom\n```js\nNOSQL('products').backups().where('user', 'Peter').take(20).callback(function(err, items) {\n\titems.forEach(item => console.log(item.date, JSON.parse(item.body)));\n});\n```\n\n### db.usage([callback])\n\nType: `method`\n\nVráti počet dokumentov a veľkosť súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `QueryBuilder` Builder.\n\nOdpoveďou je `{ documents, filesize }` (veľkosť v bajtoch). Hodnoty pochádzajú z posledného spočítania databázy; `db.recount()` znova spočíta dokumenty a zmeria súbor.\n\nExample: Využitie\n```js\nNOSQL('users').usage(function(err, response) {\n\tconsole.log(response.documents, response.filesize);\n});\n```\n\n### db.memory([count], [size])\n\nType: `method`\n\nNastaví buffer na čítanie databázy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | no | `15` | Počet dokumentov spracovaných naraz. |\n| `size` | `Number` | no | `32` | Veľkosť buffera na čítanie v kB. |\n\nVäčšie buffery čítajú veľké súbory rýchlejšie a používajú viac pamäte.\n\nExample: Väčšie buffery\n```js\nNOSQL('logs').memory(50, 128);\n```\n\n### db.lock(callback)\n\nType: `method`\n\nSpustí funkciu, kým nebeží žiadna iná operácia databázy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(next)`; zavolaj `next()` na uvoľnenie zámku. |\n\nCallback dostane `next`. Operácie vo fronte čakajú, kým ho nezavoláš.\n\nExample: Zámok\n```js\nNOSQL('counters').lock(function(next) {\n\t// exclusive work with the file\n\tnext();\n});\n```\n\n### db.alter(schema, [callback])\n\nType: `method`\n\nNastaví alebo zmení schému tabuľky. Iba pre `TABLE()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Stĺpce ako `name:type`, oddelené `\\|`, `,` alebo `;`. |\n| `callback` | `Function` | no |  | Zavolá sa, keď je schéma použitá. |\n\nReturns: `Database` Tabuľka.\n\nNová tabuľka zapíše riadok so schémou. Keď sa schéma líši od aktuálnej, súbor sa prepíše a existujúce riadky dostanú nové stĺpce. Stĺpec zapísaný ako `newname=oldname:type` prevezme hodnoty starého stĺpca.\n\nExample: Deklarácia tabuľky\n```js\nTABLE('users').alter('id:string(20)|name:string(50)|age:number|active:boolean|created:date');\n```\n\nExample: Premenovanie stĺpca\n```js\nTABLE('users').alter('id:string(20)|fullname=name:string(50)|age:number|active:boolean|created:date');\n```\n\n### db.oninsert = function(doc) {}\n\nType: `delegate`\n\nVolá sa pre každý vložený dokument.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Vložený dokument. |\n\nPriraď ho pred prvou operáciou databázy. Volajú ho iba databázy `NOSQL()` a nevolá sa, keď je zapnuté `textdb_worker`.\n\nExample: Logovanie vložení\n```js\nvar db = NOSQL('orders');\ndb.oninsert = function(doc) {\n\tconsole.log('New order', doc.id);\n};\n```\n\n### db.onupdate = function(doc) {}\n\nType: `delegate`\n\nVolá sa pre každý zmenený dokument.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `doc` | `Object` | yes |  | Dokument po zmene. |\n\nPriraď ho pred prvou operáciou databázy. Volajú ho `NOSQL()` aj `TABLE()`, nie však, keď je zapnuté `textdb_worker`.\n\nExample: Logovanie aktualizácií\n```js\nNOSQL('orders').onupdate = function(doc) {\n\tconsole.log('Changed order', doc.id);\n};\n```\n\n### db.onremove = function(record) {}\n\nType: `delegate`\n\nVolá sa pre každý odstránený dokument.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `record` | `String` | yes |  | Odstránený záznam tak, ako je uložený v súbore. |\n\nPriraď ho pred prvou operáciou databázy. Dostane uložený riadok dokumentu ako reťazec (pre `NOSQL()` JSON). Nevolá sa, keď je zapnuté `textdb_worker`.\n\nExample: Logovanie odstránení\n```js\nNOSQL('orders').onremove = function(record) {\n\tvar doc = JSON.parse(record);\n\tconsole.log('Removed order', doc.id);\n};\n```\n\n### builder.where(name, [operator], value)\n\nType: `method`\n\nPridá podmienku, ktorá porovná pole s hodnotou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `operator` | `String` | no | `==` | Operátor porovnania. |\n| `value` | `Object` | yes |  | Hodnota na porovnanie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nOperátory: `=` a `==` (rovná sa), `!=` a `<>` (nerovná sa), `>`, `<`, `>=`, `<=`. S dvoma argumentmi je operátor `==`. Názov s bodkami číta vnorené pole (`address.city`); chýbajúci rodič nevyhodí chybu.\n\nExample: Podmienky\n```js\nNOSQL('users').find().where('role', 'admin').where('age', '>=', 18).where('address.city', 'Bratislava').callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nPridá podmienku pre pole `id`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | yes |  | Id alebo pole id. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPole id funguje ako `in('id', ids)`.\n\nExample: Podľa id\n```js\nNOSQL('users').read().id('3ab5k001pt51d').callback(console.log);\n```\n\nExample: Viacero id\n```js\nNOSQL('users').find().id(['a1', 'a2', 'a3']).callback(console.log);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nHodnota poľa musí byť v poli hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `Array` | yes |  | Povolené hodnoty. |\n| `key` | `String` | no |  | Vlastnosť, ktorá sa načíta z objektov vo `value`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nKeď pole obsahuje pole (array), stačí, ak je jedna z jeho položiek vo `value`. S `key` je `value` pole objektov a použije sa ich vlastnosť `key`.\n\nExample: In\n```js\nNOSQL('products').find().in('category', ['books', 'music']).callback(console.log);\n```\n\nExample: Id z iných dokumentov\n```js\nNOSQL('users').find().in('id', orders, 'userid').callback(console.log);\n```\n\n### builder.notin(name, value, [key])\n\nType: `method`\n\nHodnota poľa nesmie byť v poli hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `Array` | yes |  | Vylúčené hodnoty. |\n| `key` | `String` | no |  | Vlastnosť, ktorá sa načíta z objektov vo `value`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nOpak `in()`. S `key` je `value` pole objektov a použije sa ich vlastnosť `key`.\n\nExample: Not in\n```js\nNOSQL('orders').find().notin('status', ['canceled', 'deleted']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nHodnota poľa musí byť medzi dvoma hodnotami, vrátane oboch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `a` | `Number|Date|String` | yes |  | Najnižšia hodnota. |\n| `b` | `Number|Date|String` | yes |  | Najvyššia hodnota. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nExample: Between\n```js\nNOSQL('orders').find().between('created', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nVyhľadávanie textu v poli bez ohľadu na veľkosť písmen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n| `value` | `String` | yes |  | Hľadaný text. |\n| `where` | `String` | no |  | `beg` alebo `end`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nBez `where` musí pole obsahovať hodnotu. `beg` znamená, že ňou začína, `end`, že ňou končí. Pole s poľom (array) vyhovuje, keď vyhovuje jedna z jeho položiek. Prázdne pole alebo hodnota nevyhovujú nikdy.\n\nExample: Vyhľadávanie\n```js\nNOSQL('products').find().search('name', 'phone').callback(console.log);\n```\n\nExample: Začína na\n```js\nNOSQL('users').find().search('email', 'admin', 'beg').callback(console.log);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nPole nesmie byť prázdne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPole (array) musí mať položky; akákoľvek iná hodnota musí byť pravdivá.\n\nExample: S fotkami\n```js\nNOSQL('products').find().contains('photos').callback(console.log);\n```\n\n### builder.empty(name)\n\nType: `method`\n\nPole musí byť prázdne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPrázdne pole (array), `null`, `undefined`, prázdny reťazec, `0` alebo `false`.\n\nExample: Bez poznámky\n```js\nNOSQL('orders').find().empty('note').callback(console.log);\n```\n\n### builder.year(name, [operator], value)\n\nType: `method`\n\nPorovná rok dátumového poľa. `month()` a `day()` porovnajú mesiac (1-12) a deň v mesiaci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Pole s `Date`. |\n| `operator` | `String` | no | `=` | Operátor porovnania. |\n| `value` | `Number` | yes |  | Rok, mesiac (1-12) alebo deň. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`builder.month(name, [operator], value)` a `builder.day(name, [operator], value)` fungujú rovnako. Operátory sú rovnaké ako vo `where()`; predvolený je `=`. Polia bez dátumu nevyhovujú nikdy.\n\nExample: Objednávky od júna 2022\n```js\nNOSQL('orders').find().year('created', 2022).month('created', '>=', 6).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nSpojí podmienky pridané vnútri funkcie pomocou OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`, ktorá pridáva podmienky. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nFunkcia dostane builder (aj ako `this`). Podmienky mimo funkcie sa stále spájajú pomocou AND.\n\nExample: Or\n```js\nNOSQL('products').find().where('active', true).or(function(builder) {\n\tbuilder.where('stock', '>', 0);\n\tbuilder.where('preorder', true);\n}).callback(console.log);\n```\n\n### builder.rule(code, [arg])\n\nType: `method`\n\nPridá surovú JavaScript podmienku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | JavaScript výraz, napr. `doc.age > arg.age`. |\n| `arg` | `Object` | no |  | Hodnoty pre výraz. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\n`code` je výraz, ktorý vráti boolovskú hodnotu. Vidí `doc` (dokument) a `arg` (tvoje hodnoty; kľúče `arg` sa doň skopírujú). Kód so slovami `require` alebo `global` sa odmietne a nevyhovuje ničomu.\n\nExample: Pravidlo\n```js\nNOSQL('users').find().rule('doc.age >= arg.min && doc.age <= arg.max', { min: 18, max: 30 }).callback(console.log);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nVyberie vrátené polia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Polia, napr. `id,name,email` alebo `-password`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nZoznam oddelený čiarkami. `-name` odstráni pole a ostatné ponechá. `name as title` vráti pole pod iným názvom.\n\nExample: Iba niektoré polia\n```js\nNOSQL('users').find().fields('id,name,email').callback(console.log);\n```\n\nExample: Bez poľa\n```js\nNOSQL('users').read().id(id).fields('-password').callback(console.log);\n```\n\n### builder.sort(sort)\n\nType: `method`\n\nZoradí výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Napr. `name`, `created_desc` alebo `country,name_desc`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nAlias: `builder.gridsort()`. `name` alebo `name_asc` triedi vzostupne, `name_desc` zostupne. Viacero polí sa oddeľuje čiarkami; názvy s bodkami triedia podľa vnorených polí.\n\nExample: Triedenie\n```js\nNOSQL('users').find().sort('created_desc').take(10).callback(console.log);\n```\n\n### builder.take(count)\n\nType: `method`\n\nVráti najviac `count` dokumentov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximálny počet dokumentov. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nAlias: `builder.limit()`.\n\nExample: Take\n```js\nNOSQL('users').find().take(5).callback(console.log);\n```\n\n### builder.skip(count)\n\nType: `method`\n\nPreskočí prvých `count` vyhovujúcich dokumentov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet dokumentov na preskočenie. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nExample: Skip\n```js\nNOSQL('users').find().sort('name').skip(20).take(10).callback(console.log);\n```\n\n### builder.first()\n\nType: `method`\n\nVráti iba prvý vyhovujúci dokument namiesto poľa.\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nV `join()` z pripojeného poľa urobí jeden dokument (alebo `null`) namiesto poľa.\n\nExample: First\n```js\nNOSQL('users').find().where('role', 'admin').sort('created').first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nVyberie stránku. Číslo stránky začína od `0`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Index stránky, od `0`. |\n| `limit` | `Number` | no |  | Dokumenty na stránku. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nNastaví `skip` na `page * limit`. Bez `limit` sa použije hodnota z predchádzajúceho `take()`. Pre čísla stránok z query stringu, ktoré začínajú od `1`, použi `paginate()`.\n\nExample: Druhá stránka\n```js\nNOSQL('users').list().sort('name').page(1, 20).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nVyberie stránku. Číslo stránky začína od `1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number|String` | yes |  | Číslo stránky, od `1`. |\n| `limit` | `Number|String` | yes |  | Dokumenty na stránku. |\n| `maxlimit` | `Number` | no |  | Najvyšší povolený limit. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPrijíma reťazce, takže hodnoty z query môžeš odovzdať tak, ako sú. Stránka nižšia ako `1` sa zmení na `1`. `limit` je obmedzený hodnotou `maxlimit`; bez `limit` sa použije `maxlimit`.\n\nExample: Z query\n```js\nNOSQL('users').list().paginate($.query.page, $.query.limit, 100).callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.callback(fn, [error]) or builder.callback($, [error])\n\nType: `method`\n\nNastaví funkciu, ktorá dostane výsledok, alebo prepojí builder s operáciou `$`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response, meta)` alebo objekt `$` operácie. |\n| `error` | `String` | no |  | Chyba, keď sa nič nenašlo, napr. `error-users-404`. |\n\nReturns: `QueryBuilder|Promise` Builder pre funkciu; promise pre `$`.\n\nS funkciou dostane funkcia `(err, response, meta)`. S `$` operácie schémy sa chyba odovzdá do `$.invalid()` a metóda vráti promise s odpoveďou, takže na ňu môžeš použiť `await`.\n\n`error` sa použije, keď je odpoveď prázdna (nič, `0` alebo prázdne pole): funkcia ho dostane ako `err`, alebo sa zavolá `$.invalid(error)`.\n\nExample: Callback\n```js\nNOSQL('users').find().callback(function(err, items, meta) {\n\tconsole.log(items, meta.scanned);\n});\n```\n\nExample: Await v operácii\n```js\nschema.setRead(async function($) {\n\tvar item = await NOSQL('users').read().id($.id).callback($, 'error-users-404');\n\t$.callback(item);\n});\n```\n\n### builder.promise([fn])\n\nType: `method`\n\nVráti promise s odpoveďou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(response)`, ktorá vráti hodnotu pre promise. |\n\nReturns: `Promise` Promise s odpoveďou.\n\nPromise sa zamietne s chybou. `fn` môže transformovať odpoveď predtým, ako sa promise splní.\n\nExample: Await\n```js\nvar items = await NOSQL('users').find().where('active', true).promise();\n```\n\nExample: Transformácia\n```js\nvar count = await NOSQL('users').count().promise(response => response.count);\n```\n\n### builder.done($, fn, [param])\n\nType: `method`\n\nZavolá `fn` s odpoveďou, alebo pri chybe `$.invalid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Objekt `$` operácie. |\n| `fn` | `Function` | yes |  | `function(response, param)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn` ako druhý argument. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nExample: Done\n```js\nNOSQL('users').count().done($, function(response) {\n\t$.callback(response.count);\n});\n```\n\n### builder.error(message)\n\nType: `method`\n\nNastaví chybu pre prázdnu odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | yes |  | Chybová správa alebo kľúč. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nAlias: `builder.err()`. Keď je odpoveď prázdna (nič, `0` alebo prázdne pole), callback dostane túto chybu, alebo sa zavolá `$.invalid()`, keď je builder prepojený s `$`.\n\nExample: Nenájdené\n```js\nNOSQL('users').read().id(id).error('error-users-404').callback($);\n```\n\n### builder.insert(fn)\n\nType: `method`\n\nUpraví dokument, ktorý vloží upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(doc, builder)`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nIba pre `update(data, true)`. Keď nič nevyhovelo, `fn` dostane dáta, ktoré sa vložia, a builder.\n\nExample: Upsert s ďalšími poliami\n```js\nNOSQL('stats').update({ id: key, '+count': 1, updated: NOW }, true).id(key).insert(function(doc) {\n\tdoc.created = NOW;\n});\n```\n\n### builder.backup([data])\n\nType: `method`\n\nUloží pôvodné dokumenty pred aktualizáciou alebo odstránením.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ďalšie polia pre záznam zálohy, napr. kto urobil zmenu. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nKaždý zmenený alebo odstránený dokument sa pripojí do `{file}.bk` ako `{ ...data, date, body }`, kde `body` je pôvodný dokument ako JSON reťazec. Zálohy načítaš pomocou `db.backups()`.\n\nExample: Záloha s používateľom\n```js\nNOSQL('products').update(model).id(model.id).backup({ user: $.user.name }).callback($.done());\n```\n\n### builder.join(field, database, [type])\n\nType: `method`\n\nPridá ku každému výsledku dokumenty z inej databázy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Pole, ktoré dostane pripojené dokumenty. |\n| `database` | `String` | yes |  | `name`, `nosql/name` alebo `table/name`. |\n| `type` | `String` | no | `left` | `inner`; čokoľvek iné je left join. |\n\nReturns: `QueryBuilder` Builder pre pripojenú databázu.\n\nVráti nový builder pre pripojenú databázu: väzbu nastav pomocou `on()` a použi na ňom `where()`, `fields()`, `take()` alebo `first()`. `callback()` na ňom nastaví callback hlavného dopytu.\n\n`database` je názov NoSQL, `nosql/name` alebo `table/name`. Predvolene (`left`) sa ponechá každý dokument a `field` je pole (alebo `null` s `first()`). S `inner` sa dokumenty bez zhody vynechajú.\n\nExample: Objednávky s ich používateľom\n```js\nNOSQL('orders').find().where('paid', true).join('user', 'users').on('id', 'userid').fields('id,name').first().callback(function(err, items) {\n\t// items[0].user = { id, name }\n});\n```\n\n### builder.on(field, parentfield)\n\nType: `method`\n\nPrepojí pripojenú databázu s hlavným dopytom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `field` | `String` | yes |  | Pole v pripojenej databáze. |\n| `parentfield` | `String` | yes |  | Pole v dokumentoch hlavného dopytu. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nPouži ho na builderi, ktorý vráti `join()`. Pripojený dokument vyhovuje, keď sa jeho `field` rovná `parentfield` hlavného dokumentu.\n\nExample: On\n```js\nNOSQL('users').find().join('orders', 'orders').on('userid', 'id').callback(console.log);\n```\n\n### builder.gridfilter(name, obj, [type], [field])\n\nType: `method`\n\nPridá podmienku z hodnoty filtra, ktorú zadal používateľ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Kľúč v `obj`. |\n| `obj` | `Object` | yes |  | Hodnoty filtra, napr. `$.query`. |\n| `type` | `Function` | no | `String` | `String`, `Number`, `Date` alebo `Boolean`. |\n| `field` | `String` | no |  | Pole na filtrovanie, keď sa líši od `name`. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nNačíta `obj[name]` a nerobí nič, keď je prázdne. Hodnota sa prevedie pomocou `type` (`String`, `Number`, `Date` alebo `Boolean`):\n\n- `a - b` pridá `between()`.\n- `a, b` pridá `in()`; pre reťazce `search()` pre každú hodnotu, spojené pomocou OR.\n- Reťazec pridá `search()`; ostatné typy pridajú `where()`.\n- Pre `Date`: `today`, `yesterday`, rok (`2022`), číslo mesiaca alebo dátum pre celý deň.\n\nExample: Filtre z query\n```js\nvar builder = NOSQL('orders').list();\nbuilder.gridfilter('name', $.query);\nbuilder.gridfilter('price', $.query, Number);\nbuilder.gridfilter('created', $.query, Date);\nbuilder.paginate($.query.page, $.query.limit, 50);\nbuilder.callback(function(err, response) {\n\t$.callback(response);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])\n\nType: `method`\n\nNastaví polia, filtre, triedenie a stránkovanie z query operácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Objekt `$` operácie schémy. |\n| `allowedfields` | `String` | no |  | Ďalšie polia, napr. `id,created:date`. |\n| `skipfields` | `String` | no |  | Polia schémy, ktoré sa vynechajú, napr. `password`. |\n| `defsort` | `String|Number` | no |  | Predvolené triedenie, napr. `created_desc`. Číslo na tomto mieste je `maxlimit`. |\n| `maxlimit` | `Number` | no | `50` | Najväčšia veľkosť stránky. |\n\nReturns: `QueryBuilder` Ten istý builder, na reťazenie.\n\nNačíta `$.query` a schému operácie:\n\n- `fields`: vrátené polia; iba polia schémy a `allowedfields`. Bez neho všetky.\n- Akýkoľvek kľúč s názvom poľa schémy pridá filter pomocou `gridfilter()`.\n- `sort`: napr. `name_desc`; neznáme polia sa ignorujú. Bez neho `defsort`.\n- `page` a `limit`: `paginate()` s `maxlimit`.\n\n`allowedfields` pridá polia, ktoré nie sú v schéme (`name:type`, kde typ zároveň pridá filter); `skipfields` skryje polia schémy.\n\nExample: Operácia query\n```js\nschema.setQuery(async function($) {\n\tvar response = await NOSQL('users').list().autofill($, 'id,created:date', 'password', 'created_desc', 100).callback($);\n\t$.callback(response);\n});\n```\n","entries":[{"type":"method","name":"NOSQL()","signature":"NOSQL(name)","since":"","deprecated":false},{"type":"method","name":"TABLE()","signature":"TABLE(name)","since":"","deprecated":false},{"type":"config","name":"directory_databases","signature":"directory_databases : /databases/","since":"","deprecated":false},{"type":"config","name":"table_{name}","signature":"table_{name} : column:type|column:type","since":"","deprecated":false},{"type":"config","name":"textdb_inmemory","signature":"textdb_inmemory : 0","since":"","deprecated":false},{"type":"config","name":"textdb_worker","signature":"textdb_worker : false","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find()","since":"","deprecated":false},{"type":"method","name":"db.find2()","signature":"db.find2()","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read()","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list()","since":"","deprecated":false},{"type":"method","name":"db.count()","signature":"db.count()","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(type, key, [key2])","since":"","deprecated":false},{"type":"method","name":"db.stats()","signature":"db.stats(groupfield, datefield, key, [type])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(doc, [check])","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove()","since":"","deprecated":false},{"type":"method","name":"db.clear()","signature":"db.clear([callback])","since":"","deprecated":false},{"type":"method","name":"db.clean()","signature":"db.clean([callback])","since":"","deprecated":false},{"type":"method","name":"db.drop()","signature":"db.drop()","since":"","deprecated":false},{"type":"method","name":"db.backups()","signature":"db.backups([callback])","since":"","deprecated":false},{"type":"method","name":"db.usage()","signature":"db.usage([callback])","since":"","deprecated":false},{"type":"method","name":"db.memory()","signature":"db.memory([count], [size])","since":"","deprecated":false},{"type":"method","name":"db.lock()","signature":"db.lock(callback)","since":"","deprecated":false},{"type":"method","name":"db.alter()","signature":"db.alter(schema, [callback])","since":"","deprecated":false},{"type":"delegate","name":"db.oninsert","signature":"db.oninsert = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onupdate","signature":"db.onupdate = function(doc) {}","since":"","deprecated":false},{"type":"delegate","name":"db.onremove","signature":"db.onremove = function(record) {}","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.notin()","signature":"builder.notin(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.empty()","signature":"builder.empty(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [operator], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.rule()","signature":"builder.rule(code, [arg])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(sort)","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.skip()","signature":"builder.skip(count)","since":"","deprecated":false},{"type":"method","name":"builder.first()","signature":"builder.first()","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn, [error]) or builder.callback($, [error])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([fn])","since":"","deprecated":false},{"type":"method","name":"builder.done()","signature":"builder.done($, fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(message)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn)","since":"","deprecated":false},{"type":"method","name":"builder.backup()","signature":"builder.backup([data])","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(field, database, [type])","since":"","deprecated":false},{"type":"method","name":"builder.on()","signature":"builder.on(field, parentfield)","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [field])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [defsort], [maxlimit])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Localization","summary":"Resource files, translation functions, the localization delegate and the translate tool.","markdown":"---\ntitle: Localization\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localization\n\n> Resource files, translation functions, the localization delegate and the translate tool.\n\nGlobal functions, delegates, properties, configuration keys, view commands and command-line tools for resource files and translations. The guide [Localization](../../guides/localization/) explains how they work together, with examples; this page is the exact reference.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nA text file with `key : value` lines that holds the texts of one language.\n\nThe file name without `.resource` is the name of the resource, usually a language (`en`, `sk`). `default.resource` is the fallback for all languages. Each line holds a key, ` : ` and a value. Keep a space after the colon, because the parser skips the first character after `:`. Lines that start with `//` or `#` are comments. Keys `T` + hash are translations of `@(Text)` and are created by `total4 translate`. A resource is joined from files registered with `F.register()`, then `tmp/{name}.resource`, then `resources/{name}.resource`; a later line with the same key wins.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nReads a value from a resource file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | The resource name (file name without `.resource`), usually a language. |\n| `key` | `String` | yes |  | The key. |\n\nReturns: `String` The value, or an empty string.\n\nWith one argument it reads from `default.resource`. When the key is missing in the named resource, the value from `default.resource` is used and cached. The result is an empty string when the key exists nowhere. Parsed files are cached in `F.resources`.\n\nExample: Read values\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nTranslates one text the same way as `@(Text)` in views.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | The resource name. |\n| `text` | `String` | yes |  | The text in the default language, or `#key`. |\n\nReturns: `String` The translation or the original text.\n\nThe key is `T` plus the hash of the text. When no translation exists, the original text is returned. A text that starts with `#` (not followed by a space) is read as a resource key, so `TRANSLATE('sk', '#title')` is `RESOURCE('sk', 'title')`. Without a language, `default.resource` is used.\n\nExample: Translate a message\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nReplaces every `@(...)` in a string with its translation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | The resource name. |\n| `text` | `String` | yes |  | A string with `@(...)` commands. |\n\nReturns: `String` The translated string.\n\nUses the same rules as views: `@(Text)` is translated by hash, `@(#key)` is read from the resource, quotes are escaped when the command is inside quotes. A text with `@{notranslate}` is returned without that command and without translation. When the resource of the language does not exist, the texts stay.\n\nExample: Translate a template\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nWrites a resource into the temporary directory and clears its cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The resource name, or a URL that returns several resources. |\n| `value` | `String|Object|Array` | no |  | The content, an object, an array, or an `http(s)` URL. |\n\n`value` can be the content of a resource file (a string), an object `{ key: value }`, or an array of items with `id`/`key`/`code`/`language` and `value`/`name`/`text`/`body`. The result is saved as `tmp/{name}.resource` and joined with `resources/{name}.resource`, which wins for duplicate keys. `LOADRESOURCE(name, url)` downloads one resource; `LOADRESOURCE(url)` downloads an object or an array of several resources. Download errors are thrown.\n\nExample: Load from an object\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Download from a URL\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nSets the delegate that returns the language of each request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)` that returns a language string. |\n\nThe function is stored as `DEF.onLocale`. It receives `req`, `res` and, for static files, `true`. It must return the language, which is saved to `req.$language`. For WebSocket connections it gets only `req`.\n\nExample: Language from the query or the header\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nServes static files of a URL translated into the language of the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL, for example `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | File extensions (`.md`) and `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifies HTML. |\n\nCreates a file route that reads the file, replaces `@(...)` and returns it. Without an extension in the URL it handles `.html`, `.htm`, `.md` and `.txt`. HTML is minified unless `minify` is `false` or `flags` contains `nocompress`. In release mode the result is cached for each language. A URL that starts with `#` is taken from the sitemap.\n\nExample: Localized Markdown\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nThe delegate that returns the language of a request; `null` by default.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `res` | `Response` | no |  | The response. |\n| `isStaticFile` | `Boolean` | no |  | `true` for static files. |\n\nReturns: `String` The language, saved to `req.$language`.\n\nSet it with `LOCALIZE(fn)` or directly. It is called at the start of a static file request, after authorization for routes (so `req.user` is known), and when a WebSocket connects (with `req` only). `req.localize()` calls it again.\n\nExample: Language of the user\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nOption of the built-in session `AUTH()` that sets the language from the user.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | The user data from `onread`, or `null`. |\n| `req` | `Request` | yes |  | The request. |\n\nReturns: `String` The language.\n\nIt is called after the session is read, with the user data (or `null` when the session is missing or invalid) and the request. The returned value is saved to `req.$language`.\n\nExample: Language from the user\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nThe language of the controller; views and e-mails use it.\n\nReturns: `String`\n\nIt is set from `req.$language` when the controller is created, so it is `undefined` without a localization delegate. You can assign another value before you render a view. Views are compiled and cached for each language. `client.language` in WebSocket controllers works the same way.\n\nExample: Language from the URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nThe language of the request.\n\nReturns: `String`\n\nReturns `req.$language`. When it is not set, it returns the first language of the `Accept-Language` header in lower case (for example `en-us`) and keeps it. It can be assigned.\n\nExample: Read the language\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nRuns `DEF.onLocale` again and returns the new language.\n\nReturns: `String` The language.\n\nUseful when something that the delegate reads (a cookie, the user) has changed during the request.\n\nExample: Refresh the language\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nThe language of the request in schemas, operations, middleware and `AUTH()`.\n\nReturns: `String`\n\nIn schemas and operations it is `controller.language` (an empty string without a controller). In middleware it is `req.$language`. In an `AUTH()` delegate it is `req.language`, which falls back to `Accept-Language`, because the localization delegate runs after authorization.\n\nExample: Use it in a schema\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nMarks text for translation in views and static HTML files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | The text in the default language, or `#key`. |\n\nThe text is replaced with the translation from the resource of the current language when the view is compiled. The key is `T` plus a hash of the text; when there is no translation, or the resource file of the language does not exist, the original text stays. `@(#key)` reads a key from the resource directly. Inside quotes, quotes in the translation are escaped.\n\nExample: Translated text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nPrints a value from a resource file in a view, HTML-encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | The resource name. |\n| `key` | `String` | yes |  | The key. |\n\nReturns: `String` The value, or an empty string.\n\nIt calls `RESOURCE()`, so without `name` it reads `default.resource`. Use the view variable `language` to read the resource of the current language. `@{!resource(...)}` prints the value raw.\n\nExample: Resource values\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nThe language of the request inside a view.\n\nThe view variable `language` holds `req.$language`, or an empty string. Use it in expressions, for example in `@{resource(language, 'key')}` or in the `lang` attribute.\n\nExample: The lang attribute\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nTurns off translation of `@(...)` in a view.\n\nPut it anywhere in the view or in a string passed to `TRANSLATOR()`. It is removed from the output and the `@(...)` commands stay untouched. `@{nolocalize}` does the same.\n\nExample: A view without translation\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nSends an e-mail rendered from a view, in a given language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | The recipient or recipients. |\n| `subject` | `String` | yes |  | The subject. |\n| `view` | `String` | yes |  | The view name. |\n| `model` | `Object` | no |  | The model of the view. |\n| `language` | `String` | no |  | The language. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` The message.\n\nWith a language, the subject is translated (with `TRANSLATOR()` when it contains `@(`, otherwise with `TRANSLATE()`) and the view is rendered with that language. `language` and `callback` can be swapped.\n\nExample: A translated e-mail\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nSends a raw HTML e-mail, translated into a given language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | The recipient or recipients. |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The HTML body. |\n| `language` | `String` | no |  | The language. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` The message.\n\nWith a language, the subject is translated and every `@(...)` in the body is replaced. `language` and `callback` can be swapped.\n\nExample: A translated HTML e-mail\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRenders a view to a string, optionally in a given language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The view name. |\n| `model` | `Object` | no |  | The model. |\n| `layout` | `String` | no |  | The layout. |\n| `repository` | `Object` | no |  | The repository. |\n| `language` | `String` | no |  | The language. |\n\nReturns: `String` The HTML.\n\nThe language is used for `@(...)` in the view. Without it the view is translated with `default.resource`.\n\nExample: Render in Slovak\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormats a date; month and day names are read from a resource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | The format, for example `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | The resource with names of months and days. |\n\nReturns: `String` The formatted date.\n\n`MMMM` and `MMM` read the English month name (`January`…`December`) as a key from the resource, `dddd` and `ddd` the day name (`Sunday`…`Saturday`). When a key is missing, the English name is used.\n\nExample: Localized names\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nSets the resource and the key prefix for error messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The resource name. |\n| `prefix` | `String` | no | `''` | A prefix for keys. |\n\nReturns: `ErrorBuilder` The builder.\n\nErrors pushed with a key (`builder.push('email')`) are read as `prefix + name` from the resource. The builder then keeps this resource and is not switched to the language of the request.\n\nExample: Errors from a resource\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nSets only the resource for error messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The resource name. |\n\nReturns: `ErrorBuilder` The builder.\n\nThe framework calls it with the language of the request before it sends errors, unless you have set a resource yourself.\n\nExample: Fixed language\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nSets the prefix of keys for error messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | The prefix. |\n\nReturns: `ErrorBuilder` The builder.\n\nAn error pushed with a name is read as `prefix + name` from the resource.\n\nExample: A prefix\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nReads the errors of a schema from a fixed resource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The resource name. |\n\nReturns: `SchemaBuilderEntity` The schema.\n\nWithout it, errors of the schema are translated with the language of the request.\n\nExample: Errors from errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nSets a prefix for resource keys of the schema errors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | The prefix. |\n\nReturns: `SchemaBuilderEntity` The schema.\n\nA required or invalid field `email` is read as `prefix + 'email'` from the resource.\n\nExample: Prefixed keys\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nAdds a `.resource` file from another location to a resource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The path to a `.resource` file. |\n\nThe file name gives the resource name, so `/modules/shop/sk.resource` is added to the `sk` resource. A path that starts with `@` is in a package, `=` in a theme. Registered files are read before `tmp/` and `resources/`, so the application can override their keys. Other extensions throw an error.\n\nExample: Resources of a module\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nThe cache of parsed resources, by name.\n\nReturns: `Object`\n\nEach value is an object of keys and values. It is cleared every `default_interval_clear_resources` minutes, and for one name when `LOADRESOURCE()` or `F.register()` changes it.\n\nExample: Clear the cache\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nReturns the path of the resources directory or of a file in it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` The absolute path.\n\nExample: Path to a resource\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nThe directory with resource files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | A path relative to the root of the application. |\n\nExample: Another directory\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nTranslates `.html` and `.htm` files from `public/` with `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Enables translation of static HTML files. |\n\nThe translated files are cached for each language in release mode.\n\nExample: Turn it off\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nHow often, in minutes, the cache of resources is cleared.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minutes. |\n\nAfter clearing, resource files are read again on the next use, so changes appear without a restart. The `clear` event is emitted with `resources`.\n\nExample: Every five minutes\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nThe default resource of every new `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | The resource name. |\n\nNot set by default. The framework still switches error builders to the language of the request before it sends them.\n\nExample: Errors from errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nThe default key prefix of every new `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | The prefix. |\n\nNot set by default (an empty prefix).\n\nExample: Prefixed keys\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nCreates `translate.resource` with every text to translate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | A directory, a text file, or a text. |\n\nWithout an argument it scans the current directory (without `node_modules`, `tmp` and `.git`): `@(Text)` in `.html`, `.js` and sitemap files, and in `.js` also keys of `$.invalid('key')` and `.error('key')`. Texts are grouped under comments with the file names. `@(#key)` is skipped. With a text file, each line becomes one entry. With a text that is not a file, it prints its key.\n\nExample: Create the file\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nWrites the texts to translate into `translate.csv`.\n\nThe CSV has the columns `Hash;Text;Translation`. Fill the last column, then convert it back with `total4 csv`.\n\nExample: Export to CSV\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nCreates a resource file from a CSV file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The CSV file. |\n\nReads a `;`-separated CSV, skips the first row, and uses the first column as the key and the second as the value. The output has the same name with `.resource`.\n\nExample: Import from CSV\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nLists keys to add to and to remove from a resource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The new file, for example `translate.resource`. |\n| `target` | `String` | yes |  | The translated file. |\n\nCompares the keys of both files and writes `<target>-diff.txt` with the keys of `source` that the target does not have and the keys of the target that `source` does not have.\n\nExample: Find new texts\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nCopies values from one resource into another.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The file with new values. |\n| `target` | `String` | yes |  | The file to update. |\n\nWrites `<target>-merged.txt`: the lines of the target, with the value of each key replaced by the value from `source` when it has one.\n\nExample: Merge translations\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nAligns the keys and values of a resource file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The resource file. |\n\nWrites `<source>-cleaned.txt` with all keys padded to the same width and ` : ` between key and value.\n\nExample: Clean a file\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Lokalisierung","summary":"Ressourcendateien, Übersetzungsfunktionen, der Lokalisierungs-Delegate und das Übersetzungswerkzeug.","markdown":"---\ntitle: Lokalisierung\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Lokalisierung\n\n> Ressourcendateien, Übersetzungsfunktionen, der Lokalisierungs-Delegate und das Übersetzungswerkzeug.\n\nGlobale Funktionen, Delegates, Eigenschaften, Konfigurationsschlüssel, View-Befehle und Kommandozeilenwerkzeuge für Ressourcendateien und Übersetzungen. Der Leitfaden [Lokalisierung](../../guides/localization/) erklärt mit Beispielen, wie sie zusammenspielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nEine Textdatei mit `key : value`-Zeilen, die die Texte einer Sprache enthält.\n\nDer Dateiname ohne `.resource` ist der Name der Ressource, meist eine Sprache (`en`, `sk`). `default.resource` ist der Fallback für alle Sprachen. Jede Zeile enthält einen Schlüssel, ` : ` und einen Wert. Lass ein Leerzeichen nach dem Doppelpunkt, denn der Parser überspringt das erste Zeichen nach `:`. Zeilen, die mit `//` oder `#` beginnen, sind Kommentare. Schlüssel `T` + Hash sind Übersetzungen von `@(Text)` und werden von `total4 translate` erstellt. Eine Ressource wird aus mit `F.register()` registrierten Dateien, dann `tmp/{name}.resource`, dann `resources/{name}.resource` zusammengefügt; eine spätere Zeile mit demselben Schlüssel gewinnt.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nLiest einen Wert aus einer Ressourcendatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Der Name der Ressource (Dateiname ohne `.resource`), meist eine Sprache. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `String` Der Wert oder ein leerer String.\n\nMit einem Argument liest es aus `default.resource`. Fehlt der Schlüssel in der genannten Ressource, wird der Wert aus `default.resource` verwendet und gecacht. Das Ergebnis ist ein leerer String, wenn der Schlüssel nirgends existiert. Geparste Dateien werden in `F.resources` gecacht.\n\nExample: Werte lesen\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nÜbersetzt einen Text genauso wie `@(Text)` in Views.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | Der Name der Ressource. |\n| `text` | `String` | yes |  | Der Text in der Standardsprache oder `#key`. |\n\nReturns: `String` Die Übersetzung oder der Originaltext.\n\nDer Schlüssel ist `T` plus der Hash des Textes. Existiert keine Übersetzung, wird der Originaltext zurückgegeben. Ein Text, der mit `#` beginnt (ohne folgendes Leerzeichen), wird als Ressourcenschlüssel gelesen, daher ist `TRANSLATE('sk', '#title')` gleich `RESOURCE('sk', 'title')`. Ohne Sprache wird `default.resource` verwendet.\n\nExample: Eine Meldung übersetzen\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nErsetzt jedes `@(...)` in einem String durch seine Übersetzung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Der Name der Ressource. |\n| `text` | `String` | yes |  | Ein String mit `@(...)`-Befehlen. |\n\nReturns: `String` Der übersetzte String.\n\nVerwendet dieselben Regeln wie Views: `@(Text)` wird per Hash übersetzt, `@(#key)` wird aus der Ressource gelesen, Anführungszeichen werden maskiert, wenn der Befehl in Anführungszeichen steht. Ein Text mit `@{notranslate}` wird ohne diesen Befehl und ohne Übersetzung zurückgegeben. Existiert die Ressource der Sprache nicht, bleiben die Texte erhalten.\n\nExample: Ein Template übersetzen\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nSchreibt eine Ressource in das temporäre Verzeichnis und leert ihren Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Ressource oder eine URL, die mehrere Ressourcen zurückgibt. |\n| `value` | `String|Object|Array` | no |  | Der Inhalt, ein Objekt, ein Array oder eine `http(s)`-URL. |\n\n`value` kann der Inhalt einer Ressourcendatei (ein String), ein Objekt `{ key: value }` oder ein Array von Einträgen mit `id`/`key`/`code`/`language` und `value`/`name`/`text`/`body` sein. Das Ergebnis wird als `tmp/{name}.resource` gespeichert und mit `resources/{name}.resource` zusammengefügt, das bei doppelten Schlüsseln gewinnt. `LOADRESOURCE(name, url)` lädt eine Ressource herunter; `LOADRESOURCE(url)` lädt ein Objekt oder ein Array mit mehreren Ressourcen herunter. Download-Fehler werden geworfen.\n\nExample: Aus einem Objekt laden\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Von einer URL herunterladen\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nSetzt den Delegate, der die Sprache jeder Anfrage zurückgibt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)`, die einen Sprach-String zurückgibt. |\n\nDie Funktion wird als `DEF.onLocale` gespeichert. Sie erhält `req`, `res` und, für statische Dateien, `true`. Sie muss die Sprache zurückgeben, die in `req.$language` gespeichert wird. Für WebSocket-Verbindungen erhält sie nur `req`.\n\nExample: Sprache aus dem Query String oder dem Header\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nLiefert statische Dateien einer URL in die Sprache der Anfrage übersetzt aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL, zum Beispiel `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | Dateiendungen (`.md`) und `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifiziert HTML. |\n\nErstellt eine Datei-Route, die die Datei liest, `@(...)` ersetzt und sie zurückgibt. Ohne Endung in der URL verarbeitet sie `.html`, `.htm`, `.md` und `.txt`. HTML wird minifiziert, außer `minify` ist `false` oder `flags` enthält `nocompress`. Im Release-Modus wird das Ergebnis für jede Sprache gecacht. Eine URL, die mit `#` beginnt, wird aus der Sitemap übernommen.\n\nExample: Lokalisiertes Markdown\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nDer Delegate, der die Sprache einer Anfrage zurückgibt; standardmäßig `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `res` | `Response` | no |  | Die Antwort. |\n| `isStaticFile` | `Boolean` | no |  | `true` für statische Dateien. |\n\nReturns: `String` Die Sprache, gespeichert in `req.$language`.\n\nSetz ihn mit `LOCALIZE(fn)` oder direkt. Er wird zu Beginn einer Anfrage nach einer statischen Datei aufgerufen, bei Routen nach der Autorisierung (sodass `req.user` bekannt ist) und beim Verbinden eines WebSockets (nur mit `req`). `req.localize()` ruft ihn erneut auf.\n\nExample: Sprache des Benutzers\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nOption der eingebauten Session von `AUTH()`, die die Sprache vom Benutzer setzt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Die Benutzerdaten aus `onread` oder `null`. |\n| `req` | `Request` | yes |  | Die Anfrage. |\n\nReturns: `String` Die Sprache.\n\nSie wird nach dem Lesen der Session aufgerufen, mit den Benutzerdaten (oder `null`, wenn die Session fehlt oder ungültig ist) und der Anfrage. Der zurückgegebene Wert wird in `req.$language` gespeichert.\n\nExample: Sprache vom Benutzer\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nDie Sprache des Controllers; Views und E-Mails verwenden sie.\n\nReturns: `String`\n\nSie wird beim Erstellen des Controllers aus `req.$language` gesetzt, ist also ohne Lokalisierungs-Delegate `undefined`. Du kannst einen anderen Wert zuweisen, bevor du eine View renderst. Views werden für jede Sprache kompiliert und gecacht. `client.language` in WebSocket-Controllern funktioniert genauso.\n\nExample: Sprache aus der URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nDie Sprache der Anfrage.\n\nReturns: `String`\n\nGibt `req.$language` zurück. Ist sie nicht gesetzt, gibt es die erste Sprache des Headers `Accept-Language` in Kleinbuchstaben zurück (zum Beispiel `en-us`) und behält sie. Sie kann zugewiesen werden.\n\nExample: Die Sprache lesen\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nFührt `DEF.onLocale` erneut aus und gibt die neue Sprache zurück.\n\nReturns: `String` Die Sprache.\n\nNützlich, wenn sich während der Anfrage etwas geändert hat, das der Delegate liest (ein Cookie, der Benutzer).\n\nExample: Die Sprache aktualisieren\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nDie Sprache der Anfrage in Schemas, Operationen, Middleware und `AUTH()`.\n\nReturns: `String`\n\nIn Schemas und Operationen ist sie `controller.language` (ein leerer String ohne Controller). In Middleware ist sie `req.$language`. In einem `AUTH()`-Delegate ist sie `req.language`, das auf `Accept-Language` zurückfällt, weil der Lokalisierungs-Delegate nach der Autorisierung läuft.\n\nExample: In einem Schema verwenden\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nMarkiert Text zur Übersetzung in Views und statischen HTML-Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Der Text in der Standardsprache oder `#key`. |\n\nDer Text wird beim Kompilieren der View durch die Übersetzung aus der Ressource der aktuellen Sprache ersetzt. Der Schlüssel ist `T` plus ein Hash des Textes; gibt es keine Übersetzung oder existiert die Ressourcendatei der Sprache nicht, bleibt der Originaltext. `@(#key)` liest einen Schlüssel direkt aus der Ressource. In Anführungszeichen werden Anführungszeichen in der Übersetzung maskiert.\n\nExample: Übersetzter Text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nGibt einen Wert aus einer Ressourcendatei in einer View HTML-kodiert aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Der Name der Ressource. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `String` Der Wert oder ein leerer String.\n\nEs ruft `RESOURCE()` auf, daher liest es ohne `name` aus `default.resource`. Verwende die View-Variable `language`, um die Ressource der aktuellen Sprache zu lesen. `@{!resource(...)}` gibt den Wert roh aus.\n\nExample: Ressourcenwerte\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nDie Sprache der Anfrage innerhalb einer View.\n\nDie View-Variable `language` enthält `req.$language` oder einen leeren String. Verwende sie in Ausdrücken, zum Beispiel in `@{resource(language, 'key')}` oder im Attribut `lang`.\n\nExample: Das Attribut lang\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nSchaltet die Übersetzung von `@(...)` in einer View ab.\n\nSetz es an eine beliebige Stelle in der View oder in einem String, der an `TRANSLATOR()` übergeben wird. Es wird aus der Ausgabe entfernt, und die `@(...)`-Befehle bleiben unverändert. `@{nolocalize}` bewirkt dasselbe.\n\nExample: Eine View ohne Übersetzung\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nSendet eine aus einer View gerenderte E-Mail in einer bestimmten Sprache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Der Empfänger oder die Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `view` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | no |  | Das Model der View. |\n| `language` | `String` | no |  | Die Sprache. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nMit einer Sprache wird der Betreff übersetzt (mit `TRANSLATOR()`, wenn er `@(` enthält, sonst mit `TRANSLATE()`), und die View wird in dieser Sprache gerendert. `language` und `callback` können vertauscht werden.\n\nExample: Eine übersetzte E-Mail\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nSendet eine rohe HTML-E-Mail, übersetzt in eine bestimmte Sprache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Der Empfänger oder die Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Der HTML-Body. |\n| `language` | `String` | no |  | Die Sprache. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nMit einer Sprache wird der Betreff übersetzt und jedes `@(...)` im Body ersetzt. `language` und `callback` können vertauscht werden.\n\nExample: Eine übersetzte HTML-E-Mail\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRendert eine View in einen String, optional in einer bestimmten Sprache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der View. |\n| `model` | `Object` | no |  | Das Model. |\n| `layout` | `String` | no |  | Das Layout. |\n| `repository` | `Object` | no |  | Das Repository. |\n| `language` | `String` | no |  | Die Sprache. |\n\nReturns: `String` Das HTML.\n\nDie Sprache wird für `@(...)` in der View verwendet. Ohne sie wird die View mit `default.resource` übersetzt.\n\nExample: Auf Slowakisch rendern\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatiert ein Datum; Monats- und Tagesnamen werden aus einer Ressource gelesen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Das Format, zum Beispiel `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | Die Ressource mit den Namen von Monaten und Tagen. |\n\nReturns: `String` Das formatierte Datum.\n\n`MMMM` und `MMM` lesen den englischen Monatsnamen (`January`…`December`) als Schlüssel aus der Ressource, `dddd` und `ddd` den Tagesnamen (`Sunday`…`Saturday`). Fehlt ein Schlüssel, wird der englische Name verwendet.\n\nExample: Lokalisierte Namen\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nSetzt die Ressource und das Schlüsselpräfix für Fehlermeldungen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Ressource. |\n| `prefix` | `String` | no | `''` | Ein Präfix für Schlüssel. |\n\nReturns: `ErrorBuilder` Der Builder.\n\nMit einem Schlüssel hinzugefügte Fehler (`builder.push('email')`) werden als `prefix + name` aus der Ressource gelesen. Der Builder behält dann diese Ressource und wird nicht auf die Sprache der Anfrage umgeschaltet.\n\nExample: Fehler aus einer Ressource\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nSetzt nur die Ressource für Fehlermeldungen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Ressource. |\n\nReturns: `ErrorBuilder` Der Builder.\n\nDas Framework ruft es mit der Sprache der Anfrage auf, bevor es Fehler sendet, außer du hast selbst eine Ressource gesetzt.\n\nExample: Feste Sprache\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nSetzt das Präfix der Schlüssel für Fehlermeldungen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Das Präfix. |\n\nReturns: `ErrorBuilder` Der Builder.\n\nEin mit einem Namen hinzugefügter Fehler wird als `prefix + name` aus der Ressource gelesen.\n\nExample: Ein Präfix\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nLiest die Fehler eines Schemas aus einer festen Ressource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Ressource. |\n\nReturns: `SchemaBuilderEntity` Das Schema.\n\nOhne dies werden Fehler des Schemas mit der Sprache der Anfrage übersetzt.\n\nExample: Fehler aus errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nSetzt ein Präfix für Ressourcenschlüssel der Schemafehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Das Präfix. |\n\nReturns: `SchemaBuilderEntity` Das Schema.\n\nEin erforderliches oder ungültiges Feld `email` wird als `prefix + 'email'` aus der Ressource gelesen.\n\nExample: Schlüssel mit Präfix\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nFügt einer Ressource eine `.resource`-Datei aus einem anderen Ort hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Der Pfad zu einer `.resource`-Datei. |\n\nDer Dateiname bestimmt den Namen der Ressource, daher wird `/modules/shop/sk.resource` zur Ressource `sk` hinzugefügt. Ein Pfad, der mit `@` beginnt, liegt in einem Paket, mit `=` in einem Theme. Registrierte Dateien werden vor `tmp/` und `resources/` gelesen, sodass die Anwendung ihre Schlüssel überschreiben kann. Andere Endungen werfen einen Fehler.\n\nExample: Ressourcen eines Moduls\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nDer Cache der geparsten Ressourcen, nach Namen.\n\nReturns: `Object`\n\nJeder Wert ist ein Objekt aus Schlüsseln und Werten. Er wird alle `default_interval_clear_resources` Minuten geleert, und für einen einzelnen Namen, wenn `LOADRESOURCE()` oder `F.register()` ihn ändert.\n\nExample: Den Cache leeren\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nGibt den Pfad des Ressourcenverzeichnisses oder einer Datei darin zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Der absolute Pfad.\n\nExample: Pfad zu einer Ressource\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nDas Verzeichnis mit den Ressourcendateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | Ein Pfad relativ zum Stammverzeichnis der Anwendung. |\n\nExample: Ein anderes Verzeichnis\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nÜbersetzt `.html`- und `.htm`-Dateien aus `public/` mit `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Aktiviert die Übersetzung statischer HTML-Dateien. |\n\nDie übersetzten Dateien werden im Release-Modus für jede Sprache gecacht.\n\nExample: Abschalten\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nWie oft, in Minuten, der Ressourcen-Cache geleert wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minuten. |\n\nNach dem Leeren werden Ressourcendateien bei der nächsten Verwendung erneut gelesen, sodass Änderungen ohne Neustart sichtbar werden. Das Event `clear` wird mit `resources` ausgelöst.\n\nExample: Alle fünf Minuten\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nDie Standardressource jedes neuen `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | Der Name der Ressource. |\n\nStandardmäßig nicht gesetzt. Das Framework schaltet Error-Builder trotzdem auf die Sprache der Anfrage um, bevor es sie sendet.\n\nExample: Fehler aus errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nDas Standard-Schlüsselpräfix jedes neuen `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | Das Präfix. |\n\nStandardmäßig nicht gesetzt (ein leeres Präfix).\n\nExample: Schlüssel mit Präfix\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nErstellt `translate.resource` mit allen zu übersetzenden Texten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | Ein Verzeichnis, eine Textdatei oder ein Text. |\n\nOhne Argument durchsucht es das aktuelle Verzeichnis (ohne `node_modules`, `tmp` und `.git`): `@(Text)` in `.html`-, `.js`- und Sitemap-Dateien und in `.js` außerdem Schlüssel von `$.invalid('key')` und `.error('key')`. Die Texte werden unter Kommentaren mit den Dateinamen gruppiert. `@(#key)` wird übersprungen. Mit einer Textdatei wird jede Zeile zu einem Eintrag. Mit einem Text, der keine Datei ist, gibt es dessen Schlüssel aus.\n\nExample: Die Datei erstellen\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nSchreibt die zu übersetzenden Texte in `translate.csv`.\n\nDie CSV-Datei hat die Spalten `Hash;Text;Translation`. Füll die letzte Spalte aus und konvertiere sie dann mit `total4 csv` zurück.\n\nExample: Als CSV exportieren\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nErstellt eine Ressourcendatei aus einer CSV-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die CSV-Datei. |\n\nLiest eine durch `;` getrennte CSV-Datei, überspringt die erste Zeile und verwendet die erste Spalte als Schlüssel und die zweite als Wert. Die Ausgabe hat denselben Namen mit `.resource`.\n\nExample: Aus CSV importieren\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nListet Schlüssel auf, die zu einer Ressource hinzugefügt bzw. daraus entfernt werden müssen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die neue Datei, zum Beispiel `translate.resource`. |\n| `target` | `String` | yes |  | Die übersetzte Datei. |\n\nVergleicht die Schlüssel beider Dateien und schreibt `<target>-diff.txt` mit den Schlüsseln von `source`, die das Ziel nicht hat, und den Schlüsseln des Ziels, die `source` nicht hat.\n\nExample: Neue Texte finden\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nKopiert Werte aus einer Ressource in eine andere.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die Datei mit den neuen Werten. |\n| `target` | `String` | yes |  | Die zu aktualisierende Datei. |\n\nSchreibt `<target>-merged.txt`: die Zeilen des Ziels, wobei der Wert jedes Schlüssels durch den Wert aus `source` ersetzt wird, sofern dort einer existiert.\n\nExample: Übersetzungen zusammenführen\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nRichtet die Schlüssel und Werte einer Ressourcendatei aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die Ressourcendatei. |\n\nSchreibt `<source>-cleaned.txt`, in dem alle Schlüssel auf dieselbe Breite aufgefüllt sind und ` : ` zwischen Schlüssel und Wert steht.\n\nExample: Eine Datei bereinigen\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Localización","summary":"Archivos de recursos, funciones de traducción, el delegado de localización y la herramienta de traducción.","markdown":"---\ntitle: \"Localización\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localización\n\n> Archivos de recursos, funciones de traducción, el delegado de localización y la herramienta de traducción.\n\nFunciones globales, delegados, propiedades, claves de configuración, comandos de vista y herramientas de línea de comandos para archivos de recursos y traducciones. La guía [Localización](../../guides/localization/) explica cómo funcionan juntos, con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nUn archivo de texto con líneas `key : value` que contiene los textos de un idioma.\n\nEl nombre del archivo sin `.resource` es el nombre del recurso, normalmente un idioma (`en`, `sk`). `default.resource` es el respaldo para todos los idiomas. Cada línea contiene una clave, ` : ` y un valor. Deja un espacio después de los dos puntos, porque el parser omite el primer carácter después de `:`. Las líneas que empiezan con `//` o `#` son comentarios. Las claves `T` + hash son traducciones de `@(Text)` y las crea `total4 translate`. Un recurso se une a partir de los archivos registrados con `F.register()`, después `tmp/{name}.resource` y después `resources/{name}.resource`; una línea posterior con la misma clave gana.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nLee un valor de un archivo de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | El nombre del recurso (nombre del archivo sin `.resource`), normalmente un idioma. |\n| `key` | `String` | yes |  | La clave. |\n\nReturns: `String` El valor, o una cadena vacía.\n\nCon un argumento lee de `default.resource`. Cuando falta la clave en el recurso indicado, se usa el valor de `default.resource` y se guarda en caché. El resultado es una cadena vacía cuando la clave no existe en ningún sitio. Los archivos analizados se guardan en caché en `F.resources`.\n\nExample: Leer valores\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nTraduce un texto de la misma forma que `@(Text)` en las vistas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | El nombre del recurso. |\n| `text` | `String` | yes |  | El texto en el idioma predeterminado, o `#key`. |\n\nReturns: `String` La traducción o el texto original.\n\nLa clave es `T` más el hash del texto. Cuando no existe traducción, se devuelve el texto original. Un texto que empieza con `#` (no seguido de un espacio) se lee como clave de recurso, así que `TRANSLATE('sk', '#title')` equivale a `RESOURCE('sk', 'title')`. Sin idioma, se usa `default.resource`.\n\nExample: Traducir un mensaje\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nReemplaza cada `@(...)` de una cadena por su traducción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | El nombre del recurso. |\n| `text` | `String` | yes |  | Una cadena con comandos `@(...)`. |\n\nReturns: `String` La cadena traducida.\n\nUsa las mismas reglas que las vistas: `@(Text)` se traduce por hash, `@(#key)` se lee del recurso y las comillas se escapan cuando el comando está entre comillas. Un texto con `@{notranslate}` se devuelve sin ese comando y sin traducir. Cuando el recurso del idioma no existe, los textos se mantienen.\n\nExample: Traducir una plantilla\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nEscribe un recurso en el directorio temporal y vacía su caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del recurso, o una URL que devuelve varios recursos. |\n| `value` | `String|Object|Array` | no |  | El contenido, un objeto, un array o una URL `http(s)`. |\n\n`value` puede ser el contenido de un archivo de recursos (una cadena), un objeto `{ key: value }` o un array de elementos con `id`/`key`/`code`/`language` y `value`/`name`/`text`/`body`. El resultado se guarda como `tmp/{name}.resource` y se une con `resources/{name}.resource`, que gana en las claves duplicadas. `LOADRESOURCE(name, url)` descarga un recurso; `LOADRESOURCE(url)` descarga un objeto o un array de varios recursos. Los errores de descarga se lanzan como excepción.\n\nExample: Cargar desde un objeto\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Descargar desde una URL\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nDefine el delegado que devuelve el idioma de cada petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)` que devuelve una cadena con el idioma. |\n\nLa función se guarda como `DEF.onLocale`. Recibe `req`, `res` y, para archivos estáticos, `true`. Debe devolver el idioma, que se guarda en `req.$language`. Para conexiones WebSocket solo recibe `req`.\n\nExample: Idioma desde la query string o la cabecera\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nSirve los archivos estáticos de una URL traducidos al idioma de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL, por ejemplo `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | Extensiones de archivo (`.md`) y `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifica el HTML. |\n\nCrea una ruta de archivo que lee el archivo, reemplaza `@(...)` y lo devuelve. Sin extensión en la URL gestiona `.html`, `.htm`, `.md` y `.txt`. El HTML se minifica salvo que `minify` sea `false` o `flags` contenga `nocompress`. En modo release el resultado se guarda en caché para cada idioma. Una URL que empieza con `#` se toma del sitemap.\n\nExample: Markdown localizado\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nEl delegado que devuelve el idioma de una petición; `null` por defecto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `res` | `Response` | no |  | La respuesta. |\n| `isStaticFile` | `Boolean` | no |  | `true` para archivos estáticos. |\n\nReturns: `String` El idioma, guardado en `req.$language`.\n\nDefínelo con `LOCALIZE(fn)` o directamente. Se llama al inicio de una petición de archivo estático, después de la autorización en las rutas (así `req.user` ya se conoce) y cuando se conecta un WebSocket (solo con `req`). `req.localize()` lo vuelve a llamar.\n\nExample: Idioma del usuario\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nOpción del `AUTH()` de sesión integrado que define el idioma a partir del usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Los datos del usuario de `onread`, o `null`. |\n| `req` | `Request` | yes |  | La petición. |\n\nReturns: `String` El idioma.\n\nSe llama después de leer la sesión, con los datos del usuario (o `null` cuando la sesión falta o no es válida) y la petición. El valor devuelto se guarda en `req.$language`.\n\nExample: Idioma a partir del usuario\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nEl idioma del controlador; lo usan las vistas y los correos electrónicos.\n\nReturns: `String`\n\nSe define a partir de `req.$language` cuando se crea el controlador, así que es `undefined` sin un delegado de localización. Puedes asignar otro valor antes de renderizar una vista. Las vistas se compilan y se guardan en caché para cada idioma. `client.language` en los controladores WebSocket funciona igual.\n\nExample: Idioma desde la URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nEl idioma de la petición.\n\nReturns: `String`\n\nDevuelve `req.$language`. Cuando no está definido, devuelve el primer idioma de la cabecera `Accept-Language` en minúsculas (por ejemplo `en-us`) y lo conserva. Se puede asignar.\n\nExample: Leer el idioma\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nEjecuta `DEF.onLocale` de nuevo y devuelve el nuevo idioma.\n\nReturns: `String` El idioma.\n\nÚtil cuando algo que lee el delegado (una cookie, el usuario) ha cambiado durante la petición.\n\nExample: Actualizar el idioma\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nEl idioma de la petición en esquemas, operaciones, middleware y `AUTH()`.\n\nReturns: `String`\n\nEn esquemas y operaciones es `controller.language` (una cadena vacía sin controlador). En middleware es `req.$language`. En un delegado de `AUTH()` es `req.language`, que recurre a `Accept-Language`, porque el delegado de localización se ejecuta después de la autorización.\n\nExample: Usarlo en un esquema\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nMarca texto para traducir en vistas y archivos HTML estáticos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | El texto en el idioma predeterminado, o `#key`. |\n\nEl texto se reemplaza por la traducción del recurso del idioma actual cuando se compila la vista. La clave es `T` más un hash del texto; cuando no hay traducción, o el archivo de recursos del idioma no existe, se mantiene el texto original. `@(#key)` lee una clave directamente del recurso. Dentro de comillas, las comillas de la traducción se escapan.\n\nExample: Texto traducido\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nImprime en una vista un valor de un archivo de recursos, codificado en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | El nombre del recurso. |\n| `key` | `String` | yes |  | La clave. |\n\nReturns: `String` El valor, o una cadena vacía.\n\nLlama a `RESOURCE()`, así que sin `name` lee `default.resource`. Usa la variable de vista `language` para leer el recurso del idioma actual. `@{!resource(...)}` imprime el valor sin codificar.\n\nExample: Valores de recursos\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nEl idioma de la petición dentro de una vista.\n\nLa variable de vista `language` contiene `req.$language`, o una cadena vacía. Úsala en expresiones, por ejemplo en `@{resource(language, 'key')}` o en el atributo `lang`.\n\nExample: El atributo lang\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nDesactiva la traducción de `@(...)` en una vista.\n\nColócalo en cualquier parte de la vista o en una cadena pasada a `TRANSLATOR()`. Se elimina de la salida y los comandos `@(...)` quedan intactos. `@{nolocalize}` hace lo mismo.\n\nExample: Una vista sin traducción\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nEnvía un correo electrónico renderizado a partir de una vista, en un idioma dado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | El destinatario o los destinatarios. |\n| `subject` | `String` | yes |  | El asunto. |\n| `view` | `String` | yes |  | El nombre de la vista. |\n| `model` | `Object` | no |  | El modelo de la vista. |\n| `language` | `String` | no |  | El idioma. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` El mensaje.\n\nCon un idioma, el asunto se traduce (con `TRANSLATOR()` cuando contiene `@(`, si no con `TRANSLATE()`) y la vista se renderiza en ese idioma. `language` y `callback` se pueden intercambiar.\n\nExample: Un correo electrónico traducido\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nEnvía un correo electrónico HTML sin procesar, traducido a un idioma dado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | El destinatario o los destinatarios. |\n| `subject` | `String` | yes |  | El asunto. |\n| `body` | `String` | yes |  | El cuerpo HTML. |\n| `language` | `String` | no |  | El idioma. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` El mensaje.\n\nCon un idioma, el asunto se traduce y cada `@(...)` del cuerpo se reemplaza. `language` y `callback` se pueden intercambiar.\n\nExample: Un correo electrónico HTML traducido\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRenderiza una vista en una cadena, opcionalmente en un idioma dado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la vista. |\n| `model` | `Object` | no |  | El modelo. |\n| `layout` | `String` | no |  | La plantilla (layout). |\n| `repository` | `Object` | no |  | El repositorio. |\n| `language` | `String` | no |  | El idioma. |\n\nReturns: `String` El HTML.\n\nEl idioma se usa para `@(...)` en la vista. Sin él, la vista se traduce con `default.resource`.\n\nExample: Renderizar en eslovaco\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatea una fecha; los nombres de meses y días se leen de un recurso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | El formato, por ejemplo `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | El recurso con los nombres de meses y días. |\n\nReturns: `String` La fecha formateada.\n\n`MMMM` y `MMM` leen el nombre del mes en inglés (`January`…`December`) como clave del recurso, y `dddd` y `ddd` el nombre del día (`Sunday`…`Saturday`). Cuando falta una clave, se usa el nombre en inglés.\n\nExample: Nombres localizados\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nDefine el recurso y el prefijo de clave para los mensajes de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del recurso. |\n| `prefix` | `String` | no | `''` | Un prefijo para las claves. |\n\nReturns: `ErrorBuilder` El builder.\n\nLos errores añadidos con una clave (`builder.push('email')`) se leen del recurso como `prefix + name`. A partir de entonces el builder conserva este recurso y no se cambia al idioma de la petición.\n\nExample: Errores desde un recurso\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nDefine solo el recurso para los mensajes de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del recurso. |\n\nReturns: `ErrorBuilder` El builder.\n\nEl framework lo llama con el idioma de la petición antes de enviar los errores, salvo que tú mismo hayas definido un recurso.\n\nExample: Idioma fijo\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nDefine el prefijo de las claves para los mensajes de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | El prefijo. |\n\nReturns: `ErrorBuilder` El builder.\n\nUn error añadido con un nombre se lee del recurso como `prefix + name`.\n\nExample: Un prefijo\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nLee los errores de un esquema desde un recurso fijo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del recurso. |\n\nReturns: `SchemaBuilderEntity` El esquema.\n\nSin esto, los errores del esquema se traducen con el idioma de la petición.\n\nExample: Errores desde errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nDefine un prefijo para las claves de recurso de los errores del esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | El prefijo. |\n\nReturns: `SchemaBuilderEntity` El esquema.\n\nUn campo `email` obligatorio o no válido se lee del recurso como `prefix + 'email'`.\n\nExample: Claves con prefijo\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nAñade a un recurso un archivo `.resource` de otra ubicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La ruta a un archivo `.resource`. |\n\nEl nombre del archivo da el nombre del recurso, así que `/modules/shop/sk.resource` se añade al recurso `sk`. Una ruta que empieza con `@` está en un paquete, y con `=` en un tema. Los archivos registrados se leen antes que `tmp/` y `resources/`, así que la aplicación puede sobrescribir sus claves. Otras extensiones lanzan un error.\n\nExample: Recursos de un módulo\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nLa caché de recursos analizados, por nombre.\n\nReturns: `Object`\n\nCada valor es un objeto de claves y valores. Se vacía cada `default_interval_clear_resources` minutos, y para un nombre concreto cuando `LOADRESOURCE()` o `F.register()` lo modifican.\n\nExample: Vaciar la caché\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nDevuelve la ruta del directorio de recursos o de un archivo dentro de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` La ruta absoluta.\n\nExample: Ruta a un recurso\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nEl directorio con los archivos de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | Una ruta relativa a la raíz de la aplicación. |\n\nExample: Otro directorio\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nTraduce los archivos `.html` y `.htm` de `public/` con `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Activa la traducción de archivos HTML estáticos. |\n\nLos archivos traducidos se guardan en caché para cada idioma en modo release.\n\nExample: Desactivarlo\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nCada cuántos minutos se vacía la caché de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minutos. |\n\nDespués de vaciarla, los archivos de recursos se vuelven a leer en el siguiente uso, así que los cambios aparecen sin reiniciar. Se emite el evento `clear` con `resources`.\n\nExample: Cada cinco minutos\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nEl recurso predeterminado de cada nuevo `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | El nombre del recurso. |\n\nNo está definido por defecto. Aun así, el framework cambia los error builders al idioma de la petición antes de enviarlos.\n\nExample: Errores desde errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nEl prefijo de clave predeterminado de cada nuevo `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | El prefijo. |\n\nNo está definido por defecto (un prefijo vacío).\n\nExample: Claves con prefijo\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nCrea `translate.resource` con todos los textos que hay que traducir.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | Un directorio, un archivo de texto o un texto. |\n\nSin argumento analiza el directorio actual (sin `node_modules`, `tmp` ni `.git`): `@(Text)` en archivos `.html`, `.js` y de sitemap, y en `.js` también las claves de `$.invalid('key')` y `.error('key')`. Los textos se agrupan bajo comentarios con los nombres de archivo. `@(#key)` se omite. Con un archivo de texto, cada línea se convierte en una entrada. Con un texto que no es un archivo, imprime su clave.\n\nExample: Crear el archivo\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nEscribe los textos que hay que traducir en `translate.csv`.\n\nEl CSV tiene las columnas `Hash;Text;Translation`. Rellena la última columna y conviértelo de nuevo con `total4 csv`.\n\nExample: Exportar a CSV\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nCrea un archivo de recursos a partir de un archivo CSV.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo CSV. |\n\nLee un CSV separado por `;`, omite la primera fila y usa la primera columna como clave y la segunda como valor. La salida tiene el mismo nombre con `.resource`.\n\nExample: Importar desde CSV\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nLista las claves que hay que añadir a un recurso y quitar de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El archivo nuevo, por ejemplo `translate.resource`. |\n| `target` | `String` | yes |  | El archivo traducido. |\n\nCompara las claves de ambos archivos y escribe `<target>-diff.txt` con las claves de `source` que el destino no tiene y las claves del destino que `source` no tiene.\n\nExample: Encontrar textos nuevos\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nCopia valores de un recurso a otro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El archivo con los valores nuevos. |\n| `target` | `String` | yes |  | El archivo que hay que actualizar. |\n\nEscribe `<target>-merged.txt`: las líneas del destino, con el valor de cada clave reemplazado por el valor de `source` cuando este lo tiene.\n\nExample: Combinar traducciones\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nAlinea las claves y los valores de un archivo de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El archivo de recursos. |\n\nEscribe `<source>-cleaned.txt` con todas las claves rellenadas al mismo ancho y ` : ` entre la clave y el valor.\n\nExample: Limpiar un archivo\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Localisation","summary":"Les fichiers de ressources, les fonctions de traduction, le délégué de localisation et l'outil de traduction.","markdown":"---\ntitle: Localisation\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localisation\n\n> Les fichiers de ressources, les fonctions de traduction, le délégué de localisation et l'outil de traduction.\n\nFonctions globales, délégués, propriétés, clés de configuration, commandes de vue et outils en ligne de commande pour les fichiers de ressources et les traductions. Le guide [Localisation](../../guides/localization/) explique comment ils fonctionnent ensemble, avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nUn fichier texte avec des lignes `key : value` qui contient les textes d'une langue.\n\nLe nom du fichier sans `.resource` est le nom de la ressource, généralement une langue (`en`, `sk`). `default.resource` sert de repli pour toutes les langues. Chaque ligne contient une clé, ` : ` et une valeur. Laisse un espace après les deux-points, car l'analyseur ignore le premier caractère après `:`. Les lignes qui commencent par `//` ou `#` sont des commentaires. Les clés `T` + hachage sont des traductions de `@(Text)` et sont créées par `total4 translate`. Une ressource est assemblée à partir des fichiers enregistrés avec `F.register()`, puis de `tmp/{name}.resource`, puis de `resources/{name}.resource` ; une ligne ultérieure avec la même clé l'emporte.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nLit une valeur dans un fichier de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Le nom de la ressource (nom de fichier sans `.resource`), généralement une langue. |\n| `key` | `String` | yes |  | La clé. |\n\nReturns: `String` La valeur, ou une chaîne vide.\n\nAvec un seul argument, elle lit dans `default.resource`. Quand la clé manque dans la ressource nommée, la valeur de `default.resource` est utilisée et mise en cache. Le résultat est une chaîne vide quand la clé n'existe nulle part. Les fichiers analysés sont mis en cache dans `F.resources`.\n\nExample: Lire des valeurs\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nTraduit un texte de la même façon que `@(Text)` dans les vues.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | Le nom de la ressource. |\n| `text` | `String` | yes |  | Le texte dans la langue par défaut, ou `#key`. |\n\nReturns: `String` La traduction ou le texte d'origine.\n\nLa clé est `T` suivi du hachage du texte. Quand aucune traduction n'existe, le texte d'origine est renvoyé. Un texte qui commence par `#` (non suivi d'un espace) est lu comme une clé de ressource, ainsi `TRANSLATE('sk', '#title')` équivaut à `RESOURCE('sk', 'title')`. Sans langue, `default.resource` est utilisé.\n\nExample: Traduire un message\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nRemplace chaque `@(...)` d'une chaîne par sa traduction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Le nom de la ressource. |\n| `text` | `String` | yes |  | Une chaîne contenant des commandes `@(...)`. |\n\nReturns: `String` La chaîne traduite.\n\nApplique les mêmes règles que les vues : `@(Text)` est traduit par hachage, `@(#key)` est lu dans la ressource, les guillemets sont échappés quand la commande est entre guillemets. Un texte contenant `@{notranslate}` est renvoyé sans cette commande et sans traduction. Quand la ressource de la langue n'existe pas, les textes restent inchangés.\n\nExample: Traduire un modèle\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nÉcrit une ressource dans le répertoire temporaire et vide son cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la ressource, ou une URL qui renvoie plusieurs ressources. |\n| `value` | `String|Object|Array` | no |  | Le contenu, un objet, un tableau ou une URL `http(s)`. |\n\n`value` peut être le contenu d'un fichier de ressources (une chaîne), un objet `{ key: value }`, ou un tableau d'éléments avec `id`/`key`/`code`/`language` et `value`/`name`/`text`/`body`. Le résultat est enregistré sous `tmp/{name}.resource` et joint à `resources/{name}.resource`, qui l'emporte pour les clés en double. `LOADRESOURCE(name, url)` télécharge une ressource ; `LOADRESOURCE(url)` télécharge un objet ou un tableau de plusieurs ressources. Les erreurs de téléchargement sont levées.\n\nExample: Charger depuis un objet\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Télécharger depuis une URL\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nDéfinit le délégué qui renvoie la langue de chaque requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)` qui renvoie une chaîne de langue. |\n\nLa fonction est stockée dans `DEF.onLocale`. Elle reçoit `req`, `res` et, pour les fichiers statiques, `true`. Elle doit renvoyer la langue, qui est enregistrée dans `req.$language`. Pour les connexions WebSocket, elle ne reçoit que `req`.\n\nExample: Langue depuis la query ou l'en-tête\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nSert les fichiers statiques d'une URL traduits dans la langue de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL, par exemple `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | Les extensions de fichiers (`.md`) et `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifie le HTML. |\n\nCrée une route de fichier qui lit le fichier, remplace `@(...)` et le renvoie. Sans extension dans l'URL, elle gère `.html`, `.htm`, `.md` et `.txt`. Le HTML est minifié sauf si `minify` vaut `false` ou si `flags` contient `nocompress`. En mode release, le résultat est mis en cache pour chaque langue. Une URL qui commence par `#` est prise dans le sitemap.\n\nExample: Markdown localisé\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nLe délégué qui renvoie la langue d'une requête ; `null` par défaut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `res` | `Response` | no |  | La réponse. |\n| `isStaticFile` | `Boolean` | no |  | `true` pour les fichiers statiques. |\n\nReturns: `String` La langue, enregistrée dans `req.$language`.\n\nDéfinis-le avec `LOCALIZE(fn)` ou directement. Il est appelé au début d'une requête de fichier statique, après l'autorisation pour les routes (donc `req.user` est connu), et lorsqu'un WebSocket se connecte (avec `req` uniquement). `req.localize()` l'appelle de nouveau.\n\nExample: Langue de l'utilisateur\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nOption du `AUTH()` à session intégré qui définit la langue à partir de l'utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Les données de l'utilisateur issues de `onread`, ou `null`. |\n| `req` | `Request` | yes |  | La requête. |\n\nReturns: `String` La langue.\n\nElle est appelée après la lecture de la session, avec les données de l'utilisateur (ou `null` quand la session est absente ou invalide) et la requête. La valeur renvoyée est enregistrée dans `req.$language`.\n\nExample: Langue depuis l'utilisateur\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nLa langue du contrôleur ; les vues et les e-mails l'utilisent.\n\nReturns: `String`\n\nElle est définie à partir de `req.$language` à la création du contrôleur, elle vaut donc `undefined` sans délégué de localisation. Tu peux affecter une autre valeur avant de rendre une vue. Les vues sont compilées et mises en cache pour chaque langue. `client.language` dans les contrôleurs WebSocket fonctionne de la même façon.\n\nExample: Langue depuis l'URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nLa langue de la requête.\n\nReturns: `String`\n\nRenvoie `req.$language`. Quand elle n'est pas définie, renvoie la première langue de l'en-tête `Accept-Language` en minuscules (par exemple `en-us`) et la conserve. Elle peut être affectée.\n\nExample: Lire la langue\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nExécute de nouveau `DEF.onLocale` et renvoie la nouvelle langue.\n\nReturns: `String` La langue.\n\nUtile quand un élément lu par le délégué (un cookie, l'utilisateur) a changé pendant la requête.\n\nExample: Actualiser la langue\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nLa langue de la requête dans les schémas, les opérations, les middlewares et `AUTH()`.\n\nReturns: `String`\n\nDans les schémas et les opérations, il s'agit de `controller.language` (une chaîne vide sans contrôleur). Dans un middleware, il s'agit de `req.$language`. Dans un délégué `AUTH()`, il s'agit de `req.language`, qui se rabat sur `Accept-Language`, car le délégué de localisation s'exécute après l'autorisation.\n\nExample: L'utiliser dans un schéma\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nMarque du texte à traduire dans les vues et les fichiers HTML statiques.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Le texte dans la langue par défaut, ou `#key`. |\n\nLe texte est remplacé par la traduction issue de la ressource de la langue courante lors de la compilation de la vue. La clé est `T` suivi d'un hachage du texte ; sans traduction, ou si le fichier de ressources de la langue n'existe pas, le texte d'origine reste. `@(#key)` lit directement une clé dans la ressource. Entre guillemets, les guillemets de la traduction sont échappés.\n\nExample: Texte traduit\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nAffiche dans une vue une valeur d'un fichier de ressources, encodée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Le nom de la ressource. |\n| `key` | `String` | yes |  | La clé. |\n\nReturns: `String` La valeur, ou une chaîne vide.\n\nElle appelle `RESOURCE()`, donc sans `name` elle lit `default.resource`. Utilise la variable de vue `language` pour lire la ressource de la langue courante. `@{!resource(...)}` affiche la valeur brute.\n\nExample: Valeurs de ressource\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nLa langue de la requête à l'intérieur d'une vue.\n\nLa variable de vue `language` contient `req.$language`, ou une chaîne vide. Utilise-la dans des expressions, par exemple dans `@{resource(language, 'key')}` ou dans l'attribut `lang`.\n\nExample: L'attribut lang\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nDésactive la traduction de `@(...)` dans une vue.\n\nPlace-la n'importe où dans la vue ou dans une chaîne passée à `TRANSLATOR()`. Elle est retirée de la sortie et les commandes `@(...)` restent intactes. `@{nolocalize}` fait la même chose.\n\nExample: Une vue sans traduction\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nEnvoie un e-mail rendu à partir d'une vue, dans une langue donnée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Le ou les destinataires. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `view` | `String` | yes |  | Le nom de la vue. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n| `language` | `String` | no |  | La langue. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Le message.\n\nAvec une langue, le sujet est traduit (avec `TRANSLATOR()` quand il contient `@(`, sinon avec `TRANSLATE()`) et la vue est rendue dans cette langue. `language` et `callback` peuvent être intervertis.\n\nExample: Un e-mail traduit\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nEnvoie un e-mail HTML brut, traduit dans une langue donnée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Le ou les destinataires. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le corps HTML. |\n| `language` | `String` | no |  | La langue. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Le message.\n\nAvec une langue, le sujet est traduit et chaque `@(...)` du corps est remplacé. `language` et `callback` peuvent être intervertis.\n\nExample: Un e-mail HTML traduit\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nRend une vue dans une chaîne, éventuellement dans une langue donnée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la vue. |\n| `model` | `Object` | no |  | Le modèle. |\n| `layout` | `String` | no |  | Le layout. |\n| `repository` | `Object` | no |  | Le repository. |\n| `language` | `String` | no |  | La langue. |\n\nReturns: `String` Le HTML.\n\nLa langue est utilisée pour les `@(...)` de la vue. Sans elle, la vue est traduite avec `default.resource`.\n\nExample: Rendu en slovaque\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormate une date ; les noms des mois et des jours sont lus dans une ressource.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Le format, par exemple `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | La ressource contenant les noms des mois et des jours. |\n\nReturns: `String` La date formatée.\n\n`MMMM` et `MMM` lisent le nom anglais du mois (`January`…`December`) comme clé dans la ressource, `dddd` et `ddd` le nom du jour (`Sunday`…`Saturday`). Quand une clé manque, le nom anglais est utilisé.\n\nExample: Noms localisés\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nDéfinit la ressource et le préfixe de clé des messages d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la ressource. |\n| `prefix` | `String` | no | `''` | Un préfixe pour les clés. |\n\nReturns: `ErrorBuilder` Le builder.\n\nLes erreurs ajoutées avec une clé (`builder.push('email')`) sont lues sous la forme `prefix + name` dans la ressource. Le builder conserve alors cette ressource et ne passe pas à la langue de la requête.\n\nExample: Erreurs depuis une ressource\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nDéfinit uniquement la ressource des messages d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la ressource. |\n\nReturns: `ErrorBuilder` Le builder.\n\nLe framework l'appelle avec la langue de la requête avant d'envoyer les erreurs, sauf si tu as défini une ressource toi-même.\n\nExample: Langue fixe\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nDéfinit le préfixe des clés des messages d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Le préfixe. |\n\nReturns: `ErrorBuilder` Le builder.\n\nUne erreur ajoutée avec un nom est lue sous la forme `prefix + name` dans la ressource.\n\nExample: Un préfixe\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nLit les erreurs d'un schéma depuis une ressource fixe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la ressource. |\n\nReturns: `SchemaBuilderEntity` Le schéma.\n\nSans elle, les erreurs du schéma sont traduites dans la langue de la requête.\n\nExample: Erreurs depuis errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nDéfinit un préfixe pour les clés de ressource des erreurs du schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Le préfixe. |\n\nReturns: `SchemaBuilderEntity` Le schéma.\n\nUn champ `email` obligatoire ou invalide est lu sous la forme `prefix + 'email'` dans la ressource.\n\nExample: Clés préfixées\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nAjoute à une ressource un fichier `.resource` situé ailleurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le chemin vers un fichier `.resource`. |\n\nLe nom du fichier donne le nom de la ressource, ainsi `/modules/shop/sk.resource` est ajouté à la ressource `sk`. Un chemin qui commence par `@` se trouve dans un paquet, par `=` dans un thème. Les fichiers enregistrés sont lus avant `tmp/` et `resources/`, l'application peut donc surcharger leurs clés. Les autres extensions lèvent une erreur.\n\nExample: Ressources d'un module\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nLe cache des ressources analysées, par nom.\n\nReturns: `Object`\n\nChaque valeur est un objet de clés et de valeurs. Il est vidé toutes les `default_interval_clear_resources` minutes, et pour un nom donné quand `LOADRESOURCE()` ou `F.register()` le modifie.\n\nExample: Vider le cache\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nRenvoie le chemin du répertoire des ressources ou d'un fichier qu'il contient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Le chemin absolu.\n\nExample: Chemin vers une ressource\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nLe répertoire des fichiers de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | Un chemin relatif à la racine de l'application. |\n\nExample: Un autre répertoire\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nTraduit les fichiers `.html` et `.htm` de `public/` avec `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Active la traduction des fichiers HTML statiques. |\n\nLes fichiers traduits sont mis en cache pour chaque langue en mode release.\n\nExample: La désactiver\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nLa fréquence, en minutes, à laquelle le cache des ressources est vidé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minutes. |\n\nAprès le vidage, les fichiers de ressources sont relus à la prochaine utilisation, les modifications apparaissent donc sans redémarrage. L'événement `clear` est émis avec `resources`.\n\nExample: Toutes les cinq minutes\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nLa ressource par défaut de chaque nouvel `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | Le nom de la ressource. |\n\nNon définie par défaut. Le framework fait tout de même passer les error builders à la langue de la requête avant de les envoyer.\n\nExample: Erreurs depuis errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nLe préfixe de clé par défaut de chaque nouvel `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | Le préfixe. |\n\nNon défini par défaut (un préfixe vide).\n\nExample: Clés préfixées\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nCrée `translate.resource` avec tous les textes à traduire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | Un répertoire, un fichier texte ou un texte. |\n\nSans argument, elle analyse le répertoire courant (sans `node_modules`, `tmp` et `.git`) : `@(Text)` dans les fichiers `.html`, `.js` et sitemap, et dans les `.js` également les clés de `$.invalid('key')` et `.error('key')`. Les textes sont regroupés sous des commentaires portant les noms des fichiers. `@(#key)` est ignoré. Avec un fichier texte, chaque ligne devient une entrée. Avec un texte qui n'est pas un fichier, elle affiche sa clé.\n\nExample: Créer le fichier\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nÉcrit les textes à traduire dans `translate.csv`.\n\nLe CSV a les colonnes `Hash;Text;Translation`. Remplis la dernière colonne, puis reconvertis-le avec `total4 csv`.\n\nExample: Exporter en CSV\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nCrée un fichier de ressources à partir d'un fichier CSV.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier CSV. |\n\nLit un CSV séparé par des `;`, ignore la première ligne, et utilise la première colonne comme clé et la deuxième comme valeur. Le fichier produit porte le même nom avec `.resource`.\n\nExample: Importer depuis un CSV\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nListe les clés à ajouter à une ressource et à en retirer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Le nouveau fichier, par exemple `translate.resource`. |\n| `target` | `String` | yes |  | Le fichier traduit. |\n\nCompare les clés des deux fichiers et écrit `<target>-diff.txt` avec les clés de `source` que la cible n'a pas et les clés de la cible que `source` n'a pas.\n\nExample: Trouver les nouveaux textes\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nCopie les valeurs d'une ressource dans une autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Le fichier contenant les nouvelles valeurs. |\n| `target` | `String` | yes |  | Le fichier à mettre à jour. |\n\nÉcrit `<target>-merged.txt` : les lignes de la cible, où la valeur de chaque clé est remplacée par celle de `source` quand elle en a une.\n\nExample: Fusionner des traductions\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nAligne les clés et les valeurs d'un fichier de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Le fichier de ressources. |\n\nÉcrit `<source>-cleaned.txt` avec toutes les clés complétées à la même largeur et ` : ` entre la clé et la valeur.\n\nExample: Nettoyer un fichier\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Localizzazione","summary":"File di risorse, funzioni di traduzione, il delegato di localizzazione e lo strumento di traduzione.","markdown":"---\ntitle: Localizzazione\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Localizzazione\n\n> File di risorse, funzioni di traduzione, il delegato di localizzazione e lo strumento di traduzione.\n\nFunzioni globali, delegati, proprietà, chiavi di configurazione, comandi delle viste e strumenti da riga di comando per file di risorse e traduzioni. La guida [Localizzazione](../../guides/localization/) spiega come funzionano insieme, con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nUn file di testo con righe `key : value` che contiene i testi di una lingua.\n\nIl nome del file senza `.resource` è il nome della risorsa, di solito una lingua (`en`, `sk`). `default.resource` è il fallback per tutte le lingue. Ogni riga contiene una chiave, ` : ` e un valore. Lascia uno spazio dopo i due punti, perché il parser salta il primo carattere dopo `:`. Le righe che iniziano con `//` o `#` sono commenti. Le chiavi `T` + hash sono traduzioni di `@(Text)` e vengono create da `total4 translate`. Una risorsa viene composta dai file registrati con `F.register()`, poi da `tmp/{name}.resource`, poi da `resources/{name}.resource`; una riga successiva con la stessa chiave prevale.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nLegge un valore da un file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Il nome della risorsa (nome del file senza `.resource`), di solito una lingua. |\n| `key` | `String` | yes |  | La chiave. |\n\nReturns: `String` Il valore, oppure una stringa vuota.\n\nCon un solo argomento legge da `default.resource`. Quando la chiave manca nella risorsa indicata, viene usato e messo in cache il valore di `default.resource`. Il risultato è una stringa vuota quando la chiave non esiste da nessuna parte. I file analizzati vengono messi in cache in `F.resources`.\n\nExample: Leggere valori\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nTraduce un testo allo stesso modo di `@(Text)` nelle viste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | Il nome della risorsa. |\n| `text` | `String` | yes |  | Il testo nella lingua predefinita, oppure `#key`. |\n\nReturns: `String` La traduzione o il testo originale.\n\nLa chiave è `T` più l'hash del testo. Quando non esiste una traduzione, viene restituito il testo originale. Un testo che inizia con `#` (non seguito da uno spazio) viene letto come chiave di risorsa, quindi `TRANSLATE('sk', '#title')` equivale a `RESOURCE('sk', 'title')`. Senza lingua viene usato `default.resource`.\n\nExample: Tradurre un messaggio\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nSostituisce ogni `@(...)` in una stringa con la sua traduzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Il nome della risorsa. |\n| `text` | `String` | yes |  | Una stringa con comandi `@(...)`. |\n\nReturns: `String` La stringa tradotta.\n\nUsa le stesse regole delle viste: `@(Text)` viene tradotto tramite hash, `@(#key)` viene letto dalla risorsa, le virgolette vengono escapate quando il comando è tra virgolette. Un testo con `@{notranslate}` viene restituito senza quel comando e senza traduzione. Quando la risorsa della lingua non esiste, i testi restano invariati.\n\nExample: Tradurre un template\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nScrive una risorsa nella directory temporanea e ne svuota la cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della risorsa, oppure un URL che restituisce più risorse. |\n| `value` | `String|Object|Array` | no |  | Il contenuto, un oggetto, un array o un URL `http(s)`. |\n\n`value` può essere il contenuto di un file di risorse (una stringa), un oggetto `{ key: value }` o un array di elementi con `id`/`key`/`code`/`language` e `value`/`name`/`text`/`body`. Il risultato viene salvato come `tmp/{name}.resource` e unito a `resources/{name}.resource`, che prevale per le chiavi duplicate. `LOADRESOURCE(name, url)` scarica una risorsa; `LOADRESOURCE(url)` scarica un oggetto o un array di più risorse. Gli errori di download vengono sollevati come eccezioni.\n\nExample: Caricare da un oggetto\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Scaricare da un URL\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nImposta il delegato che restituisce la lingua di ogni richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)` che restituisce una stringa con la lingua. |\n\nLa funzione viene salvata come `DEF.onLocale`. Riceve `req`, `res` e, per i file statici, `true`. Deve restituire la lingua, che viene salvata in `req.$language`. Per le connessioni WebSocket riceve solo `req`.\n\nExample: Lingua dalla query o dall'header\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nServe i file statici di un URL tradotti nella lingua della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL, per esempio `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | Estensioni dei file (`.md`) e `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifica l'HTML. |\n\nCrea una route di file che legge il file, sostituisce `@(...)` e lo restituisce. Senza estensione nell'URL gestisce `.html`, `.htm`, `.md` e `.txt`. L'HTML viene minificato a meno che `minify` sia `false` o `flags` contenga `nocompress`. In modalità release il risultato viene messo in cache per ogni lingua. Un URL che inizia con `#` viene preso dalla sitemap.\n\nExample: Markdown localizzato\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nIl delegato che restituisce la lingua di una richiesta; `null` per impostazione predefinita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `res` | `Response` | no |  | La risposta. |\n| `isStaticFile` | `Boolean` | no |  | `true` per i file statici. |\n\nReturns: `String` La lingua, salvata in `req.$language`.\n\nImpostalo con `LOCALIZE(fn)` o direttamente. Viene chiamato all'inizio di una richiesta di file statico, dopo l'autorizzazione per le route (quindi `req.user` è noto) e quando si connette un WebSocket (solo con `req`). `req.localize()` lo richiama.\n\nExample: Lingua dell'utente\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nOpzione della sessione integrata di `AUTH()` che imposta la lingua a partire dall'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | I dati dell'utente da `onread`, oppure `null`. |\n| `req` | `Request` | yes |  | La richiesta. |\n\nReturns: `String` La lingua.\n\nViene chiamata dopo la lettura della sessione, con i dati dell'utente (o `null` quando la sessione manca o non è valida) e la richiesta. Il valore restituito viene salvato in `req.$language`.\n\nExample: Lingua dall'utente\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nLa lingua del controller; la usano viste ed e-mail.\n\nReturns: `String`\n\nViene impostata da `req.$language` quando il controller viene creato, quindi è `undefined` senza un delegato di localizzazione. Puoi assegnare un altro valore prima di fare il render di una vista. Le viste vengono compilate e messe in cache per ogni lingua. `client.language` nei controller WebSocket funziona allo stesso modo.\n\nExample: Lingua dall'URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nLa lingua della richiesta.\n\nReturns: `String`\n\nRestituisce `req.$language`. Quando non è impostata, restituisce la prima lingua dell'header `Accept-Language` in minuscolo (per esempio `en-us`) e la conserva. Può essere assegnata.\n\nExample: Leggere la lingua\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nEsegue di nuovo `DEF.onLocale` e restituisce la nuova lingua.\n\nReturns: `String` La lingua.\n\nUtile quando qualcosa che il delegato legge (un cookie, l'utente) è cambiato durante la richiesta.\n\nExample: Aggiornare la lingua\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nLa lingua della richiesta in schemi, operazioni, middleware e `AUTH()`.\n\nReturns: `String`\n\nIn schemi e operazioni è `controller.language` (una stringa vuota senza controller). Nei middleware è `req.$language`. In un delegato `AUTH()` è `req.language`, che ripiega su `Accept-Language`, perché il delegato di localizzazione viene eseguito dopo l'autorizzazione.\n\nExample: Usarla in uno schema\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nContrassegna il testo da tradurre nelle viste e nei file HTML statici.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Il testo nella lingua predefinita, oppure `#key`. |\n\nIl testo viene sostituito con la traduzione dalla risorsa della lingua corrente quando la vista viene compilata. La chiave è `T` più un hash del testo; quando non c'è traduzione, o il file di risorse della lingua non esiste, resta il testo originale. `@(#key)` legge una chiave direttamente dalla risorsa. Tra virgolette, le virgolette nella traduzione vengono escapate.\n\nExample: Testo tradotto\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nStampa in una vista un valore da un file di risorse, codificato in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Il nome della risorsa. |\n| `key` | `String` | yes |  | La chiave. |\n\nReturns: `String` Il valore, oppure una stringa vuota.\n\nChiama `RESOURCE()`, quindi senza `name` legge `default.resource`. Usa la variabile di vista `language` per leggere la risorsa della lingua corrente. `@{!resource(...)}` stampa il valore senza codifica.\n\nExample: Valori di risorsa\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nLa lingua della richiesta all'interno di una vista.\n\nLa variabile di vista `language` contiene `req.$language`, oppure una stringa vuota. Usala nelle espressioni, per esempio in `@{resource(language, 'key')}` o nell'attributo `lang`.\n\nExample: L'attributo lang\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nDisattiva la traduzione di `@(...)` in una vista.\n\nMettilo in qualsiasi punto della vista o in una stringa passata a `TRANSLATOR()`. Viene rimosso dall'output e i comandi `@(...)` restano intatti. `@{nolocalize}` fa la stessa cosa.\n\nExample: Una vista senza traduzione\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nInvia un'e-mail renderizzata da una vista, in una lingua indicata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Il destinatario o i destinatari. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `view` | `String` | yes |  | Il nome della vista. |\n| `model` | `Object` | no |  | Il modello della vista. |\n| `language` | `String` | no |  | La lingua. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Il messaggio.\n\nCon una lingua, l'oggetto viene tradotto (con `TRANSLATOR()` quando contiene `@(`, altrimenti con `TRANSLATE()`) e la vista viene renderizzata in quella lingua. `language` e `callback` possono essere scambiati.\n\nExample: Un'e-mail tradotta\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nInvia un'e-mail HTML grezza, tradotta in una lingua indicata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Il destinatario o i destinatari. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `body` | `String` | yes |  | Il corpo HTML. |\n| `language` | `String` | no |  | La lingua. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Il messaggio.\n\nCon una lingua, l'oggetto viene tradotto e ogni `@(...)` nel corpo viene sostituito. `language` e `callback` possono essere scambiati.\n\nExample: Un'e-mail HTML tradotta\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nEsegue il render di una vista in una stringa, eventualmente in una lingua indicata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della vista. |\n| `model` | `Object` | no |  | Il modello. |\n| `layout` | `String` | no |  | Il layout. |\n| `repository` | `Object` | no |  | Il repository. |\n| `language` | `String` | no |  | La lingua. |\n\nReturns: `String` L'HTML.\n\nLa lingua viene usata per `@(...)` nella vista. Senza di essa la vista viene tradotta con `default.resource`.\n\nExample: Render in slovacco\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nFormatta una data; i nomi di mesi e giorni vengono letti da una risorsa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Il formato, per esempio `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | La risorsa con i nomi dei mesi e dei giorni. |\n\nReturns: `String` La data formattata.\n\n`MMMM` e `MMM` leggono il nome inglese del mese (`January`…`December`) come chiave dalla risorsa, `dddd` e `ddd` il nome del giorno (`Sunday`…`Saturday`). Quando una chiave manca, viene usato il nome inglese.\n\nExample: Nomi localizzati\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nImposta la risorsa e il prefisso delle chiavi per i messaggi di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della risorsa. |\n| `prefix` | `String` | no | `''` | Un prefisso per le chiavi. |\n\nReturns: `ErrorBuilder` Il builder.\n\nGli errori aggiunti con una chiave (`builder.push('email')`) vengono letti come `prefix + name` dalla risorsa. Il builder mantiene poi questa risorsa e non passa alla lingua della richiesta.\n\nExample: Errori da una risorsa\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nImposta solo la risorsa per i messaggi di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della risorsa. |\n\nReturns: `ErrorBuilder` Il builder.\n\nIl framework la chiama con la lingua della richiesta prima di inviare gli errori, a meno che tu non abbia impostato una risorsa.\n\nExample: Lingua fissa\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nImposta il prefisso delle chiavi per i messaggi di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Il prefisso. |\n\nReturns: `ErrorBuilder` Il builder.\n\nUn errore aggiunto con un nome viene letto come `prefix + name` dalla risorsa.\n\nExample: Un prefisso\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nLegge gli errori di uno schema da una risorsa fissa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della risorsa. |\n\nReturns: `SchemaBuilderEntity` Lo schema.\n\nSenza di esso, gli errori dello schema vengono tradotti con la lingua della richiesta.\n\nExample: Errori da errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nImposta un prefisso per le chiavi di risorsa degli errori dello schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Il prefisso. |\n\nReturns: `SchemaBuilderEntity` Lo schema.\n\nUn campo `email` obbligatorio o non valido viene letto come `prefix + 'email'` dalla risorsa.\n\nExample: Chiavi con prefisso\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nAggiunge a una risorsa un file `.resource` da un'altra posizione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Il percorso di un file `.resource`. |\n\nIl nome del file dà il nome della risorsa, quindi `/modules/shop/sk.resource` viene aggiunto alla risorsa `sk`. Un percorso che inizia con `@` si trova in un pacchetto, con `=` in un tema. I file registrati vengono letti prima di `tmp/` e `resources/`, quindi l'applicazione può sovrascriverne le chiavi. Altre estensioni sollevano un errore.\n\nExample: Risorse di un modulo\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nLa cache delle risorse analizzate, per nome.\n\nReturns: `Object`\n\nOgni valore è un oggetto di chiavi e valori. Viene svuotata ogni `default_interval_clear_resources` minuti, e per un singolo nome quando `LOADRESOURCE()` o `F.register()` lo modificano.\n\nExample: Svuotare la cache\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nRestituisce il percorso della directory delle risorse o di un file al suo interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Il percorso assoluto.\n\nExample: Percorso di una risorsa\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nLa directory con i file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | Un percorso relativo alla radice dell'applicazione. |\n\nExample: Un'altra directory\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nTraduce i file `.html` e `.htm` di `public/` con `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Abilita la traduzione dei file HTML statici. |\n\nI file tradotti vengono messi in cache per ogni lingua in modalità release.\n\nExample: Disattivarla\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nOgni quanti minuti viene svuotata la cache delle risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minuti. |\n\nDopo lo svuotamento, i file di risorse vengono riletti al successivo utilizzo, quindi le modifiche compaiono senza un riavvio. Viene emesso l'evento `clear` con `resources`.\n\nExample: Ogni cinque minuti\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nLa risorsa predefinita di ogni nuovo `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | Il nome della risorsa. |\n\nNon impostata per impostazione predefinita. Il framework fa comunque passare gli error builder alla lingua della richiesta prima di inviarli.\n\nExample: Errori da errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nIl prefisso di chiave predefinito di ogni nuovo `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | Il prefisso. |\n\nNon impostato per impostazione predefinita (un prefisso vuoto).\n\nExample: Chiavi con prefisso\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nCrea `translate.resource` con tutti i testi da tradurre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | Una directory, un file di testo o un testo. |\n\nSenza argomenti analizza la directory corrente (senza `node_modules`, `tmp` e `.git`): `@(Text)` nei file `.html`, `.js` e della sitemap, e nei `.js` anche le chiavi di `$.invalid('key')` e `.error('key')`. I testi vengono raggruppati sotto commenti con i nomi dei file. `@(#key)` viene saltato. Con un file di testo, ogni riga diventa una voce. Con un testo che non è un file, ne stampa la chiave.\n\nExample: Creare il file\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nScrive i testi da tradurre in `translate.csv`.\n\nIl CSV ha le colonne `Hash;Text;Translation`. Compila l'ultima colonna, poi riconvertilo con `total4 csv`.\n\nExample: Esportare in CSV\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nCrea un file di risorse da un file CSV.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file CSV. |\n\nLegge un CSV separato da `;`, salta la prima riga e usa la prima colonna come chiave e la seconda come valore. L'output ha lo stesso nome con `.resource`.\n\nExample: Importare da CSV\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nElenca le chiavi da aggiungere e da rimuovere in una risorsa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Il nuovo file, per esempio `translate.resource`. |\n| `target` | `String` | yes |  | Il file tradotto. |\n\nConfronta le chiavi dei due file e scrive `<target>-diff.txt` con le chiavi di `source` che il file di destinazione non ha e le chiavi del file di destinazione che `source` non ha.\n\nExample: Trovare i nuovi testi\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nCopia i valori da una risorsa a un'altra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Il file con i nuovi valori. |\n| `target` | `String` | yes |  | Il file da aggiornare. |\n\nScrive `<target>-merged.txt`: le righe del file di destinazione, con il valore di ogni chiave sostituito dal valore di `source` quando questo ne ha uno.\n\nExample: Unire le traduzioni\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nAllinea le chiavi e i valori di un file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Il file di risorse. |\n\nScrive `<source>-cleaned.txt` con tutte le chiavi riempite fino alla stessa larghezza e ` : ` tra chiave e valore.\n\nExample: Pulire un file\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZSS62j61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/localization/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Lokalizácia","summary":"Súbory zdrojov, prekladové funkcie, lokalizačný delegát a nástroj na preklad.","markdown":"---\ntitle: \"Lokalizácia\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/localization/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Lokalizácia\n\n> Súbory zdrojov, prekladové funkcie, lokalizačný delegát a nástroj na preklad.\n\nGlobálne funkcie, delegáti, vlastnosti, konfiguračné kľúče, príkazy view a nástroje príkazového riadka pre súbory zdrojov a preklady. Návod [Lokalizácia](../../guides/localization/) vysvetľuje, ako spolu fungujú, s príkladmi; táto stránka je presná referencia.\n\n## API\n\n### resources/{name}.resource\n\nType: `type`\n\nTextový súbor s riadkami `key : value`, ktorý obsahuje texty jedného jazyka.\n\nNázov súboru bez `.resource` je názov zdroja, zvyčajne jazyk (`en`, `sk`). `default.resource` je záloha pre všetky jazyky. Každý riadok obsahuje kľúč, ` : ` a hodnotu. Za dvojbodkou nechaj medzeru, pretože parser preskočí prvý znak za `:`. Riadky, ktoré začínajú `//` alebo `#`, sú komentáre. Kľúče `T` + hash sú preklady `@(Text)` a vytvára ich `total4 translate`. Zdroj sa spája zo súborov zaregistrovaných cez `F.register()`, potom `tmp/{name}.resource`, potom `resources/{name}.resource`; neskorší riadok s rovnakým kľúčom vyhráva.\n\nExample: resources/sk.resource\n```text\n// Slovak texts\ntitle                : Moja stránka\nerror-email          : Zadajte platnú e-mailovú adresu\n```\n\n### RESOURCE([name], key)\n\nType: `method`\n\nPrečíta hodnotu zo súboru zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Názov zdroja (názov súboru bez `.resource`), zvyčajne jazyk. |\n| `key` | `String` | yes |  | Kľúč. |\n\nReturns: `String` Hodnota, alebo prázdny reťazec.\n\nS jedným argumentom číta z `default.resource`. Keď kľúč v pomenovanom zdroji chýba, použije sa hodnota z `default.resource` a uloží sa do cache. Výsledkom je prázdny reťazec, keď kľúč neexistuje nikde. Spracované súbory sú v cache v `F.resources`.\n\nExample: Čítanie hodnôt\n```js\nvar title = RESOURCE('sk', 'title');\nvar fallback = RESOURCE('title'); // default.resource\n```\n\n### TRANSLATE([language], text)\n\nType: `method`\n\nPreloží jeden text rovnako ako `@(Text)` vo view.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | no | `default` | Názov zdroja. |\n| `text` | `String` | yes |  | Text v predvolenom jazyku, alebo `#key`. |\n\nReturns: `String` Preklad alebo pôvodný text.\n\nKľúč je `T` plus hash textu. Keď preklad neexistuje, vráti sa pôvodný text. Text, ktorý začína `#` (bez medzery za ním), sa číta ako kľúč zdroja, takže `TRANSLATE('sk', '#title')` je `RESOURCE('sk', 'title')`. Bez jazyka sa použije `default.resource`.\n\nExample: Preklad správy\n```js\nvar msg = TRANSLATE($.language, 'Thank you for your order');\n```\n\n### TRANSLATOR(language, text)\n\nType: `method`\n\nNahradí každý `@(...)` v reťazci jeho prekladom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Názov zdroja. |\n| `text` | `String` | yes |  | Reťazec s príkazmi `@(...)`. |\n\nReturns: `String` Preložený reťazec.\n\nPoužíva rovnaké pravidlá ako view: `@(Text)` sa prekladá podľa hashu, `@(#key)` sa číta zo zdroja, úvodzovky sa escapujú, keď je príkaz v úvodzovkách. Text s `@{notranslate}` sa vráti bez tohto príkazu a bez prekladu. Keď zdroj jazyka neexistuje, texty zostanú.\n\nExample: Preklad šablóny\n```js\nvar html = TRANSLATOR('sk', '<h1>@(Products)</h1><p>@(#welcome)</p>');\n```\n\n### LOADRESOURCE(name, value)\n\nType: `method`\n\nZapíše zdroj do dočasného adresára a vymaže jeho cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov zdroja, alebo URL, ktorá vracia viac zdrojov. |\n| `value` | `String|Object|Array` | no |  | Obsah, objekt, pole alebo `http(s)` URL. |\n\n`value` môže byť obsah súboru zdroja (reťazec), objekt `{ key: value }` alebo pole položiek s `id`/`key`/`code`/`language` a `value`/`name`/`text`/`body`. Výsledok sa uloží ako `tmp/{name}.resource` a spojí sa s `resources/{name}.resource`, ktorý pri duplicitných kľúčoch vyhráva. `LOADRESOURCE(name, url)` stiahne jeden zdroj; `LOADRESOURCE(url)` stiahne objekt alebo pole viacerých zdrojov. Chyby sťahovania sa vyhadzujú.\n\nExample: Načítanie z objektu\n```js\nLOADRESOURCE('sk', { title: 'Moja stránka', welcome: 'Vitajte' });\n```\n\nExample: Stiahnutie z URL\n```js\nLOADRESOURCE('sk', 'https://example.com/translations/sk.json');\nLOADRESOURCE('https://example.com/translations/');\n```\n\n### LOCALIZE(fn)\n\nType: `method`\n\nNastaví delegáta, ktorý vracia jazyk každej požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(req, res, isStaticFile)`, ktorá vráti reťazec jazyka. |\n\nFunkcia sa uloží ako `DEF.onLocale`. Dostane `req`, `res` a pri statických súboroch `true`. Musí vrátiť jazyk, ktorý sa uloží do `req.$language`. Pri WebSocket spojeniach dostane iba `req`.\n\nExample: Jazyk z query alebo z hlavičky\n```js\nLOCALIZE(function(req, res) {\n\tvar lang = req.query.language || (req.headers['accept-language'] || '').substring(0, 2);\n\treturn lang === 'sk' ? 'sk' : 'en';\n});\n```\n\n### LOCALIZE(url, [flags], [minify])\n\nType: `method`\n\nPoskytuje statické súbory URL preložené do jazyka požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL, napríklad `/docs/*.md`. |\n| `flags` | `Array` | no | `[]` | Prípony súborov (`.md`) a `nocompress`. |\n| `minify` | `Boolean` | no | `true` | Minifikuje HTML. |\n\nVytvorí súborovú routu, ktorá prečíta súbor, nahradí `@(...)` a vráti ho. Bez prípony v URL spracuje `.html`, `.htm`, `.md` a `.txt`. HTML sa minifikuje, pokiaľ `minify` nie je `false` alebo `flags` neobsahuje `nocompress`. V release režime sa výsledok ukladá do cache pre každý jazyk. URL, ktorá začína `#`, sa vezme zo sitemap.\n\nExample: Lokalizovaný Markdown\n```js\nLOCALIZE('/docs/*.md');\nLOCALIZE('/templates/*.html', ['nocompress']);\n```\n\n### DEF.onLocale = function(req, res, isStaticFile)\n\nType: `delegate`\n\nDelegát, ktorý vracia jazyk požiadavky; predvolene `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `res` | `Response` | no |  | Odpoveď. |\n| `isStaticFile` | `Boolean` | no |  | `true` pre statické súbory. |\n\nReturns: `String` Jazyk, uložený do `req.$language`.\n\nNastav ho cez `LOCALIZE(fn)` alebo priamo. Volá sa na začiatku požiadavky na statický súbor, pri routách po autorizácii (takže `req.user` je známy) a pri pripojení WebSocketu (iba s `req`). `req.localize()` ho zavolá znova.\n\nExample: Jazyk používateľa\n```js\nDEF.onLocale = function(req) {\n\treturn req.user ? req.user.language : 'en';\n};\n```\n\n### AUTH({ locale: function(user, req) })\n\nType: `config` · Since: `0.0.57`\n\nVoľba vstavanej session `AUTH()`, ktorá nastaví jazyk podľa používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `Object` | yes |  | Údaje používateľa z `onread`, alebo `null`. |\n| `req` | `Request` | yes |  | Požiadavka. |\n\nReturns: `String` Jazyk.\n\nVolá sa po prečítaní session, s údajmi používateľa (alebo `null`, keď session chýba alebo je neplatná) a s požiadavkou. Vrátená hodnota sa uloží do `req.$language`.\n\nExample: Jazyk od používateľa\n```js\nAUTH({\n\tsecret: 'my-secret',\n\tcookie: 'session',\n\tonread: function(meta, next) {\n\t\tNOSQL('users').one().id(meta.userid).callback(next);\n\t},\n\tlocale: function(user, req) {\n\t\treturn user ? user.language : 'en';\n\t}\n});\n```\n\n### controller.language\n\nType: `property`\n\nJazyk kontroléra; používajú ho view a e-maily.\n\nReturns: `String`\n\nNastaví sa z `req.$language` pri vytvorení kontroléra, takže bez lokalizačného delegáta je `undefined`. Pred vykreslením view mu môžeš priradiť inú hodnotu. View sa kompilujú a ukladajú do cache pre každý jazyk. `client.language` vo WebSocket kontroléroch funguje rovnako.\n\nExample: Jazyk z URL\n```js\nexports.install = function() {\n\tROUTE('GET /{lang}/', home);\n};\n\nfunction home(lang) {\n\tthis.language = lang;\n\tthis.view('index');\n}\n```\n\n### req.language\n\nType: `property`\n\nJazyk požiadavky.\n\nReturns: `String`\n\nVracia `req.$language`. Keď nie je nastavený, vráti prvý jazyk z hlavičky `Accept-Language` malými písmenami (napríklad `en-us`) a ponechá si ho. Dá sa priradiť.\n\nExample: Čítanie jazyka\n```js\nfunction detail() {\n\tvar lang = this.req.language;\n\tthis.plain(lang);\n}\n```\n\n### req.localize()\n\nType: `method`\n\nZnova spustí `DEF.onLocale` a vráti nový jazyk.\n\nReturns: `String` Jazyk.\n\nUžitočné, keď sa počas požiadavky zmenilo niečo, čo delegát číta (cookie, používateľ).\n\nExample: Obnovenie jazyka\n```js\nfunction setlanguage() {\n\tthis.req.user.language = this.query.lang;\n\tthis.language = this.req.localize();\n\tthis.redirect('/');\n}\n```\n\n### $.language\n\nType: `property`\n\nJazyk požiadavky v schémach, operáciách, middleware a `AUTH()`.\n\nReturns: `String`\n\nV schémach a operáciách je to `controller.language` (prázdny reťazec bez kontroléra). V middleware je to `req.$language`. V delegátovi `AUTH()` je to `req.language`, ktorý sa vracia k `Accept-Language`, pretože lokalizačný delegát beží po autorizácii.\n\nExample: Použitie v schéme\n```js\nschema.addWorkflow('send', function($) {\n\tvar subject = TRANSLATE($.language, 'Your message was received');\n\t$.success(subject);\n});\n```\n\n### @(Text)\n\nType: `method`\n\nOznačí text na preklad vo view a statických HTML súboroch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `Text` | `String` | yes |  | Text v predvolenom jazyku, alebo `#key`. |\n\nText sa pri kompilácii view nahradí prekladom zo zdroja aktuálneho jazyka. Kľúč je `T` plus hash textu; keď preklad neexistuje alebo súbor zdroja jazyka neexistuje, zostane pôvodný text. `@(#key)` prečíta kľúč priamo zo zdroja. V úvodzovkách sa úvodzovky v preklade escapujú.\n\nExample: Preložený text\n```html\n<h1>@(Products)</h1>\n<button title=\"@(Add to cart)\">@(Add)</button>\n<p>@(#welcome)</p>\n```\n\n### @{resource([name], key)}\n\nType: `method`\n\nVypíše vo view hodnotu zo súboru zdroja, zakódovanú pre HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `default` | Názov zdroja. |\n| `key` | `String` | yes |  | Kľúč. |\n\nReturns: `String` Hodnota, alebo prázdny reťazec.\n\nVolá `RESOURCE()`, takže bez `name` číta `default.resource`. Použi premennú view `language`, aby si čítal zdroj aktuálneho jazyka. `@{!resource(...)}` vypíše hodnotu nespracovanú.\n\nExample: Hodnoty zdroja\n```html\n<p>@{resource('welcome')}</p>\n<p>@{resource(language, 'welcome')}</p>\n```\n\n### @{language}\n\nType: `property`\n\nJazyk požiadavky vo view.\n\nPremenná view `language` obsahuje `req.$language`, alebo prázdny reťazec. Použi ju vo výrazoch, napríklad v `@{resource(language, 'key')}` alebo v atribúte `lang`.\n\nExample: Atribút lang\n```html\n<html lang=\"@{language}\">\n```\n\n### @{notranslate}\n\nType: `method`\n\nVypne preklad `@(...)` vo view.\n\nVlož ho kamkoľvek do view alebo do reťazca odovzdaného `TRANSLATOR()`. Z výstupu sa odstráni a príkazy `@(...)` zostanú nedotknuté. `@{nolocalize}` robí to isté.\n\nExample: View bez prekladu\n```html\n@{notranslate}\n<p>@(This text stays as it is)</p>\n```\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nPošle e-mail vykreslený z view, v danom jazyku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Príjemca alebo príjemcovia. |\n| `subject` | `String` | yes |  | Predmet. |\n| `view` | `String` | yes |  | Názov view. |\n| `model` | `Object` | no |  | Model view. |\n| `language` | `String` | no |  | Jazyk. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Správa.\n\nS jazykom sa preloží predmet (cez `TRANSLATOR()`, keď obsahuje `@(`, inak cez `TRANSLATE()`) a view sa vykreslí v tomto jazyku. `language` a `callback` sa dajú vymeniť.\n\nExample: Preložený e-mail\n```js\nMAIL(user.email, '@(Order confirmation)', 'mails/order', order, user.language, function(err) {\n\terr && console.log(err);\n});\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method` · Since: `0.0.37`\n\nPošle surový HTML e-mail preložený do daného jazyka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Príjemca alebo príjemcovia. |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | HTML telo. |\n| `language` | `String` | no |  | Jazyk. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `MailMessage` Správa.\n\nS jazykom sa preloží predmet a nahradí sa každý `@(...)` v tele. `language` a `callback` sa dajú vymeniť.\n\nExample: Preložený HTML e-mail\n```js\nHTMLMAIL(user.email, '@(Welcome)', '<p>@(Thank you for signing up.)</p>', 'sk');\n```\n\n### VIEW(name, [model], [layout], [repository], [language])\n\nType: `method`\n\nVykreslí view do reťazca, voliteľne v danom jazyku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov view. |\n| `model` | `Object` | no |  | Model. |\n| `layout` | `String` | no |  | Layout. |\n| `repository` | `Object` | no |  | Repozitár. |\n| `language` | `String` | no |  | Jazyk. |\n\nReturns: `String` HTML.\n\nJazyk sa použije pre `@(...)` vo view. Bez neho sa view preloží pomocou `default.resource`.\n\nExample: Vykreslenie v slovenčine\n```js\nvar html = VIEW('mails/invoice', invoice, '', null, 'sk');\n```\n\n### date.format([format], [resource])\n\nType: `method`\n\nNaformátuje dátum; názvy mesiacov a dní sa čítajú zo zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Formát, napríklad `dddd d. MMMM yyyy`. |\n| `resource` | `String` | no | `default` | Zdroj s názvami mesiacov a dní. |\n\nReturns: `String` Naformátovaný dátum.\n\n`MMMM` a `MMM` čítajú anglický názov mesiaca (`January`…`December`) ako kľúč zo zdroja, `dddd` a `ddd` názov dňa (`Sunday`…`Saturday`). Keď kľúč chýba, použije sa anglický názov.\n\nExample: Lokalizované názvy\n```js\n// sk.resource: January : január, Monday : pondelok\nvar text = NOW.format('dddd d. MMMM yyyy', 'sk');\n```\n\n### builder.resource(name, [prefix])\n\nType: `method`\n\nNastaví zdroj a prefix kľúčov pre chybové hlásenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov zdroja. |\n| `prefix` | `String` | no | `''` | Prefix pre kľúče. |\n\nReturns: `ErrorBuilder` Builder.\n\nChyby pridané s kľúčom (`builder.push('email')`) sa čítajú zo zdroja ako `prefix + name`. Builder si potom tento zdroj ponechá a neprepne sa na jazyk požiadavky.\n\nExample: Chyby zo zdroja\n```js\nvar builder = new ErrorBuilder();\nbuilder.resource('sk', 'error-');\nbuilder.push('email'); // reads error-email from sk.resource\n```\n\n### builder.setResource(name)\n\nType: `method`\n\nNastaví iba zdroj pre chybové hlásenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov zdroja. |\n\nReturns: `ErrorBuilder` Builder.\n\nFramework ho volá s jazykom požiadavky pred odoslaním chýb, pokiaľ si zdroj nenastavil sám.\n\nExample: Pevný jazyk\n```js\nvar builder = new ErrorBuilder();\nbuilder.setResource('de');\n```\n\n### builder.setPrefix(prefix)\n\nType: `method`\n\nNastaví prefix kľúčov pre chybové hlásenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Prefix. |\n\nReturns: `ErrorBuilder` Builder.\n\nChyba pridaná s názvom sa číta zo zdroja ako `prefix + name`.\n\nExample: Prefix\n```js\nvar builder = new ErrorBuilder();\nbuilder.setPrefix('error-');\nbuilder.push('name');\n```\n\n### schema.setResource(name)\n\nType: `method`\n\nČíta chyby schémy z pevného zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov zdroja. |\n\nReturns: `SchemaBuilderEntity` Schéma.\n\nBez toho sa chyby schémy prekladajú do jazyka požiadavky.\n\nExample: Chyby z errors.resource\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setResource('errors');\n\tschema.define('email', 'Email', true);\n});\n```\n\n### schema.setPrefix(prefix)\n\nType: `method`\n\nNastaví prefix pre kľúče zdroja pre chyby schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Prefix. |\n\nReturns: `SchemaBuilderEntity` Schéma.\n\nPovinné alebo neplatné pole `email` sa číta zo zdroja ako `prefix + 'email'`.\n\nExample: Kľúče s prefixom\n```js\nNEWSCHEMA('Contact', function(schema) {\n\tschema.setPrefix('contact-');\n\tschema.define('email', 'Email', true); // key: contact-email\n});\n```\n\n### F.register(path)\n\nType: `method`\n\nPridá do zdroja súbor `.resource` z iného umiestnenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta k súboru `.resource`. |\n\nNázov súboru určuje názov zdroja, takže `/modules/shop/sk.resource` sa pridá do zdroja `sk`. Cesta, ktorá začína `@`, je v balíku, `=` v téme. Zaregistrované súbory sa čítajú pred `tmp/` a `resources/`, takže aplikácia môže prepísať ich kľúče. Iné prípony vyhodia chybu.\n\nExample: Zdroje modulu\n```js\nF.register(PATH.root('modules/shop/sk.resource'));\n```\n\n### F.resources\n\nType: `property`\n\nCache spracovaných zdrojov podľa názvu.\n\nReturns: `Object`\n\nKaždá hodnota je objekt kľúčov a hodnôt. Maže sa každých `default_interval_clear_resources` minút a pre jeden názov vtedy, keď ho zmení `LOADRESOURCE()` alebo `F.register()`.\n\nExample: Vymazanie cache\n```js\nF.resources = {};\n```\n\n### PATH.resources([filename])\n\nType: `method`\n\nVráti cestu k adresáru zdrojov alebo k súboru v ňom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nExample: Cesta k zdroju\n```js\nvar filename = PATH.resources('sk.resource');\n```\n\n### directory_resources : /resources/\n\nType: `config`\n\nAdresár so súbormi zdrojov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory_resources` | `String` | no | `/resources/` | Cesta relatívna ku koreňu aplikácie. |\n\nExample: Iný adresár\n```text\ndirectory_resources     : /translations/\n```\n\n### allow_localize : true\n\nType: `config`\n\nPrekladá súbory `.html` a `.htm` z `public/` s `@(...)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `allow_localize` | `Boolean` | no | `true` | Zapne preklad statických HTML súborov. |\n\nPreložené súbory sa v release režime ukladajú do cache pre každý jazyk.\n\nExample: Vypnutie\n```text\nallow_localize          : false\n```\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nAko často, v minútach, sa maže cache zdrojov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_interval_clear_resources` | `Number` | no | `20` | Minúty. |\n\nPo vymazaní sa súbory zdrojov pri ďalšom použití načítajú znova, takže zmeny sa prejavia bez reštartu. Vyvolá sa udalosť `clear` s `resources`.\n\nExample: Každých päť minút\n```text\ndefault_interval_clear_resources : 5\n```\n\n### default_errorbuilder_resource_name : name\n\nType: `config`\n\nPredvolený zdroj každého nového `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_name` | `String` | no |  | Názov zdroja. |\n\nPredvolene nie je nastavený. Framework aj tak prepne error buildery na jazyk požiadavky pred ich odoslaním.\n\nExample: Chyby z errors.resource\n```text\ndefault_errorbuilder_resource_name : errors\n```\n\n### default_errorbuilder_resource_prefix : prefix\n\nType: `config`\n\nPredvolený prefix kľúčov každého nového `ErrorBuilder`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `default_errorbuilder_resource_prefix` | `String` | no | `''` | Prefix. |\n\nPredvolene nie je nastavený (prázdny prefix).\n\nExample: Kľúče s prefixom\n```text\ndefault_errorbuilder_resource_prefix : error-\n```\n\n### total4 translate [path | \"text\" | filename]\n\nType: `method`\n\nVytvorí `translate.resource` so všetkými textami na preklad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `argument` | `String` | no |  | Adresár, textový súbor alebo text. |\n\nBez argumentu prehľadá aktuálny adresár (bez `node_modules`, `tmp` a `.git`): `@(Text)` v súboroch `.html`, `.js` a sitemap, a v `.js` aj kľúče `$.invalid('key')` a `.error('key')`. Texty sú zoskupené pod komentármi s názvami súborov. `@(#key)` sa preskočí. S textovým súborom sa každý riadok stane jednou položkou. S textom, ktorý nie je súborom, vypíše jeho kľúč.\n\nExample: Vytvorenie súboru\n```bash\ntotal4 translate\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translatecsv\n\nType: `method`\n\nZapíše texty na preklad do `translate.csv`.\n\nCSV má stĺpce `Hash;Text;Translation`. Vyplň posledný stĺpec a potom ho preveď späť cez `total4 csv`.\n\nExample: Export do CSV\n```bash\ntotal4 translatecsv\n```\n\n### total4 csv <filename>\n\nType: `method`\n\nVytvorí súbor zdroja zo súboru CSV.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor CSV. |\n\nPrečíta CSV oddelené `;`, preskočí prvý riadok a prvý stĺpec použije ako kľúč a druhý ako hodnotu. Výstup má rovnaký názov s `.resource`.\n\nExample: Import z CSV\n```bash\ntotal4 csv sk.csv\n```\n\n### total4 diff <source> <target>\n\nType: `method`\n\nVypíše kľúče, ktoré treba do zdroja pridať a zo zdroja odstrániť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Nový súbor, napríklad `translate.resource`. |\n| `target` | `String` | yes |  | Preložený súbor. |\n\nPorovná kľúče oboch súborov a zapíše `<target>-diff.txt` s kľúčmi zo `source`, ktoré cieľ nemá, a s kľúčmi cieľa, ktoré `source` nemá.\n\nExample: Nájdenie nových textov\n```bash\ntotal4 diff translate.resource resources/sk.resource\n```\n\n### total4 merge <source> <target>\n\nType: `method`\n\nSkopíruje hodnoty z jedného zdroja do druhého.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Súbor s novými hodnotami. |\n| `target` | `String` | yes |  | Súbor na aktualizáciu. |\n\nZapíše `<target>-merged.txt`: riadky cieľa, kde hodnota každého kľúča je nahradená hodnotou zo `source`, ak ju má.\n\nExample: Zlúčenie prekladov\n```bash\ntotal4 merge translated.resource resources/sk.resource\n```\n\n### total4 clean <source>\n\nType: `method`\n\nZarovná kľúče a hodnoty súboru zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Súbor zdroja. |\n\nZapíše `<source>-cleaned.txt` so všetkými kľúčmi doplnenými na rovnakú šírku a s ` : ` medzi kľúčom a hodnotou.\n\nExample: Vyčistenie súboru\n```bash\ntotal4 clean resources/sk.resource\n```\n","entries":[{"type":"type","name":"Resource file","signature":"resources/{name}.resource","since":"","deprecated":false},{"type":"method","name":"RESOURCE()","signature":"RESOURCE([name], key)","since":"","deprecated":false},{"type":"method","name":"TRANSLATE()","signature":"TRANSLATE([language], text)","since":"","deprecated":false},{"type":"method","name":"TRANSLATOR()","signature":"TRANSLATOR(language, text)","since":"","deprecated":false},{"type":"method","name":"LOADRESOURCE()","signature":"LOADRESOURCE(name, value)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE()","signature":"LOCALIZE(fn)","since":"","deprecated":false},{"type":"method","name":"LOCALIZE(url)","signature":"LOCALIZE(url, [flags], [minify])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onLocale","signature":"DEF.onLocale = function(req, res, isStaticFile)","since":"","deprecated":false},{"type":"config","name":"opt.locale","signature":"AUTH({ locale: function(user, req) })","since":"0.0.57","deprecated":false},{"type":"property","name":"controller.language","signature":"controller.language","since":"","deprecated":false},{"type":"property","name":"req.language","signature":"req.language","since":"","deprecated":false},{"type":"method","name":"req.localize()","signature":"req.localize()","since":"","deprecated":false},{"type":"property","name":"$.language","signature":"$.language","since":"","deprecated":false},{"type":"method","name":"@(Text)","signature":"@(Text)","since":"","deprecated":false},{"type":"method","name":"@{resource()}","signature":"@{resource([name], key)}","since":"","deprecated":false},{"type":"property","name":"@{language}","signature":"@{language}","since":"","deprecated":false},{"type":"method","name":"@{notranslate}","signature":"@{notranslate}","since":"","deprecated":false},{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"0.0.37","deprecated":false},{"type":"method","name":"VIEW()","signature":"VIEW(name, [model], [layout], [repository], [language])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.resource()","signature":"builder.resource(name, [prefix])","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setResource()","signature":"builder.setResource(name)","since":"","deprecated":false},{"type":"method","name":"ErrorBuilder.setPrefix()","signature":"builder.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"schema.setResource()","signature":"schema.setResource(name)","since":"","deprecated":false},{"type":"method","name":"schema.setPrefix()","signature":"schema.setPrefix(prefix)","since":"","deprecated":false},{"type":"method","name":"F.register()","signature":"F.register(path)","since":"","deprecated":false},{"type":"property","name":"F.resources","signature":"F.resources","since":"","deprecated":false},{"type":"method","name":"PATH.resources()","signature":"PATH.resources([filename])","since":"","deprecated":false},{"type":"config","name":"directory_resources","signature":"directory_resources : /resources/","since":"","deprecated":false},{"type":"config","name":"allow_localize","signature":"allow_localize : true","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_name","signature":"default_errorbuilder_resource_name : name","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_resource_prefix","signature":"default_errorbuilder_resource_prefix : prefix","since":"","deprecated":false},{"type":"method","name":"total4 translate","signature":"total4 translate [path | \"text\" | filename]","since":"","deprecated":false},{"type":"method","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"method","name":"total4 csv","signature":"total4 csv <filename>","since":"","deprecated":false},{"type":"method","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"method","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabmGj3li60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"HTTP requests","summary":"RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services.","markdown":"---\ntitle: HTTP requests\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# HTTP requests\n\n> RESTBuilder, REQUEST() and DOWNLOAD(): the clients for other HTTP services.\n\nThe global functions and the `RESTBuilder` methods that send requests to other services. The guide [HTTP requests](../../guides/http-requests/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nSends an HTTP request and returns the raw response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | The options of the request (see the table). |\n| `callback` | `Function` | no |  | `function(err, response)`. Without it the method returns a promise. |\n\nReturns: `Promise|undefined` A promise of the response when you do not pass a callback.\n\nThe low-level HTTP client of the framework; `RESTBuilder` and `DOWNLOAD()` use it. Without a callback it returns a promise of the response.\n\n**Options**\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `url` | String | The address (`http://` or `https://`) |\n| `method` | String | The HTTP method, default `GET` |\n| `headers` | Object | Request headers |\n| `query` | Object/String | Appended to the URL as a query string |\n| `body` | String/Buffer | The body; with `files`, an object of form fields |\n| `type` | String | Sets `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`) |\n| `files` | Array | Files to upload as `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` or `{ name, filename, url }` |\n| `cookies` | Object | Cookies to send, as `{ name: value }` |\n| `cook` | Boolean | Collects cookies of the responses (also from redirects) into `options.cookies` |\n| `timeout` | Number | Milliseconds; default `CONF.default_restbuilder_timeout` (`10000`); `0` turns it off |\n| `encoding` | String | Encoding of a text response, default `utf8`; `binary` returns a `Buffer` |\n| `custom` | Boolean | Returns `response.stream` instead of reading the body |\n| `noredirect` | Boolean | Does not follow `301` and `302` redirects |\n| `keepalive` | Boolean | Reuses connections (not with a proxy) |\n| `proxy` | String | A proxy server, for example `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Resolves the host name once and caches the address |\n| `xhr` | Boolean | Adds `X-Requested-With: XMLHttpRequest` |\n| `unixsocket` | Object | `{ socket, path }` sends the request to a Unix socket instead of `url` |\n| `key`, `cert`, `dhparam` | Buffer | TLS client certificate |\n| `insecure` | Boolean | Accepts invalid TLS certificates |\n| `compress` | String | Compresses the body with `gzip` or `deflate` and sets `Content-Encoding` |\n| `encrypt` | String | Encrypts the body with this key (header `X-Encryption`) and decrypts a text response |\n| `onprogress` | Function | `fn(percentage)` while the body downloads |\n| `ondata` | Function | `fn(chunk, percentage)` for every chunk |\n| `callback` | Function | The same as the `callback` argument |\n\n**Response**: `status`, `headers`, `body`, `host`, `origin` (the resolved addresses, with `resolve`) and `cookies`; with `custom: true`, `stream` instead of `body`. Errors: `Invalid hostname`, the text of status `408` after a timeout, `Too many redirects` after four redirects, or a network error (then `status` is `0`).\n\nExample: GET with a callback\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: POST JSON with a promise\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Read a stream\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nDownloads a URL into a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | An absolute or relative URL, or `{ socket, path }`. |\n| `filename` | `String` | yes |  | The target file. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Milliseconds. |\n\nReturns: `Promise|undefined` A promise of the response when you do not pass a callback.\n\nSends a `GET` request and writes the response body into `filename`. The callback runs when the file is written. Without a callback the method returns a promise.\n\nA relative URL (for example `/sitemap.xml`) is requested from your own application; before the application is loaded the call waits. An object `{ socket, path }` instead of the URL sends the request to a Unix socket.\n\nThe response has `status`, `headers` and `filename`. The status code is not checked: the file is written for `404` too.\n\nExample: Save an image\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: With await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCreates a builder for a `GET` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n| `data` | `Object` | no |  | Query string arguments. |\n\nReturns: `RESTBuilder` A new builder.\n\n`data` becomes the query string of the URL. Send the request with `callback()`, `exec()`, `promise()` or `stream()`.\n\nExample: Load a list\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCreates a builder for a `POST` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n| `data` | `Object` | no |  | The body, sent as JSON. |\n\nReturns: `RESTBuilder` A new builder.\n\nThe data is sent as JSON. Call `urlencoded()` or `xml()` to send another format.\n\nExample: POST request\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCreates a builder for a `PUT` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n| `data` | `Object` | no |  | The body, sent as JSON. |\n\nReturns: `RESTBuilder` A new builder.\n\nThe data is sent as JSON.\n\nExample: PUT request\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCreates a builder for a `PATCH` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n| `data` | `Object` | no |  | The body, sent as JSON. |\n\nReturns: `RESTBuilder` A new builder.\n\nThe data is sent as JSON.\n\nExample: PATCH request\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCreates a builder for a `DELETE` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n| `data` | `Object` | no |  | The body, sent as JSON. |\n\nReturns: `RESTBuilder` A new builder.\n\nThe data, if any, is sent as JSON.\n\nExample: DELETE request\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nCreates a builder for a `HEAD` request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address. |\n\nReturns: `RESTBuilder` A new builder.\n\nRead the answer from `output.status` and `output.headers` in the callback.\n\nExample: Does the file exist?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nCalls an operation of a Total.js API endpoint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address of the API endpoint. |\n| `name` | `String` | yes |  | The name of the operation, with its parameters (for example `products_read/P01`). |\n| `data` | `Object` | no |  | The data of the operation. |\n\nReturns: `RESTBuilder` A new builder.\n\nSends a `POST` with the JSON body `{ schema: name, data: data }`, the format that Total.js API routes read.\n\nExample: Call an operation\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCreates an empty builder and passes it to a function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` The new builder.\n\n`fn(builder)` sets the URL, method and everything else. `RESTBuilder.url(url)` creates a builder with a URL only, and the instance method `builder.make(fn)` calls `fn` with the builder as `this` and as the argument.\n\nExample: Build the request\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nChanges every builder before it sends its request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` runs in `exec()` for every builder of the application, after the body is prepared and before the request is sent. Register it once, in a definition file.\n\nExample: Add a header to all requests\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nRegisters a function that changes parsed responses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the transformation. |\n| `fn` | `Function` | yes |  | `function(value, output)` returning the new value. |\n| `isDefault` | `Boolean` | no | `false` | Use it for all builders. |\n\nReturns: `undefined`\n\n`fn(value, output)` runs with `this` as the builder and returns the new value. A builder uses it after `setTransform(name)`; with `isDefault`, every new builder uses it. `RESTBuilder.setDefaultTransform(name)` changes the default and `RESTBuilder.setDefaultTransform()` removes it. The transformation does not run when the response is a Total.js error array that becomes `err`.\n\nExample: Unwrap a data envelope\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nReads or sets the URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | The address. |\n\nReturns: `RESTBuilder|String` The builder, or the URL when called without an argument.\n\nWithout an argument it returns the current URL.\n\nExample: Set the URL\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nSets the HTTP method.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | For example `POST` or `put`. |\n| `data` | `Object` | no |  | The body, sent as JSON. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nLower-case names are converted to upper case. `data` is sent as JSON.\n\nExample: Choose the method\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nSwitches to `GET` and sets the query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Query string arguments. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`data` replaces the query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nSwitches to `POST` and sets the body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | The body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe body keeps the type set earlier (`urlencoded()`, `xml()`), otherwise it is JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nSwitches to `PUT` and sets the body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | The body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`builder.patch([data])` and `builder.delete([data])` work the same with `PATCH` and `DELETE`; `builder.head()` switches to `HEAD`. Each has an upper-case alias (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT and DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nSets a request header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the header. |\n| `value` | `String` | yes |  | The value. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nFor a CSRF token you can also use `builder.csrf(value)` (`X-Csrf-Token`), and `builder.origin(value)` for `Origin`.\n\nExample: Token header\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nSets the `Content-Type` header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The content type. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nIt overrides the type that `json()`, `xml()` and the other body methods set.\n\nExample: Custom type\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nSets the `Accept` header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | An extension or a content type. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA short value is an extension (`json`, `xml`) and is converted to its content type; a longer value is used as it is.\n\nExample: Ask for XML\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nSets the `Authorization` header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | The user name, or the whole header value. |\n| `password` | `String` | no |  | The password. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nWith a password it creates Basic authentication. Without it, `user` is the whole value, for example `Bearer TOKEN`.\n\nExample: Basic and Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nAdds a cookie to the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name. |\n| `value` | `String` | yes |  | The value. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`builder.cookies(obj)` replaces all cookies with an object `{ name: value }`.\n\nExample: Send a session cookie\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nCollects the cookies of the responses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` turns it off. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nCookies set by the server, also during redirects, are stored in the object of `cookies()` and returned by `output.cookie(name)`. Pass the same object to the next builder to keep a session.\n\nExample: Keep a session\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nSends the body as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | The body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA `GET` becomes a `POST`.\n\nExample: JSON body\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nSends the body as `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | The body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA `GET` becomes a `POST`. An object is encoded as a form.\n\nExample: Form body\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nSends the body as XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | The XML. |\n| `replace` | `Boolean` | no | `false` | Passed to `parseXML()` for the response. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nSets `Content-Type: text/xml`; a `GET` becomes a `POST`. Send the XML as a string. An XML response is parsed with `String.parseXML()`; `replace` is its argument.\n\nExample: SOAP-like call\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nSends a text body and returns the response as text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | The body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nSets `Content-Type: text/plain`. The response is not parsed: `response` is the raw body.\n\nExample: Read text\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nSets the body and its type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | The body. |\n| `type` | `String` | yes |  | The type of the body. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`type` is `json`, `urlencoded`, `xml`, `plain`, `html` or `raw` (`application/octet-stream`). An object is serialized when the request is sent, except for type `raw`: send a string or a `Buffer` there.\n\nExample: Binary body\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nSets one field of the body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | The field, or an object of fields. |\n| `value` | `Object` | no |  | The value. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`name` can be an object with several fields. `builder.rem(name)` removes a field. With `file()`, the fields are sent as form fields.\n\nExample: Fields\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAdds a file to upload.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the form field. |\n| `filename` | `String` | yes |  | The file name. |\n| `source` | `Buffer|String` | no |  | The content, a path or a URL. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe request becomes `multipart/form-data`, and a `GET` becomes a `POST`. `source` is a `Buffer`, a path or a URL; a URL is downloaded and forwarded. Without `source`, `filename` is read as a path and only its name is sent. The content type comes from the extension of `filename`.\n\nExample: Upload two files\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nSets the timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Milliseconds. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe default of a builder is `10000`. After the timeout `err` is the text of status `408`.\n\nExample: Short timeout\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nReuses connections.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe request uses a shared keep-alive agent. It has no effect with a proxy.\n\nExample: Many calls to one host\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nSends the request through a proxy server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | For example `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe URL can contain credentials. For all requests set `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nSets a TLS client certificate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | The private key. |\n| `cert` | `Buffer` | yes |  | The certificate. |\n| `dhparam` | `Buffer` | no |  | Diffie-Hellman parameters. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nUse it for services that require client certificates. `builder.insecure()` accepts invalid server certificates (for testing only).\n\nExample: Client certificate\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nTurns off the DNS cache for this request.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA builder resolves the host name once and keeps the address; this resolves it as usual. Local addresses are never cached.\n\nExample: Fresh DNS\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nTurns following of redirects on or off.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Follow redirects. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`redirect(false)` returns the `301` or `302` response itself. Redirects are followed by default.\n\nExample: Read the location\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nSends the request to a Unix socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | The path of the socket file. |\n| `path` | `String` | yes |  | The path of the request. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA URL set earlier becomes the path.\n\nExample: Local service\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nAdds `X-Requested-With: XMLHttpRequest`.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nSets the `Referer` header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The URL. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nEncrypts the body and decrypts the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | The key. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nUses the framework encryption with `key`, or `DEF.secret_encryption`, and adds `X-Encryption`. Both sides must use the same key.\n\nExample: Encrypted call\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nCaches a successful response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | For example `5 minutes`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nA response with status `200` is stored in `F.cache` for `expire`; the key is made from the URL and the body. `builder.nocache()` skips the cache for one call.\n\nExample: Cache rates\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nValidates the response with a schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the schema. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe callback gets the model created by the schema. Errors of the schema and a status code `400` or higher come back as `err`. The method throws when the schema does not exist.\n\nExample: Validate the response\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nKeeps and converts selected fields of the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | For example `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`map` lists `field:type` pairs separated by commas. A third part renames the field: `source:type:target`. It works for an object and for an array of objects.\n\nExample: Map a list\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nConverts fields of the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | For example `price:number,date:date`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThe response goes through `CONVERT(value, schema)`. It does not run together with `schema()`.\n\nExample: Convert types\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nTreats status codes `400` and higher as errors.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nThen `err` is the status code. Without it you must check `output.status` yourself.\n\nExample: Fail on 404\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nReturns the raw body without parsing.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`response` is the body as text (or a `Buffer` for binary types).\n\nExample: Raw JSON\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nUses a registered transformation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the transformation. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nSee `RESTBuilder.addTransform()`.\n\nExample: Use a transformation\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nReports the progress of the download.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`fn(percentage)` runs for every chunk. It needs the `Content-Length` header of the response; without it the percentage is `0`.\n\nExample: Progress\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nLogs the request and the response.\n\nReturns: `RESTBuilder` The builder, for chaining.\n\nPrints the status, method, URL, error and raw body to the console.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nSends the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)`, or `$`. |\n\nReturns: `RESTBuilder|Promise` The builder, or a promise without a function.\n\nWith a function, `fn(err, response, output)` runs with the result. Without a function, or with `$` of a schema operation, the method returns a promise: with `$`, an error goes to `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promise\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nSends the request at once.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`callback(err, response, output)` is the same as in `callback()`; `exec()` sends immediately, `callback()` on the next tick.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nSends the request and returns a promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The options of an operation. |\n\nReturns: `Promise` A promise of the parsed response.\n\nThe promise resolves with the parsed response. With `$` (the options of a schema operation), an error is passed to `$.invalid()` and the promise does not settle; without it the promise rejects.\n\nExample: In an operation\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nSends the request and returns the response as a stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` The builder, for chaining.\n\n`callback(err, response)` receives `status`, `headers`, `origin` and `stream` (the incoming message). The body is not read or parsed.\n\nExample: Pipe to a file\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nReads a cookie from the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the cookie. |\n\nReturns: `String` The value.\n\n`output` is the third argument of the callback. The method reads the `Set-Cookie` headers, or the cookies collected by `cook()`, and returns the decoded value or an empty string.\n\nExample: Read a cookie\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JabmGj3li60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"HTTP-Anfragen","summary":"RESTBuilder, REQUEST() und DOWNLOAD(): die Clients für andere HTTP-Dienste.","markdown":"---\ntitle: HTTP-Anfragen\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# HTTP-Anfragen\n\n> RESTBuilder, REQUEST() und DOWNLOAD(): die Clients für andere HTTP-Dienste.\n\nDie globalen Funktionen und die `RESTBuilder`-Methoden, die Anfragen an andere Dienste senden. Der Leitfaden [HTTP-Anfragen](../../guides/http-requests/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nSendet eine HTTP-Anfrage und gibt die rohe Antwort zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Die Optionen der Anfrage (siehe Tabelle). |\n| `callback` | `Function` | no |  | `function(err, response)`. Ohne ihn gibt die Methode ein Promise zurück. |\n\nReturns: `Promise|undefined` Ein Promise mit der Antwort, wenn du keinen Callback übergibst.\n\nDer Low-Level-HTTP-Client des Frameworks; `RESTBuilder` und `DOWNLOAD()` verwenden ihn. Ohne Callback gibt er ein Promise mit der Antwort zurück.\n\n**Optionen**\n\n| Option | Typ | Beschreibung |\n| --- | --- | --- |\n| `url` | String | Die Adresse (`http://` oder `https://`) |\n| `method` | String | Die HTTP-Methode, Standard `GET` |\n| `headers` | Object | Request-Header |\n| `query` | Object/String | Wird als Query-String an die URL angehängt |\n| `body` | String/Buffer | Der Body; mit `files` ein Objekt mit Formularfeldern |\n| `type` | String | Setzt `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` oder `raw` (`application/octet-stream`) |\n| `files` | Array | Dateien, die als `multipart/form-data` hochgeladen werden: `{ name, filename, buffer }`, `{ name, filename, path }` oder `{ name, filename, url }` |\n| `cookies` | Object | Zu sendende Cookies, als `{ name: value }` |\n| `cook` | Boolean | Sammelt die Cookies der Antworten (auch aus Weiterleitungen) in `options.cookies` |\n| `timeout` | Number | Millisekunden; Standard `CONF.default_restbuilder_timeout` (`10000`); `0` schaltet es ab |\n| `encoding` | String | Kodierung einer Textantwort, Standard `utf8`; `binary` gibt einen `Buffer` zurück |\n| `custom` | Boolean | Gibt `response.stream` zurück, statt den Body zu lesen |\n| `noredirect` | Boolean | Folgt keinen Weiterleitungen mit `301` und `302` |\n| `keepalive` | Boolean | Verwendet Verbindungen wieder (nicht mit einem Proxy) |\n| `proxy` | String | Ein Proxyserver, zum Beispiel `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Löst den Hostnamen einmal auf und speichert die Adresse zwischen |\n| `xhr` | Boolean | Fügt `X-Requested-With: XMLHttpRequest` hinzu |\n| `unixsocket` | Object | `{ socket, path }` sendet die Anfrage an einen Unix-Socket statt an `url` |\n| `key`, `cert`, `dhparam` | Buffer | TLS-Client-Zertifikat |\n| `insecure` | Boolean | Akzeptiert ungültige TLS-Zertifikate |\n| `compress` | String | Komprimiert den Body mit `gzip` oder `deflate` und setzt `Content-Encoding` |\n| `encrypt` | String | Verschlüsselt den Body mit diesem Schlüssel (Header `X-Encryption`) und entschlüsselt eine Textantwort |\n| `onprogress` | Function | `fn(percentage)`, während der Body heruntergeladen wird |\n| `ondata` | Function | `fn(chunk, percentage)` für jeden Chunk |\n| `callback` | Function | Dasselbe wie das Argument `callback` |\n\n**Antwort**: `status`, `headers`, `body`, `host`, `origin` (die aufgelösten Adressen, mit `resolve`) und `cookies`; mit `custom: true` `stream` statt `body`. Fehler: `Invalid hostname`, der Text des Status `408` nach einem Timeout, `Too many redirects` nach vier Weiterleitungen oder ein Netzwerkfehler (dann ist `status` gleich `0`).\n\nExample: GET mit einem Callback\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: JSON per POST mit einem Promise\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Einen Stream lesen\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nLädt eine URL in eine Datei herunter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Eine absolute oder relative URL oder `{ socket, path }`. |\n| `filename` | `String` | yes |  | Die Zieldatei. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Millisekunden. |\n\nReturns: `Promise|undefined` Ein Promise mit der Antwort, wenn du keinen Callback übergibst.\n\nSendet eine `GET`-Anfrage und schreibt den Body der Antwort in `filename`. Der Callback läuft, wenn die Datei geschrieben ist. Ohne Callback gibt die Methode ein Promise zurück.\n\nEine relative URL (zum Beispiel `/sitemap.xml`) wird von deiner eigenen Anwendung angefordert; bevor die Anwendung geladen ist, wartet der Aufruf. Ein Objekt `{ socket, path }` statt der URL sendet die Anfrage an einen Unix-Socket.\n\nDie Antwort enthält `status`, `headers` und `filename`. Der Statuscode wird nicht geprüft: Die Datei wird auch bei `404` geschrieben.\n\nExample: Ein Bild speichern\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: Mit await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nErstellt einen Builder für eine `GET`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n| `data` | `Object` | no |  | Argumente des Query-Strings. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\n`data` wird zum Query-String der URL. Sende die Anfrage mit `callback()`, `exec()`, `promise()` oder `stream()`.\n\nExample: Eine Liste laden\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nErstellt einen Builder für eine `POST`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n| `data` | `Object` | no |  | Der Body, als JSON gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nDie Daten werden als JSON gesendet. Rufe `urlencoded()` oder `xml()` auf, um ein anderes Format zu senden.\n\nExample: POST-Anfrage\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nErstellt einen Builder für eine `PUT`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n| `data` | `Object` | no |  | Der Body, als JSON gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nDie Daten werden als JSON gesendet.\n\nExample: PUT-Anfrage\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nErstellt einen Builder für eine `PATCH`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n| `data` | `Object` | no |  | Der Body, als JSON gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nDie Daten werden als JSON gesendet.\n\nExample: PATCH-Anfrage\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nErstellt einen Builder für eine `DELETE`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n| `data` | `Object` | no |  | Der Body, als JSON gesendet. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nVorhandene Daten werden als JSON gesendet.\n\nExample: DELETE-Anfrage\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nErstellt einen Builder für eine `HEAD`-Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nLies die Antwort im Callback aus `output.status` und `output.headers`.\n\nExample: Existiert die Datei?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nRuft eine Operation eines Total.js-API-Endpunkts auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse des API-Endpunkts. |\n| `name` | `String` | yes |  | Der Name der Operation, mit ihren Parametern (zum Beispiel `products_read/P01`). |\n| `data` | `Object` | no |  | Die Daten der Operation. |\n\nReturns: `RESTBuilder` Ein neuer Builder.\n\nSendet ein `POST` mit dem JSON-Body `{ schema: name, data: data }`, dem Format, das Total.js-API-Routen lesen.\n\nExample: Eine Operation aufrufen\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nErstellt einen leeren Builder und übergibt ihn an eine Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` Der neue Builder.\n\n`fn(builder)` setzt die URL, die Methode und alles andere. `RESTBuilder.url(url)` erstellt einen Builder nur mit einer URL, und die Instanzmethode `builder.make(fn)` ruft `fn` mit dem Builder als `this` und als Argument auf.\n\nExample: Die Anfrage aufbauen\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nVerändert jeden Builder, bevor er seine Anfrage sendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` läuft in `exec()` für jeden Builder der Anwendung, nachdem der Body vorbereitet ist und bevor die Anfrage gesendet wird. Registriere die Funktion einmal, in einer Definitionsdatei.\n\nExample: Allen Anfragen einen Header hinzufügen\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nRegistriert eine Funktion, die geparste Antworten verändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Transformation. |\n| `fn` | `Function` | yes |  | `function(value, output)`, die den neuen Wert zurückgibt. |\n| `isDefault` | `Boolean` | no | `false` | Für alle Builder verwenden. |\n\nReturns: `undefined`\n\n`fn(value, output)` läuft mit dem Builder als `this` und gibt den neuen Wert zurück. Ein Builder verwendet sie nach `setTransform(name)`; mit `isDefault` verwendet sie jeder neue Builder. `RESTBuilder.setDefaultTransform(name)` ändert den Standard und `RESTBuilder.setDefaultTransform()` entfernt ihn. Die Transformation läuft nicht, wenn die Antwort ein Total.js-Fehlerarray ist, das zu `err` wird.\n\nExample: Eine Datenhülle auspacken\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nLiest oder setzt die URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Die Adresse. |\n\nReturns: `RESTBuilder|String` Der Builder oder, ohne Argument aufgerufen, die URL.\n\nOhne Argument gibt sie die aktuelle URL zurück.\n\nExample: Die URL setzen\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nSetzt die HTTP-Methode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | Zum Beispiel `POST` oder `put`. |\n| `data` | `Object` | no |  | Der Body, als JSON gesendet. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nNamen in Kleinbuchstaben werden in Großbuchstaben umgewandelt. `data` wird als JSON gesendet.\n\nExample: Die Methode wählen\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nWechselt zu `GET` und setzt den Query-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Argumente des Query-Strings. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`data` ersetzt die Query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nWechselt zu `POST` und setzt den Body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Der Body. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDer Body behält den zuvor gesetzten Typ (`urlencoded()`, `xml()`), sonst ist er JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nWechselt zu `PUT` und setzt den Body.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Der Body. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`builder.patch([data])` und `builder.delete([data])` funktionieren genauso mit `PATCH` und `DELETE`; `builder.head()` wechselt zu `HEAD`. Jede hat einen Alias in Großbuchstaben (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT und DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nSetzt einen Request-Header.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Headers. |\n| `value` | `String` | yes |  | Der Wert. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nFür ein CSRF-Token kannst du auch `builder.csrf(value)` (`X-Csrf-Token`) verwenden und `builder.origin(value)` für `Origin`.\n\nExample: Token-Header\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nSetzt den Header `Content-Type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Content-Type. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEr überschreibt den Typ, den `json()`, `xml()` und die anderen Body-Methoden setzen.\n\nExample: Eigener Typ\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nSetzt den Header `Accept`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Eine Endung oder ein Content-Type. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEin kurzer Wert ist eine Endung (`json`, `xml`) und wird in ihren Content-Type umgewandelt; ein längerer Wert wird unverändert verwendet.\n\nExample: XML anfordern\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nSetzt den Header `Authorization`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | Der Benutzername oder der ganze Header-Wert. |\n| `password` | `String` | no |  | Das Passwort. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nMit einem Passwort erzeugt sie eine Basic-Authentifizierung. Ohne Passwort ist `user` der ganze Wert, zum Beispiel `Bearer TOKEN`.\n\nExample: Basic und Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nFügt der Anfrage ein Cookie hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name. |\n| `value` | `String` | yes |  | Der Wert. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`builder.cookies(obj)` ersetzt alle Cookies durch ein Objekt `{ name: value }`.\n\nExample: Ein Session-Cookie senden\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nSammelt die Cookies der Antworten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` schaltet es aus. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nVom Server gesetzte Cookies, auch während Weiterleitungen, werden im Objekt von `cookies()` gespeichert und von `output.cookie(name)` zurückgegeben. Übergib dasselbe Objekt an den nächsten Builder, um eine Session beizubehalten.\n\nExample: Eine Session beibehalten\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nSendet den Body als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Der Body. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEin `GET` wird zu einem `POST`.\n\nExample: JSON-Body\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nSendet den Body als `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Der Body. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEin `GET` wird zu einem `POST`. Ein Objekt wird als Formular kodiert.\n\nExample: Formular-Body\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nSendet den Body als XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | Das XML. |\n| `replace` | `Boolean` | no | `false` | Wird für die Antwort an `parseXML()` übergeben. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nSetzt `Content-Type: text/xml`; ein `GET` wird zu einem `POST`. Sende das XML als String. Eine XML-Antwort wird mit `String.parseXML()` geparst; `replace` ist dessen Argument.\n\nExample: SOAP-ähnlicher Aufruf\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nSendet einen Text-Body und gibt die Antwort als Text zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Der Body. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nSetzt `Content-Type: text/plain`. Die Antwort wird nicht geparst: `response` ist der rohe Body.\n\nExample: Text lesen\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nSetzt den Body und seinen Typ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | Der Body. |\n| `type` | `String` | yes |  | Der Typ des Bodys. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`type` ist `json`, `urlencoded`, `xml`, `plain`, `html` oder `raw` (`application/octet-stream`). Ein Objekt wird beim Senden der Anfrage serialisiert, außer beim Typ `raw`: Sende dort einen String oder einen `Buffer`.\n\nExample: Binärer Body\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nSetzt ein Feld des Bodys.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Das Feld oder ein Objekt mit Feldern. |\n| `value` | `Object` | no |  | Der Wert. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`name` kann ein Objekt mit mehreren Feldern sein. `builder.rem(name)` entfernt ein Feld. Mit `file()` werden die Felder als Formularfelder gesendet.\n\nExample: Felder\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nFügt eine Datei zum Hochladen hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Formularfelds. |\n| `filename` | `String` | yes |  | Der Dateiname. |\n| `source` | `Buffer|String` | no |  | Der Inhalt, ein Pfad oder eine URL. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDie Anfrage wird zu `multipart/form-data`, und ein `GET` wird zu einem `POST`. `source` ist ein `Buffer`, ein Pfad oder eine URL; eine URL wird heruntergeladen und weitergeleitet. Ohne `source` wird `filename` als Pfad gelesen und nur sein Name gesendet. Der Content-Type ergibt sich aus der Endung von `filename`.\n\nExample: Zwei Dateien hochladen\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nSetzt das Timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Millisekunden. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDer Standard eines Builders ist `10000`. Nach dem Timeout ist `err` der Text des Status `408`.\n\nExample: Kurzes Timeout\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nVerwendet Verbindungen wieder.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDie Anfrage nutzt einen gemeinsamen Keep-Alive-Agenten. Mit einem Proxy hat das keine Wirkung.\n\nExample: Viele Aufrufe an einen Host\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nSendet die Anfrage über einen Proxyserver.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Zum Beispiel `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDie URL kann Zugangsdaten enthalten. Für alle Anfragen setzt du `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nSetzt ein TLS-Client-Zertifikat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | Der private Schlüssel. |\n| `cert` | `Buffer` | yes |  | Das Zertifikat. |\n| `dhparam` | `Buffer` | no |  | Diffie-Hellman-Parameter. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nNutze es für Dienste, die Client-Zertifikate verlangen. `builder.insecure()` akzeptiert ungültige Serverzertifikate (nur zum Testen).\n\nExample: Client-Zertifikat\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nSchaltet den DNS-Cache für diese Anfrage ab.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEin Builder löst den Hostnamen einmal auf und behält die Adresse; hiermit wird er wie üblich aufgelöst. Lokale Adressen werden nie zwischengespeichert.\n\nExample: Frisches DNS\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nSchaltet das Folgen von Weiterleitungen ein oder aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Weiterleitungen folgen. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`redirect(false)` gibt die `301`- oder `302`-Antwort selbst zurück. Weiterleitungen wird standardmäßig gefolgt.\n\nExample: Die Location lesen\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nSendet die Anfrage an einen Unix-Socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Der Pfad der Socket-Datei. |\n| `path` | `String` | yes |  | Der Pfad der Anfrage. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEine zuvor gesetzte URL wird zum Pfad.\n\nExample: Lokaler Dienst\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nFügt `X-Requested-With: XMLHttpRequest` hinzu.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nSetzt den Header `Referer`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die URL. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nVerschlüsselt den Body und entschlüsselt die Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | Der Schlüssel. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nVerwendet die Verschlüsselung des Frameworks mit `key` oder `DEF.secret_encryption` und fügt `X-Encryption` hinzu. Beide Seiten müssen denselben Schlüssel verwenden.\n\nExample: Verschlüsselter Aufruf\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nSpeichert eine erfolgreiche Antwort zwischen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | Zum Beispiel `5 minutes`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nEine Antwort mit Status `200` wird für die Dauer `expire` in `F.cache` gespeichert; der Schlüssel wird aus der URL und dem Body gebildet. `builder.nocache()` umgeht den Cache für einen Aufruf.\n\nExample: Kurse zwischenspeichern\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nValidiert die Antwort mit einem Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Schemas. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDer Callback erhält das vom Schema erstellte Modell. Fehler des Schemas und ein Statuscode ab `400` kommen als `err` zurück. Die Methode wirft einen Fehler, wenn das Schema nicht existiert.\n\nExample: Die Antwort validieren\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nBehält ausgewählte Felder der Antwort und konvertiert sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | Zum Beispiel `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`map` listet durch Kommas getrennte Paare `field:type` auf. Ein dritter Teil benennt das Feld um: `source:type:target`. Das funktioniert für ein Objekt und für ein Array von Objekten.\n\nExample: Eine Liste abbilden\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nKonvertiert Felder der Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Zum Beispiel `price:number,date:date`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDie Antwort durchläuft `CONVERT(value, schema)`. Das läuft nicht zusammen mit `schema()`.\n\nExample: Typen konvertieren\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nBehandelt Statuscodes ab `400` als Fehler.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nDann ist `err` der Statuscode. Ohne diese Methode musst du `output.status` selbst prüfen.\n\nExample: Bei 404 fehlschlagen\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nGibt den rohen Body ohne Parsen zurück.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`response` ist der Body als Text (oder ein `Buffer` bei binären Typen).\n\nExample: Rohes JSON\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nVerwendet eine registrierte Transformation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Transformation. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nSiehe `RESTBuilder.addTransform()`.\n\nExample: Eine Transformation verwenden\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nMeldet den Fortschritt des Downloads.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`fn(percentage)` läuft für jeden Chunk. Sie braucht den Header `Content-Length` der Antwort; ohne ihn ist der Prozentwert `0`.\n\nExample: Fortschritt\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nProtokolliert die Anfrage und die Antwort.\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\nGibt den Status, die Methode, die URL, den Fehler und den rohen Body auf der Konsole aus.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nSendet den Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` oder `$`. |\n\nReturns: `RESTBuilder|Promise` Der Builder oder ohne Funktion eine Promise.\n\nMit einer Funktion läuft `fn(err, response, output)` mit dem Ergebnis. Ohne Funktion oder mit `$` einer Schema-Operation gibt die Methode eine Promise zurück: Mit `$` geht ein Fehler an `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promise\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nSendet die Anfrage sofort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`callback(err, response, output)` ist derselbe wie in `callback()`; `exec()` sendet sofort, `callback()` im nächsten Tick.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nSendet die Anfrage und gibt ein Promise zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Die Optionen einer Operation. |\n\nReturns: `Promise` Ein Promise mit der geparsten Antwort.\n\nDas Promise wird mit der geparsten Antwort erfüllt. Mit `$` (den Optionen einer Schema-Operation) wird ein Fehler an `$.invalid()` übergeben und das Promise wird nicht abgeschlossen; ohne `$` wird das Promise abgelehnt.\n\nExample: In einer Operation\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nSendet die Anfrage und gibt die Antwort als Stream zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Der Builder, zum Verketten.\n\n`callback(err, response)` erhält `status`, `headers`, `origin` und `stream` (die eingehende Nachricht). Der Body wird weder gelesen noch geparst.\n\nExample: In eine Datei pipen\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nLiest ein Cookie aus der Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Cookies. |\n\nReturns: `String` Der Wert.\n\n`output` ist das dritte Argument des Callbacks. Die Methode liest die `Set-Cookie`-Header oder die von `cook()` gesammelten Cookies und gibt den dekodierten Wert oder einen leeren String zurück.\n\nExample: Ein Cookie lesen\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JabmGj3li60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Peticiones HTTP","summary":"RESTBuilder, REQUEST() y DOWNLOAD(): los clientes para otros servicios HTTP.","markdown":"---\ntitle: Peticiones HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# Peticiones HTTP\n\n> RESTBuilder, REQUEST() y DOWNLOAD(): los clientes para otros servicios HTTP.\n\nLas funciones globales y los métodos de `RESTBuilder` que envían peticiones a otros servicios. La guía [Peticiones HTTP](../../guides/http-requests/) explica con ejemplos cómo usarlos; esta página es la referencia exacta.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nEnvía una petición HTTP y devuelve la respuesta en bruto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Las opciones de la petición (ver la tabla). |\n| `callback` | `Function` | no |  | `function(err, response)`. Sin él, el método devuelve una promesa. |\n\nReturns: `Promise|undefined` Una promesa con la respuesta cuando no pasas un callback.\n\nEl cliente HTTP de bajo nivel del framework; lo usan `RESTBuilder` y `DOWNLOAD()`. Sin callback, devuelve una promesa con la respuesta.\n\n**Opciones**\n\n| Opción | Tipo | Descripción |\n| --- | --- | --- |\n| `url` | String | La dirección (`http://` o `https://`) |\n| `method` | String | El método HTTP, por defecto `GET` |\n| `headers` | Object | Cabeceras de la petición |\n| `query` | Object/String | Se añade a la URL como query string |\n| `body` | String/Buffer | El cuerpo; con `files`, un objeto de campos de formulario |\n| `type` | String | Define `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` o `raw` (`application/octet-stream`) |\n| `files` | Array | Archivos que se suben como `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` o `{ name, filename, url }` |\n| `cookies` | Object | Cookies que se envían, como `{ name: value }` |\n| `cook` | Boolean | Recoge las cookies de las respuestas (también de las redirecciones) en `options.cookies` |\n| `timeout` | Number | Milisegundos; por defecto `CONF.default_restbuilder_timeout` (`10000`); `0` lo desactiva |\n| `encoding` | String | Codificación de una respuesta de texto, por defecto `utf8`; `binary` devuelve un `Buffer` |\n| `custom` | Boolean | Devuelve `response.stream` en lugar de leer el cuerpo |\n| `noredirect` | Boolean | No sigue las redirecciones `301` y `302` |\n| `keepalive` | Boolean | Reutiliza las conexiones (no con un proxy) |\n| `proxy` | String | Un servidor proxy, por ejemplo `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Resuelve el nombre del host una vez y guarda la dirección en caché |\n| `xhr` | Boolean | Añade `X-Requested-With: XMLHttpRequest` |\n| `unixsocket` | Object | `{ socket, path }` envía la petición a un socket Unix en lugar de `url` |\n| `key`, `cert`, `dhparam` | Buffer | Certificado TLS de cliente |\n| `insecure` | Boolean | Acepta certificados TLS no válidos |\n| `compress` | String | Comprime el cuerpo con `gzip` o `deflate` y define `Content-Encoding` |\n| `encrypt` | String | Cifra el cuerpo con esta clave (cabecera `X-Encryption`) y descifra una respuesta de texto |\n| `onprogress` | Function | `fn(percentage)` mientras se descarga el cuerpo |\n| `ondata` | Function | `fn(chunk, percentage)` para cada fragmento |\n| `callback` | Function | Lo mismo que el argumento `callback` |\n\n**Respuesta**: `status`, `headers`, `body`, `host`, `origin` (las direcciones resueltas, con `resolve`) y `cookies`; con `custom: true`, `stream` en lugar de `body`. Errores: `Invalid hostname`, el texto del estado `408` tras un timeout, `Too many redirects` tras cuatro redirecciones, o un error de red (entonces `status` es `0`).\n\nExample: GET con un callback\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: POST de JSON con una promesa\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Leer un stream\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nDescarga una URL en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Una URL absoluta o relativa, o `{ socket, path }`. |\n| `filename` | `String` | yes |  | El archivo de destino. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Milisegundos. |\n\nReturns: `Promise|undefined` Una promesa con la respuesta cuando no pasas un callback.\n\nEnvía una petición `GET` y escribe el cuerpo de la respuesta en `filename`. El callback se ejecuta cuando el archivo está escrito. Sin callback, el método devuelve una promesa.\n\nUna URL relativa (por ejemplo `/sitemap.xml`) se pide a tu propia aplicación; si la aplicación aún no está cargada, la llamada espera. Un objeto `{ socket, path }` en lugar de la URL envía la petición a un socket Unix.\n\nLa respuesta tiene `status`, `headers` y `filename`. El código de estado no se comprueba: el archivo se escribe también con `404`.\n\nExample: Guardar una imagen\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: Con await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrea un builder para una petición `GET`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n| `data` | `Object` | no |  | Argumentos de la query string. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\n`data` se convierte en la query string de la URL. Envía la petición con `callback()`, `exec()`, `promise()` o `stream()`.\n\nExample: Cargar una lista\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrea un builder para una petición `POST`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n| `data` | `Object` | no |  | El cuerpo, enviado como JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nLos datos se envían como JSON. Llama a `urlencoded()` o `xml()` para enviar otro formato.\n\nExample: Petición POST\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrea un builder para una petición `PUT`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n| `data` | `Object` | no |  | El cuerpo, enviado como JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nLos datos se envían como JSON.\n\nExample: Petición PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrea un builder para una petición `PATCH`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n| `data` | `Object` | no |  | El cuerpo, enviado como JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nLos datos se envían como JSON.\n\nExample: Petición PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrea un builder para una petición `DELETE`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n| `data` | `Object` | no |  | El cuerpo, enviado como JSON. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nLos datos, si los hay, se envían como JSON.\n\nExample: Petición DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nCrea un builder para una petición `HEAD`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nLee la respuesta de `output.status` y `output.headers` en el callback.\n\nExample: ¿Existe el archivo?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nLlama a una operación de un endpoint de API de Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección del endpoint de API. |\n| `name` | `String` | yes |  | El nombre de la operación, con sus parámetros (por ejemplo `products_read/P01`). |\n| `data` | `Object` | no |  | Los datos de la operación. |\n\nReturns: `RESTBuilder` Un builder nuevo.\n\nEnvía un `POST` con el cuerpo JSON `{ schema: name, data: data }`, el formato que leen las rutas de API de Total.js.\n\nExample: Llamar a una operación\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrea un builder vacío y lo pasa a una función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` El builder nuevo.\n\n`fn(builder)` define la URL, el método y todo lo demás. `RESTBuilder.url(url)` crea un builder solo con una URL, y el método de instancia `builder.make(fn)` llama a `fn` con el builder como `this` y como argumento.\n\nExample: Construir la petición\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nModifica cada builder antes de que envíe su petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` se ejecuta en `exec()` para cada builder de la aplicación, después de preparar el cuerpo y antes de enviar la petición. Regístralo una vez, en un archivo de definición.\n\nExample: Añadir una cabecera a todas las peticiones\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nRegistra una función que modifica las respuestas parseadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la transformación. |\n| `fn` | `Function` | yes |  | `function(value, output)` que devuelve el nuevo valor. |\n| `isDefault` | `Boolean` | no | `false` | Usarla para todos los builders. |\n\nReturns: `undefined`\n\n`fn(value, output)` se ejecuta con el builder como `this` y devuelve el nuevo valor. Un builder la usa después de `setTransform(name)`; con `isDefault`, la usa cada builder nuevo. `RESTBuilder.setDefaultTransform(name)` cambia la predeterminada y `RESTBuilder.setDefaultTransform()` la elimina. La transformación no se ejecuta cuando la respuesta es un array de errores de Total.js que se convierte en `err`.\n\nExample: Desenvolver un sobre data\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nLee o define la URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La dirección. |\n\nReturns: `RESTBuilder|String` El builder, o la URL cuando se llama sin argumento.\n\nSin argumento, devuelve la URL actual.\n\nExample: Definir la URL\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nDefine el método HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | Por ejemplo `POST` o `put`. |\n| `data` | `Object` | no |  | El cuerpo, enviado como JSON. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLos nombres en minúsculas se convierten a mayúsculas. `data` se envía como JSON.\n\nExample: Elegir el método\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nCambia a `GET` y define la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Argumentos de la query string. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`data` reemplaza la query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nCambia a `POST` y define el cuerpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | El cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nEl cuerpo mantiene el tipo definido antes (`urlencoded()`, `xml()`); si no, es JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nCambia a `PUT` y define el cuerpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | El cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`builder.patch([data])` y `builder.delete([data])` funcionan igual con `PATCH` y `DELETE`; `builder.head()` cambia a `HEAD`. Cada uno tiene un alias en mayúsculas (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT y DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nDefine una cabecera de la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cabecera. |\n| `value` | `String` | yes |  | El valor. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nPara un token CSRF también puedes usar `builder.csrf(value)` (`X-Csrf-Token`), y `builder.origin(value)` para `Origin`.\n\nExample: Cabecera con token\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nDefine la cabecera `Content-Type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El tipo de contenido. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nSobrescribe el tipo que definen `json()`, `xml()` y los demás métodos del cuerpo.\n\nExample: Tipo personalizado\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nDefine la cabecera `Accept`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Una extensión o un tipo de contenido. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUn valor corto es una extensión (`json`, `xml`) y se convierte a su tipo de contenido; un valor más largo se usa tal cual.\n\nExample: Pedir XML\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nDefine la cabecera `Authorization`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | El nombre de usuario, o el valor completo de la cabecera. |\n| `password` | `String` | no |  | La contraseña. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nCon una contraseña, crea una autenticación Basic. Sin ella, `user` es el valor completo, por ejemplo `Bearer TOKEN`.\n\nExample: Basic y Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nAñade una cookie a la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre. |\n| `value` | `String` | yes |  | El valor. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`builder.cookies(obj)` reemplaza todas las cookies con un objeto `{ name: value }`.\n\nExample: Enviar una cookie de sesión\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nRecoge las cookies de las respuestas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` lo desactiva. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLas cookies que define el servidor, también durante las redirecciones, se guardan en el objeto de `cookies()` y las devuelve `output.cookie(name)`. Pasa el mismo objeto al siguiente builder para mantener una sesión.\n\nExample: Mantener una sesión\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nEnvía el cuerpo como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | El cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUn `GET` se convierte en `POST`.\n\nExample: Cuerpo JSON\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nEnvía el cuerpo como `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | El cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUn `GET` se convierte en `POST`. Un objeto se codifica como formulario.\n\nExample: Cuerpo de formulario\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nEnvía el cuerpo como XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | El XML. |\n| `replace` | `Boolean` | no | `false` | Se pasa a `parseXML()` para la respuesta. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nDefine `Content-Type: text/xml`; un `GET` se convierte en `POST`. Envía el XML como cadena. Una respuesta XML se parsea con `String.parseXML()`; `replace` es su argumento.\n\nExample: Llamada tipo SOAP\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nEnvía un cuerpo de texto y devuelve la respuesta como texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | El cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nDefine `Content-Type: text/plain`. La respuesta no se parsea: `response` es el cuerpo en bruto.\n\nExample: Leer texto\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nDefine el cuerpo y su tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | El cuerpo. |\n| `type` | `String` | yes |  | El tipo del cuerpo. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`type` es `json`, `urlencoded`, `xml`, `plain`, `html` o `raw` (`application/octet-stream`). Un objeto se serializa al enviar la petición, excepto con el tipo `raw`: ahí envía una cadena o un `Buffer`.\n\nExample: Cuerpo binario\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nDefine un campo del cuerpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | El campo, o un objeto de campos. |\n| `value` | `Object` | no |  | El valor. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`name` puede ser un objeto con varios campos. `builder.rem(name)` elimina un campo. Con `file()`, los campos se envían como campos de formulario.\n\nExample: Campos\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAñade un archivo para subir.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del campo del formulario. |\n| `filename` | `String` | yes |  | El nombre del archivo. |\n| `source` | `Buffer|String` | no |  | El contenido, una ruta o una URL. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLa petición pasa a ser `multipart/form-data`, y un `GET` se convierte en `POST`. `source` es un `Buffer`, una ruta o una URL; una URL se descarga y se reenvía. Sin `source`, `filename` se lee como ruta y solo se envía su nombre. El tipo de contenido sale de la extensión de `filename`.\n\nExample: Subir dos archivos\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nDefine el timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Milisegundos. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nEl valor por defecto de un builder es `10000`. Tras el timeout, `err` es el texto del estado `408`.\n\nExample: Timeout corto\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nReutiliza las conexiones.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLa petición usa un agente keep-alive compartido. No tiene efecto con un proxy.\n\nExample: Muchas llamadas a un mismo host\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nEnvía la petición a través de un servidor proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Por ejemplo `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLa URL puede contener credenciales. Para todas las peticiones, define `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nDefine un certificado TLS de cliente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | La clave privada. |\n| `cert` | `Buffer` | yes |  | El certificado. |\n| `dhparam` | `Buffer` | no |  | Parámetros Diffie-Hellman. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nÚsalo para servicios que exigen certificados de cliente. `builder.insecure()` acepta certificados de servidor no válidos (solo para pruebas).\n\nExample: Certificado de cliente\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDesactiva la caché DNS para esta petición.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUn builder resuelve el nombre del host una vez y guarda la dirección; esto lo resuelve de la forma habitual. Las direcciones locales nunca se guardan en caché.\n\nExample: DNS sin caché\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nActiva o desactiva el seguimiento de redirecciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Seguir las redirecciones. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`redirect(false)` devuelve la propia respuesta `301` o `302`. Las redirecciones se siguen por defecto.\n\nExample: Leer la ubicación\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nEnvía la petición a un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | La ruta del archivo del socket. |\n| `path` | `String` | yes |  | La ruta de la petición. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUna URL definida antes pasa a ser la ruta.\n\nExample: Servicio local\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nAñade `X-Requested-With: XMLHttpRequest`.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nDefine la cabecera `Referer`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | La URL. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nCifra el cuerpo y descifra la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | La clave. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUsa el cifrado del framework con `key`, o `DEF.secret_encryption`, y añade `X-Encryption`. Ambos lados deben usar la misma clave.\n\nExample: Llamada cifrada\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nGuarda en caché una respuesta correcta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | Por ejemplo `5 minutes`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nUna respuesta con estado `200` se guarda en `F.cache` durante `expire`; la clave se forma con la URL y el cuerpo. `builder.nocache()` omite la caché en una llamada.\n\nExample: Tipos de cambio en caché\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nValida la respuesta con un esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del esquema. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nEl callback recibe el modelo creado por el esquema. Los errores del esquema y un código de estado `400` o superior llegan como `err`. El método lanza una excepción cuando el esquema no existe.\n\nExample: Validar la respuesta\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nConserva y convierte campos seleccionados de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | Por ejemplo `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`map` enumera pares `field:type` separados por comas. Una tercera parte renombra el campo: `source:type:target`. Funciona con un objeto y con un array de objetos.\n\nExample: Mapear una lista\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nConvierte campos de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Por ejemplo `price:number,date:date`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nLa respuesta pasa por `CONVERT(value, schema)`. No se ejecuta junto con `schema()`.\n\nExample: Convertir tipos\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nTrata los códigos de estado `400` y superiores como errores.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nEntonces `err` es el código de estado. Sin esto, tienes que comprobar `output.status` tú mismo.\n\nExample: Fallar con 404\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nDevuelve el cuerpo en bruto sin parsear.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`response` es el cuerpo como texto (o un `Buffer` para tipos binarios).\n\nExample: JSON en bruto\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nUsa una transformación registrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la transformación. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nVer `RESTBuilder.addTransform()`.\n\nExample: Usar una transformación\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nInforma del progreso de la descarga.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`fn(percentage)` se ejecuta para cada fragmento. Necesita la cabecera `Content-Length` de la respuesta; sin ella, el porcentaje es `0`.\n\nExample: Progreso\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nRegistra la petición y la respuesta en el log.\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\nImprime en la consola el estado, el método, la URL, el error y el cuerpo en bruto.\n\nExample: Depuración\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nEnvía la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)`, o `$`. |\n\nReturns: `RESTBuilder|Promise` El builder, o una promesa si no hay función.\n\nCon una función, `fn(err, response, output)` se ejecuta con el resultado. Sin función, o con el `$` de una operación de esquema, el método devuelve una promesa: con `$`, un error va a `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promesa\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nEnvía la petición de inmediato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`callback(err, response, output)` es igual que en `callback()`; `exec()` envía inmediatamente, `callback()` en el siguiente tick.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nEnvía la petición y devuelve una promesa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Las opciones de una operación. |\n\nReturns: `Promise` Una promesa con la respuesta parseada.\n\nLa promesa se resuelve con la respuesta parseada. Con `$` (las opciones de una operación de esquema), un error se pasa a `$.invalid()` y la promesa no se resuelve; sin él, la promesa se rechaza.\n\nExample: En una operación\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nEnvía la petición y devuelve la respuesta como stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` El builder, para encadenar.\n\n`callback(err, response)` recibe `status`, `headers`, `origin` y `stream` (el mensaje entrante). El cuerpo no se lee ni se parsea.\n\nExample: Volcar a un archivo\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nLee una cookie de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la cookie. |\n\nReturns: `String` El valor.\n\n`output` es el tercer argumento del callback. El método lee las cabeceras `Set-Cookie`, o las cookies recogidas por `cook()`, y devuelve el valor decodificado o una cadena vacía.\n\nExample: Leer una cookie\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JabmGj3li60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Requêtes HTTP","summary":"RESTBuilder, REQUEST() et DOWNLOAD() : les clients pour les autres services HTTP.","markdown":"---\ntitle: \"Requêtes HTTP\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# Requêtes HTTP\n\n> RESTBuilder, REQUEST() et DOWNLOAD() : les clients pour les autres services HTTP.\n\nLes fonctions globales et les méthodes de `RESTBuilder` qui envoient des requêtes à d'autres services. Le guide [Requêtes HTTP](../../guides/http-requests/) explique comment les utiliser, avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nEnvoie une requête HTTP et renvoie la réponse brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Les options de la requête (voir le tableau). |\n| `callback` | `Function` | no |  | `function(err, response)`. Sans lui, la méthode renvoie une promesse. |\n\nReturns: `Promise|undefined` Une promesse de la réponse quand tu ne passes pas de callback.\n\nLe client HTTP de bas niveau du framework ; `RESTBuilder` et `DOWNLOAD()` l'utilisent. Sans callback, il renvoie une promesse de la réponse.\n\n**Options**\n\n| Option | Type | Description |\n| --- | --- | --- |\n| `url` | String | L'adresse (`http://` ou `https://`) |\n| `method` | String | La méthode HTTP, par défaut `GET` |\n| `headers` | Object | En-têtes de la requête |\n| `query` | Object/String | Ajouté à l'URL sous forme de query string |\n| `body` | String/Buffer | Le corps ; avec `files`, un objet de champs de formulaire |\n| `type` | String | Définit `Content-Type` : `json`, `urlencoded`, `xml`, `plain`, `html` ou `raw` (`application/octet-stream`) |\n| `files` | Array | Fichiers à envoyer en `multipart/form-data` : `{ name, filename, buffer }`, `{ name, filename, path }` ou `{ name, filename, url }` |\n| `cookies` | Object | Cookies à envoyer, sous la forme `{ name: value }` |\n| `cook` | Boolean | Collecte les cookies des réponses (y compris des redirections) dans `options.cookies` |\n| `timeout` | Number | Millisecondes ; par défaut `CONF.default_restbuilder_timeout` (`10000`) ; `0` le désactive |\n| `encoding` | String | Encodage d'une réponse texte, par défaut `utf8` ; `binary` renvoie un `Buffer` |\n| `custom` | Boolean | Renvoie `response.stream` au lieu de lire le corps |\n| `noredirect` | Boolean | Ne suit pas les redirections `301` et `302` |\n| `keepalive` | Boolean | Réutilise les connexions (pas avec un proxy) |\n| `proxy` | String | Un serveur proxy, par exemple `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Résout le nom d'hôte une seule fois et met l'adresse en cache |\n| `xhr` | Boolean | Ajoute `X-Requested-With: XMLHttpRequest` |\n| `unixsocket` | Object | `{ socket, path }` envoie la requête à un socket Unix au lieu de `url` |\n| `key`, `cert`, `dhparam` | Buffer | Certificat client TLS |\n| `insecure` | Boolean | Accepte les certificats TLS invalides |\n| `compress` | String | Compresse le corps avec `gzip` ou `deflate` et définit `Content-Encoding` |\n| `encrypt` | String | Chiffre le corps avec cette clé (en-tête `X-Encryption`) et déchiffre une réponse texte |\n| `onprogress` | Function | `fn(percentage)` pendant le téléchargement du corps |\n| `ondata` | Function | `fn(chunk, percentage)` pour chaque fragment |\n| `callback` | Function | Identique à l'argument `callback` |\n\n**Réponse** : `status`, `headers`, `body`, `host`, `origin` (les adresses résolues, avec `resolve`) et `cookies` ; avec `custom: true`, `stream` au lieu de `body`. Erreurs : `Invalid hostname`, le texte du statut `408` après un dépassement du délai, `Too many redirects` après quatre redirections, ou une erreur réseau (`status` vaut alors `0`).\n\nExample: GET avec un callback\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: POST JSON avec une promesse\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Lire un flux\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nTélécharge une URL dans un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Une URL absolue ou relative, ou `{ socket, path }`. |\n| `filename` | `String` | yes |  | Le fichier cible. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Millisecondes. |\n\nReturns: `Promise|undefined` Une promesse de la réponse quand tu ne passes pas de callback.\n\nEnvoie une requête `GET` et écrit le corps de la réponse dans `filename`. Le callback s'exécute quand le fichier est écrit. Sans callback, la méthode renvoie une promesse.\n\nUne URL relative (par exemple `/sitemap.xml`) est demandée à ton propre application ; tant que l'application n'est pas chargée, l'appel attend. Un objet `{ socket, path }` à la place de l'URL envoie la requête à un socket Unix.\n\nLa réponse contient `status`, `headers` et `filename`. Le code de statut n'est pas vérifié : le fichier est écrit même pour `404`.\n\nExample: Enregistrer une image\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: Avec await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrée un builder pour une requête `GET`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n| `data` | `Object` | no |  | Arguments de la query string. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\n`data` devient la query string de l'URL. Envoie la requête avec `callback()`, `exec()`, `promise()` ou `stream()`.\n\nExample: Charger une liste\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrée un builder pour une requête `POST`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n| `data` | `Object` | no |  | Le corps, envoyé en JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nLes données sont envoyées en JSON. Appelle `urlencoded()` ou `xml()` pour envoyer un autre format.\n\nExample: Requête POST\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrée un builder pour une requête `PUT`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n| `data` | `Object` | no |  | Le corps, envoyé en JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nLes données sont envoyées en JSON.\n\nExample: Requête PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrée un builder pour une requête `PATCH`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n| `data` | `Object` | no |  | Le corps, envoyé en JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nLes données sont envoyées en JSON.\n\nExample: Requête PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrée un builder pour une requête `DELETE`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n| `data` | `Object` | no |  | Le corps, envoyé en JSON. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nLes données éventuelles sont envoyées en JSON.\n\nExample: Requête DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nCrée un builder pour une requête `HEAD`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nLis la réponse dans `output.status` et `output.headers` dans le callback.\n\nExample: Le fichier existe-t-il ?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nAppelle une opération d'un point d'accès d'API Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse du point d'accès d'API. |\n| `name` | `String` | yes |  | Le nom de l'opération, avec ses paramètres (par exemple `products_read/P01`). |\n| `data` | `Object` | no |  | Les données de l'opération. |\n\nReturns: `RESTBuilder` Un nouveau builder.\n\nEnvoie un `POST` avec le corps JSON `{ schema: name, data: data }`, le format que lisent les routes d'API Total.js.\n\nExample: Appeler une opération\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrée un builder vide et le passe à une fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` Le nouveau builder.\n\n`fn(builder)` définit l'URL, la méthode et tout le reste. `RESTBuilder.url(url)` crée un builder avec seulement une URL, et la méthode d'instance `builder.make(fn)` appelle `fn` avec le builder comme `this` et comme argument.\n\nExample: Construire la requête\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nModifie chaque builder avant qu'il n'envoie sa requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` s'exécute dans `exec()` pour chaque builder de l'application, après la préparation du corps et avant l'envoi de la requête. Enregistre-la une seule fois, dans un fichier de définition.\n\nExample: Ajouter un en-tête à toutes les requêtes\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nEnregistre une fonction qui modifie les réponses analysées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la transformation. |\n| `fn` | `Function` | yes |  | `function(value, output)` qui renvoie la nouvelle valeur. |\n| `isDefault` | `Boolean` | no | `false` | L'utiliser pour tous les builders. |\n\nReturns: `undefined`\n\n`fn(value, output)` s'exécute avec le builder comme `this` et renvoie la nouvelle valeur. Un builder l'utilise après `setTransform(name)` ; avec `isDefault`, chaque nouveau builder l'utilise. `RESTBuilder.setDefaultTransform(name)` change la transformation par défaut et `RESTBuilder.setDefaultTransform()` la supprime. La transformation ne s'exécute pas quand la réponse est un tableau d'erreurs Total.js qui devient `err`.\n\nExample: Extraire une enveloppe data\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nLit ou définit l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'adresse. |\n\nReturns: `RESTBuilder|String` Le builder, ou l'URL quand elle est appelée sans argument.\n\nSans argument, elle renvoie l'URL actuelle.\n\nExample: Définir l'URL\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nDéfinit la méthode HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | Par exemple `POST` ou `put`. |\n| `data` | `Object` | no |  | Le corps, envoyé en JSON. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLes noms en minuscules sont convertis en majuscules. `data` est envoyé en JSON.\n\nExample: Choisir la méthode\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nPasse en `GET` et définit la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Arguments de la query string. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`data` remplace la query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nPasse en `POST` et définit le corps.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Le corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLe corps conserve le type défini auparavant (`urlencoded()`, `xml()`), sinon il est en JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nPasse en `PUT` et définit le corps.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Le corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`builder.patch([data])` et `builder.delete([data])` fonctionnent de la même façon avec `PATCH` et `DELETE` ; `builder.head()` passe en `HEAD`. Chacune a un alias en majuscules (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT et DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nDéfinit un en-tête de la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'en-tête. |\n| `value` | `String` | yes |  | La valeur. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nPour un jeton CSRF, tu peux aussi utiliser `builder.csrf(value)` (`X-Csrf-Token`), et `builder.origin(value)` pour `Origin`.\n\nExample: En-tête de jeton\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nDéfinit l'en-tête `Content-Type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le type de contenu. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nIl remplace le type que définissent `json()`, `xml()` et les autres méthodes de corps.\n\nExample: Type personnalisé\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nDéfinit l'en-tête `Accept`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Une extension ou un type de contenu. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUne valeur courte est une extension (`json`, `xml`) et est convertie en son type de contenu ; une valeur plus longue est utilisée telle quelle.\n\nExample: Demander du XML\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nDéfinit l'en-tête `Authorization`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | Le nom d'utilisateur, ou la valeur complète de l'en-tête. |\n| `password` | `String` | no |  | Le mot de passe. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nAvec un mot de passe, elle crée une authentification Basic. Sans mot de passe, `user` est la valeur complète, par exemple `Bearer TOKEN`.\n\nExample: Basic et Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nAjoute un cookie à la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom. |\n| `value` | `String` | yes |  | La valeur. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`builder.cookies(obj)` remplace tous les cookies par un objet `{ name: value }`.\n\nExample: Envoyer un cookie de session\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nCollecte les cookies des réponses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` le désactive. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLes cookies définis par le serveur, y compris pendant les redirections, sont stockés dans l'objet de `cookies()` et renvoyés par `output.cookie(name)`. Passe le même objet au builder suivant pour conserver une session.\n\nExample: Conserver une session\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nEnvoie le corps en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Le corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUn `GET` devient un `POST`.\n\nExample: Corps JSON\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nEnvoie le corps en `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Le corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUn `GET` devient un `POST`. Un objet est encodé comme un formulaire.\n\nExample: Corps de formulaire\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nEnvoie le corps en XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | Le XML. |\n| `replace` | `Boolean` | no | `false` | Passé à `parseXML()` pour la réponse. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nDéfinit `Content-Type: text/xml` ; un `GET` devient un `POST`. Envoie le XML sous forme de chaîne. Une réponse XML est analysée avec `String.parseXML()` ; `replace` est son argument.\n\nExample: Appel de type SOAP\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nEnvoie un corps texte et renvoie la réponse sous forme de texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Le corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nDéfinit `Content-Type: text/plain`. La réponse n'est pas analysée : `response` est le corps brut.\n\nExample: Lire du texte\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nDéfinit le corps et son type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | Le corps. |\n| `type` | `String` | yes |  | Le type du corps. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`type` vaut `json`, `urlencoded`, `xml`, `plain`, `html` ou `raw` (`application/octet-stream`). Un objet est sérialisé à l'envoi de la requête, sauf pour le type `raw` : envoies-y une chaîne ou un `Buffer`.\n\nExample: Corps binaire\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nDéfinit un champ du corps.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Le champ, ou un objet de champs. |\n| `value` | `Object` | no |  | La valeur. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`name` peut être un objet avec plusieurs champs. `builder.rem(name)` supprime un champ. Avec `file()`, les champs sont envoyés comme champs de formulaire.\n\nExample: Champs\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAjoute un fichier à envoyer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du champ de formulaire. |\n| `filename` | `String` | yes |  | Le nom du fichier. |\n| `source` | `Buffer|String` | no |  | Le contenu, un chemin ou une URL. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLa requête devient `multipart/form-data`, et un `GET` devient un `POST`. `source` est un `Buffer`, un chemin ou une URL ; une URL est téléchargée puis transmise. Sans `source`, `filename` est lu comme un chemin et seul son nom est envoyé. Le type de contenu est déduit de l'extension de `filename`.\n\nExample: Envoyer deux fichiers\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nDéfinit le délai d'expiration.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Millisecondes. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLa valeur par défaut d'un builder est `10000`. Après le délai, `err` est le texte du statut `408`.\n\nExample: Délai court\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nRéutilise les connexions.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLa requête utilise un agent keep-alive partagé. Sans effet avec un proxy.\n\nExample: Nombreux appels vers un même hôte\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nEnvoie la requête via un serveur proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Par exemple `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nL'URL peut contenir des identifiants. Pour toutes les requêtes, définis `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nDéfinit un certificat client TLS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | La clé privée. |\n| `cert` | `Buffer` | yes |  | Le certificat. |\n| `dhparam` | `Buffer` | no |  | Paramètres Diffie-Hellman. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUtilise-la pour les services qui exigent des certificats clients. `builder.insecure()` accepte les certificats serveur invalides (uniquement pour les tests).\n\nExample: Certificat client\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDésactive le cache DNS pour cette requête.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUn builder résout le nom d'hôte une seule fois et conserve l'adresse ; cette méthode le fait résoudre normalement. Les adresses locales ne sont jamais mises en cache.\n\nExample: DNS frais\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nActive ou désactive le suivi des redirections.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Suivre les redirections. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`redirect(false)` renvoie la réponse `301` ou `302` elle-même. Les redirections sont suivies par défaut.\n\nExample: Lire l’emplacement\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nEnvoie la requête à un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Le chemin du fichier socket. |\n| `path` | `String` | yes |  | Le chemin de la requête. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUne URL définie auparavant devient le chemin.\n\nExample: Service local\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nAjoute `X-Requested-With: XMLHttpRequest`.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nDéfinit l'en-tête `Referer`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | L'URL. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nChiffre le corps et déchiffre la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | La clé. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUtilise le chiffrement du framework avec `key`, ou `DEF.secret_encryption`, et ajoute `X-Encryption`. Les deux côtés doivent utiliser la même clé.\n\nExample: Appel chiffré\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nMet en cache une réponse réussie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | Par exemple `5 minutes`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nUne réponse avec le statut `200` est stockée dans `F.cache` pendant `expire` ; la clé est construite à partir de l'URL et du corps. `builder.nocache()` ignore le cache pour un appel.\n\nExample: Mettre en cache des taux\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nValide la réponse avec un schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du schéma. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLe callback reçoit le modèle créé par le schéma. Les erreurs du schéma et un code de statut `400` ou supérieur reviennent dans `err`. La méthode lève une exception quand le schéma n'existe pas.\n\nExample: Valider la réponse\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nConserve et convertit les champs sélectionnés de la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | Par exemple `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`map` liste des paires `field:type` séparées par des virgules. Une troisième partie renomme le champ : `source:type:target`. Cela fonctionne pour un objet et pour un tableau d'objets.\n\nExample: Mapper une liste\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nConvertit des champs de la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Par exemple `price:number,date:date`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nLa réponse passe par `CONVERT(value, schema)`. Ne s'exécute pas en même temps que `schema()`.\n\nExample: Convertir les types\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nTraite les codes de statut `400` et supérieurs comme des erreurs.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`err` est alors le code de statut. Sans cela, tu dois vérifier `output.status` toi-même.\n\nExample: Échouer sur 404\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nRenvoie le corps brut sans l'analyser.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`response` est le corps sous forme de texte (ou un `Buffer` pour les types binaires).\n\nExample: JSON brut\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nUtilise une transformation enregistrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la transformation. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nVoir `RESTBuilder.addTransform()`.\n\nExample: Utiliser une transformation\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nIndique la progression du téléchargement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`fn(percentage)` s'exécute pour chaque fragment. Elle nécessite l'en-tête `Content-Length` de la réponse ; sans lui, le pourcentage vaut `0`.\n\nExample: Progression\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nJournalise la requête et la réponse.\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\nAffiche dans la console le statut, la méthode, l'URL, l'erreur et le corps brut.\n\nExample: Débogage\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nEnvoie la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)`, ou `$`. |\n\nReturns: `RESTBuilder|Promise` Le builder, ou une promesse sans fonction.\n\nAvec une fonction, `fn(err, response, output)` s'exécute avec le résultat. Sans fonction, ou avec le `$` d'une opération de schéma, la méthode renvoie une promesse : avec `$`, une erreur va à `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promesse\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nEnvoie la requête immédiatement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`callback(err, response, output)` est identique à celui de `callback()` ; `exec()` envoie immédiatement, `callback()` au tick suivant.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nEnvoie la requête et renvoie une promesse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Les options d'une opération. |\n\nReturns: `Promise` Une promesse de la réponse analysée.\n\nLa promesse est résolue avec la réponse analysée. Avec `$` (les options d'une opération de schéma), une erreur est passée à `$.invalid()` et la promesse ne se termine pas ; sans lui, la promesse est rejetée.\n\nExample: Dans une opération\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nEnvoie la requête et renvoie la réponse sous forme de flux.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Le builder, pour l'enchaînement.\n\n`callback(err, response)` reçoit `status`, `headers`, `origin` et `stream` (le message entrant). Le corps n'est ni lu ni analysé.\n\nExample: Rediriger vers un fichier\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nLit un cookie de la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du cookie. |\n\nReturns: `String` La valeur.\n\n`output` est le troisième argument du callback. La méthode lit les en-têtes `Set-Cookie`, ou les cookies collectés par `cook()`, et renvoie la valeur décodée ou une chaîne vide.\n\nExample: Lire un cookie\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JabmGj3li60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Richieste HTTP","summary":"RESTBuilder, REQUEST() e DOWNLOAD(): i client per altri servizi HTTP.","markdown":"---\ntitle: Richieste HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# Richieste HTTP\n\n> RESTBuilder, REQUEST() e DOWNLOAD(): i client per altri servizi HTTP.\n\nLe funzioni globali e i metodi di `RESTBuilder` che inviano richieste ad altri servizi. La guida [Richieste HTTP](../../guides/http-requests/) spiega come usarli con esempi; questa pagina è la reference esatta.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nInvia una richiesta HTTP e restituisce la risposta grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Le opzioni della richiesta (vedi la tabella). |\n| `callback` | `Function` | no |  | `function(err, response)`. Senza di essa il metodo restituisce una promise. |\n\nReturns: `Promise|undefined` Una promise della risposta quando non passi una callback.\n\nIl client HTTP di basso livello del framework; lo usano `RESTBuilder` e `DOWNLOAD()`. Senza callback restituisce una promise della risposta.\n\n**Opzioni**\n\n| Opzione | Tipo | Descrizione |\n| --- | --- | --- |\n| `url` | String | L'indirizzo (`http://` o `https://`) |\n| `method` | String | Il metodo HTTP, predefinito `GET` |\n| `headers` | Object | Header della richiesta |\n| `query` | Object/String | Aggiunta all'URL come query string |\n| `body` | String/Buffer | Il corpo; con `files`, un oggetto di campi del form |\n| `type` | String | Imposta `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` o `raw` (`application/octet-stream`) |\n| `files` | Array | File da caricare come `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` o `{ name, filename, url }` |\n| `cookies` | Object | Cookie da inviare, come `{ name: value }` |\n| `cook` | Boolean | Raccoglie i cookie delle risposte (anche dai redirect) in `options.cookies` |\n| `timeout` | Number | Millisecondi; predefinito `CONF.default_restbuilder_timeout` (`10000`); `0` lo disattiva |\n| `encoding` | String | Codifica di una risposta testuale, predefinita `utf8`; `binary` restituisce un `Buffer` |\n| `custom` | Boolean | Restituisce `response.stream` invece di leggere il corpo |\n| `noredirect` | Boolean | Non segue i redirect `301` e `302` |\n| `keepalive` | Boolean | Riutilizza le connessioni (non con un proxy) |\n| `proxy` | String | Un server proxy, ad esempio `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Risolve il nome host una sola volta e mette in cache l'indirizzo |\n| `xhr` | Boolean | Aggiunge `X-Requested-With: XMLHttpRequest` |\n| `unixsocket` | Object | `{ socket, path }` invia la richiesta a un socket Unix invece che a `url` |\n| `key`, `cert`, `dhparam` | Buffer | Certificato client TLS |\n| `insecure` | Boolean | Accetta certificati TLS non validi |\n| `compress` | String | Comprime il corpo con `gzip` o `deflate` e imposta `Content-Encoding` |\n| `encrypt` | String | Cifra il corpo con questa chiave (header `X-Encryption`) e decifra una risposta testuale |\n| `onprogress` | Function | `fn(percentage)` durante il download del corpo |\n| `ondata` | Function | `fn(chunk, percentage)` per ogni chunk |\n| `callback` | Function | Uguale all'argomento `callback` |\n\n**Risposta**: `status`, `headers`, `body`, `host`, `origin` (gli indirizzi risolti, con `resolve`) e `cookies`; con `custom: true`, `stream` invece di `body`. Errori: `Invalid hostname`, il testo dello stato `408` dopo un timeout, `Too many redirects` dopo quattro redirect, oppure un errore di rete (allora `status` è `0`).\n\nExample: GET con una callback\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: POST JSON con una promise\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Leggere uno stream\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nScarica un URL in un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Un URL assoluto o relativo, oppure `{ socket, path }`. |\n| `filename` | `String` | yes |  | Il file di destinazione. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Millisecondi. |\n\nReturns: `Promise|undefined` Una promise della risposta quando non passi una callback.\n\nInvia una richiesta `GET` e scrive il corpo della risposta in `filename`. La callback viene eseguita quando il file è scritto. Senza callback il metodo restituisce una promise.\n\nUn URL relativo (ad esempio `/sitemap.xml`) viene richiesto alla tua applicazione; prima che l'applicazione sia caricata, la chiamata resta in attesa. Un oggetto `{ socket, path }` al posto dell'URL invia la richiesta a un socket Unix.\n\nLa risposta ha `status`, `headers` e `filename`. Il codice di stato non viene controllato: il file viene scritto anche per `404`.\n\nExample: Salvare un'immagine\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: Con await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nCrea un builder per una richiesta `GET`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n| `data` | `Object` | no |  | Argomenti della query string. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\n`data` diventa la query string dell'URL. Invia la richiesta con `callback()`, `exec()`, `promise()` o `stream()`.\n\nExample: Caricare un elenco\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nCrea un builder per una richiesta `POST`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n| `data` | `Object` | no |  | Il corpo, inviato come JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nI dati vengono inviati come JSON. Chiama `urlencoded()` o `xml()` per inviare un altro formato.\n\nExample: Richiesta POST\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nCrea un builder per una richiesta `PUT`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n| `data` | `Object` | no |  | Il corpo, inviato come JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nI dati vengono inviati come JSON.\n\nExample: Richiesta PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nCrea un builder per una richiesta `PATCH`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n| `data` | `Object` | no |  | Il corpo, inviato come JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nI dati vengono inviati come JSON.\n\nExample: Richiesta PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nCrea un builder per una richiesta `DELETE`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n| `data` | `Object` | no |  | Il corpo, inviato come JSON. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nGli eventuali dati vengono inviati come JSON.\n\nExample: Richiesta DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nCrea un builder per una richiesta `HEAD`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nLeggi la risposta da `output.status` e `output.headers` nella callback.\n\nExample: Il file esiste?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nChiama un'operazione di un endpoint API di Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo dell'endpoint API. |\n| `name` | `String` | yes |  | Il nome dell'operazione, con i suoi parametri (ad esempio `products_read/P01`). |\n| `data` | `Object` | no |  | I dati dell'operazione. |\n\nReturns: `RESTBuilder` Un nuovo builder.\n\nInvia un `POST` con il corpo JSON `{ schema: name, data: data }`, il formato letto dalle route API di Total.js.\n\nExample: Chiamare un'operazione\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nCrea un builder vuoto e lo passa a una funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` Il nuovo builder.\n\n`fn(builder)` imposta l'URL, il metodo e tutto il resto. `RESTBuilder.url(url)` crea un builder con il solo URL, e il metodo di istanza `builder.make(fn)` chiama `fn` con il builder come `this` e come argomento.\n\nExample: Costruire la richiesta\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nModifica ogni builder prima che invii la sua richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` viene eseguita in `exec()` per ogni builder dell'applicazione, dopo che il corpo è pronto e prima che la richiesta venga inviata. Registrala una sola volta, in un file di definizione.\n\nExample: Aggiungere un header a tutte le richieste\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nRegistra una funzione che modifica le risposte analizzate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della trasformazione. |\n| `fn` | `Function` | yes |  | `function(value, output)` che restituisce il nuovo valore. |\n| `isDefault` | `Boolean` | no | `false` | Usala per tutti i builder. |\n\nReturns: `undefined`\n\n`fn(value, output)` viene eseguita con `this` come builder e restituisce il nuovo valore. Un builder la usa dopo `setTransform(name)`; con `isDefault`, la usa ogni nuovo builder. `RESTBuilder.setDefaultTransform(name)` cambia quella predefinita e `RESTBuilder.setDefaultTransform()` la rimuove. La trasformazione non viene eseguita quando la risposta è un array di errori Total.js che diventa `err`.\n\nExample: Estrarre i dati da un involucro\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nLegge o imposta l'URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'indirizzo. |\n\nReturns: `RESTBuilder|String` Il builder, oppure l'URL quando viene chiamato senza argomento.\n\nSenza argomento restituisce l'URL corrente.\n\nExample: Impostare l'URL\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nImposta il metodo HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | Ad esempio `POST` o `put`. |\n| `data` | `Object` | no |  | Il corpo, inviato come JSON. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nI nomi in minuscolo vengono convertiti in maiuscolo. `data` viene inviato come JSON.\n\nExample: Scegliere il metodo\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nPassa a `GET` e imposta la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Argomenti della query string. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`data` sostituisce la query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nPassa a `POST` e imposta il corpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Il corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nIl corpo mantiene il tipo impostato in precedenza (`urlencoded()`, `xml()`), altrimenti è JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nPassa a `PUT` e imposta il corpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Il corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`builder.patch([data])` e `builder.delete([data])` funzionano allo stesso modo con `PATCH` e `DELETE`; `builder.head()` passa a `HEAD`. Ognuno ha un alias in maiuscolo (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT e DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nImposta un header della richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'header. |\n| `value` | `String` | yes |  | Il valore. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nPer un token CSRF puoi usare anche `builder.csrf(value)` (`X-Csrf-Token`), e `builder.origin(value)` per `Origin`.\n\nExample: Header con token\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nImposta l'header `Content-Type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il content type. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nSovrascrive il tipo impostato da `json()`, `xml()` e dagli altri metodi del corpo.\n\nExample: Tipo personalizzato\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nImposta l'header `Accept`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Un'estensione o un content type. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUn valore breve è un'estensione (`json`, `xml`) e viene convertito nel suo content type; un valore più lungo viene usato così com'è.\n\nExample: Richiedere XML\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nImposta l'header `Authorization`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | Il nome utente, oppure l'intero valore dell'header. |\n| `password` | `String` | no |  | La password. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nCon una password crea un'autenticazione Basic. Senza, `user` è l'intero valore, ad esempio `Bearer TOKEN`.\n\nExample: Basic e Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nAggiunge un cookie alla richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome. |\n| `value` | `String` | yes |  | Il valore. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`builder.cookies(obj)` sostituisce tutti i cookie con un oggetto `{ name: value }`.\n\nExample: Inviare un cookie di sessione\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nRaccoglie i cookie delle risposte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` la disattiva. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nI cookie impostati dal server, anche durante i redirect, vengono memorizzati nell'oggetto di `cookies()` e restituiti da `output.cookie(name)`. Passa lo stesso oggetto al builder successivo per mantenere una sessione.\n\nExample: Mantenere una sessione\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nInvia il corpo come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Il corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUn `GET` diventa un `POST`.\n\nExample: Corpo JSON\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nInvia il corpo come `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Il corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUn `GET` diventa un `POST`. Un oggetto viene codificato come form.\n\nExample: Corpo di un form\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nInvia il corpo come XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | L'XML. |\n| `replace` | `Boolean` | no | `false` | Passato a `parseXML()` per la risposta. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nImposta `Content-Type: text/xml`; un `GET` diventa un `POST`. Invia l'XML come stringa. Una risposta XML viene analizzata con `String.parseXML()`; `replace` è il suo argomento.\n\nExample: Chiamata in stile SOAP\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nInvia un corpo di testo e restituisce la risposta come testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Il corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nImposta `Content-Type: text/plain`. La risposta non viene analizzata: `response` è il corpo grezzo.\n\nExample: Leggere testo\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nImposta il corpo e il suo tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | Il corpo. |\n| `type` | `String` | yes |  | Il tipo del corpo. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`type` è `json`, `urlencoded`, `xml`, `plain`, `html` o `raw` (`application/octet-stream`). Un oggetto viene serializzato quando la richiesta viene inviata, tranne per il tipo `raw`: in quel caso invia una stringa o un `Buffer`.\n\nExample: Corpo binario\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nImposta un campo del corpo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Il campo, oppure un oggetto di campi. |\n| `value` | `Object` | no |  | Il valore. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`name` può essere un oggetto con più campi. `builder.rem(name)` rimuove un campo. Con `file()`, i campi vengono inviati come campi del form.\n\nExample: Campi\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nAggiunge un file da caricare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del campo del form. |\n| `filename` | `String` | yes |  | Il nome del file. |\n| `source` | `Buffer|String` | no |  | Il contenuto, un percorso o un URL. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nLa richiesta diventa `multipart/form-data`, e un `GET` diventa un `POST`. `source` è un `Buffer`, un percorso o un URL; un URL viene scaricato e inoltrato. Senza `source`, `filename` viene letto come percorso e viene inviato solo il suo nome. Il content type deriva dall'estensione di `filename`.\n\nExample: Caricare due file\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nImposta il timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Millisecondi. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nIl valore predefinito di un builder è `10000`. Dopo il timeout `err` è il testo dello stato `408`.\n\nExample: Timeout breve\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nRiutilizza le connessioni.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nLa richiesta usa un agent keep-alive condiviso. Non ha effetto con un proxy.\n\nExample: Molte chiamate a un solo host\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nInvia la richiesta attraverso un server proxy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Ad esempio `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nL'URL può contenere credenziali. Per tutte le richieste imposta `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nImposta un certificato client TLS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | La chiave privata. |\n| `cert` | `Buffer` | yes |  | Il certificato. |\n| `dhparam` | `Buffer` | no |  | Parametri Diffie-Hellman. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUsalo per i servizi che richiedono certificati client. `builder.insecure()` accetta certificati del server non validi (solo per i test).\n\nExample: Certificato client\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nDisattiva la cache DNS per questa richiesta.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUn builder risolve il nome host una sola volta e conserva l'indirizzo; questo metodo lo fa risolvere come di consueto. Gli indirizzi locali non vengono mai messi in cache.\n\nExample: DNS aggiornato\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nAttiva o disattiva il seguire dei redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Segui i redirect. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`redirect(false)` restituisce la risposta `301` o `302` stessa. Per impostazione predefinita i redirect vengono seguiti.\n\nExample: Leggere la location\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nInvia la richiesta a un socket Unix.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Il percorso del file del socket. |\n| `path` | `String` | yes |  | Il percorso della richiesta. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUn URL impostato in precedenza diventa il percorso.\n\nExample: Servizio locale\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nAggiunge `X-Requested-With: XMLHttpRequest`.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nImposta l'header `Referer`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | L'URL. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nCifra il corpo e decifra la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | La chiave. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUsa la cifratura del framework con `key`, oppure `DEF.secret_encryption`, e aggiunge `X-Encryption`. Entrambe le parti devono usare la stessa chiave.\n\nExample: Chiamata cifrata\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nMette in cache una risposta riuscita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | Ad esempio `5 minutes`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nUna risposta con stato `200` viene memorizzata in `F.cache` per `expire`; la chiave è composta dall'URL e dal corpo. `builder.nocache()` salta la cache per una singola chiamata.\n\nExample: Mettere in cache i tassi\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nValida la risposta con uno schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dello schema. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nLa callback riceve il modello creato dallo schema. Gli errori dello schema e un codice di stato `400` o superiore tornano come `err`. Il metodo lancia un'eccezione quando lo schema non esiste.\n\nExample: Validare la risposta\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nMantiene e converte i campi selezionati della risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | Ad esempio `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`map` elenca coppie `field:type` separate da virgole. Una terza parte rinomina il campo: `source:type:target`. Funziona per un oggetto e per un array di oggetti.\n\nExample: Mappare un elenco\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nConverte i campi della risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Ad esempio `price:number,date:date`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nLa risposta passa attraverso `CONVERT(value, schema)`. Non viene eseguito insieme a `schema()`.\n\nExample: Convertire i tipi\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nTratta i codici di stato `400` e superiori come errori.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nIn questo caso `err` è il codice di stato. Senza, devi controllare tu `output.status`.\n\nExample: Fallire con 404\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nRestituisce il corpo grezzo senza analizzarlo.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`response` è il corpo come testo (o un `Buffer` per i tipi binari).\n\nExample: JSON grezzo\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nUsa una trasformazione registrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della trasformazione. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nVedi `RESTBuilder.addTransform()`.\n\nExample: Usare una trasformazione\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nRiporta l'avanzamento del download.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`fn(percentage)` viene eseguita per ogni chunk. Richiede l'header `Content-Length` della risposta; senza di esso la percentuale è `0`.\n\nExample: Avanzamento\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nRegistra nel log la richiesta e la risposta.\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\nStampa nella console lo stato, il metodo, l'URL, l'errore e il corpo grezzo.\n\nExample: Debug\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nInvia la richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)`, oppure `$`. |\n\nReturns: `RESTBuilder|Promise` Il builder, oppure una promise senza funzione.\n\nCon una funzione, `fn(err, response, output)` viene eseguita con il risultato. Senza funzione, oppure con il `$` di un'operazione di schema, il metodo restituisce una promise: con `$`, un errore va a `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promise\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nInvia subito la richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`callback(err, response, output)` è uguale a quella di `callback()`; `exec()` invia immediatamente, `callback()` al tick successivo.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nInvia la richiesta e restituisce una promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le opzioni di un'operazione. |\n\nReturns: `Promise` Una promise della risposta analizzata.\n\nLa promise si risolve con la risposta analizzata. Con `$` (le opzioni di un'operazione di uno schema), un errore viene passato a `$.invalid()` e la promise non si conclude; senza, la promise viene rifiutata.\n\nExample: In un'operazione\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nInvia la richiesta e restituisce la risposta come stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Il builder, per il concatenamento.\n\n`callback(err, response)` riceve `status`, `headers`, `origin` e `stream` (il messaggio in arrivo). Il corpo non viene letto né analizzato.\n\nExample: Inoltrare in un file\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nLegge un cookie dalla risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del cookie. |\n\nReturns: `String` Il valore.\n\n`output` è il terzo argomento della callback. Il metodo legge gli header `Set-Cookie`, oppure i cookie raccolti da `cook()`, e restituisce il valore decodificato o una stringa vuota.\n\nExample: Leggere un cookie\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JabmGj3li60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/http-requests/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"HTTP požiadavky","summary":"RESTBuilder, REQUEST() a DOWNLOAD(): klienti pre iné HTTP služby.","markdown":"---\ntitle: \"HTTP požiadavky\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/http-requests/\nupdated: 2026-11-16T15:57:56.811Z\n---\n\n# HTTP požiadavky\n\n> RESTBuilder, REQUEST() a DOWNLOAD(): klienti pre iné HTTP služby.\n\nGlobálne funkcie a metódy `RESTBuilder`, ktoré odosielajú požiadavky iným službám. Návod [HTTP požiadavky](../../guides/http-requests/) vysvetľuje na príkladoch, ako ich používať; táto stránka je presná referencia.\n\n## API\n\n### REQUEST(options, [callback])\n\nType: `method`\n\nOdošle HTTP požiadavku a vráti surovú odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | yes |  | Voľby požiadavky (pozri tabuľku). |\n| `callback` | `Function` | no |  | `function(err, response)`. Bez neho metóda vracia promise. |\n\nReturns: `Promise|undefined` Promise s odpoveďou, keď neodovzdáš callback.\n\nNízkoúrovňový HTTP klient frameworku; používajú ho `RESTBuilder` a `DOWNLOAD()`. Bez callbacku vráti promise s odpoveďou.\n\n**Voľby**\n\n| Voľba | Typ | Popis |\n| --- | --- | --- |\n| `url` | String | Adresa (`http://` alebo `https://`) |\n| `method` | String | HTTP metóda, predvolene `GET` |\n| `headers` | Object | Hlavičky požiadavky |\n| `query` | Object/String | Pripojí sa k URL ako query string |\n| `body` | String/Buffer | Telo; s `files` objekt polí formulára |\n| `type` | String | Nastaví `Content-Type`: `json`, `urlencoded`, `xml`, `plain`, `html` alebo `raw` (`application/octet-stream`) |\n| `files` | Array | Súbory na nahratie ako `multipart/form-data`: `{ name, filename, buffer }`, `{ name, filename, path }` alebo `{ name, filename, url }` |\n| `cookies` | Object | Cookies na odoslanie, ako `{ name: value }` |\n| `cook` | Boolean | Zbiera cookies z odpovedí (aj z presmerovaní) do `options.cookies` |\n| `timeout` | Number | Milisekundy; predvolene `CONF.default_restbuilder_timeout` (`10000`); `0` ho vypne |\n| `encoding` | String | Kódovanie textovej odpovede, predvolene `utf8`; `binary` vráti `Buffer` |\n| `custom` | Boolean | Vráti `response.stream` namiesto čítania tela |\n| `noredirect` | Boolean | Nenasleduje presmerovania `301` a `302` |\n| `keepalive` | Boolean | Opätovne používa spojenia (nie s proxy) |\n| `proxy` | String | Proxy server, napríklad `http://user:pass@host:8080` |\n| `resolve` / `dnscache` | Boolean | Preloží názov hostiteľa raz a adresu uloží do cache |\n| `xhr` | Boolean | Pridá `X-Requested-With: XMLHttpRequest` |\n| `unixsocket` | Object | `{ socket, path }` odošle požiadavku na Unix socket namiesto `url` |\n| `key`, `cert`, `dhparam` | Buffer | Klientsky TLS certifikát |\n| `insecure` | Boolean | Prijíma neplatné TLS certifikáty |\n| `compress` | String | Skomprimuje telo pomocou `gzip` alebo `deflate` a nastaví `Content-Encoding` |\n| `encrypt` | String | Zašifruje telo týmto kľúčom (hlavička `X-Encryption`) a dešifruje textovú odpoveď |\n| `onprogress` | Function | `fn(percentage)` počas sťahovania tela |\n| `ondata` | Function | `fn(chunk, percentage)` pre každý chunk |\n| `callback` | Function | To isté ako argument `callback` |\n\n**Odpoveď**: `status`, `headers`, `body`, `host`, `origin` (preložené adresy, s `resolve`) a `cookies`; s `custom: true` je namiesto `body` `stream`. Chyby: `Invalid hostname`, text stavu `408` po timeoute, `Too many redirects` po štyroch presmerovaniach alebo sieťová chyba (vtedy je `status` `0`).\n\nExample: GET s callbackom\n```js\nREQUEST({ url: 'https://api.example.com/status/', timeout: 5000 }, function(err, response) {\n\tif (err) {\n\t\tconsole.log(err);\n\t\treturn;\n\t}\n\tconsole.log(response.status, response.body);\n});\n```\n\nExample: POST JSON s promise\n```js\nvar response = await REQUEST({\n\turl: 'https://api.example.com/items/',\n\tmethod: 'POST',\n\ttype: 'json',\n\tbody: JSON.stringify({ name: 'Item' })\n});\nvar data = response.body.parseJSON();\n```\n\nExample: Čítanie streamu\n```js\nREQUEST({ url: 'https://www.example.com/big.csv', custom: true }, function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('big.csv')));\n});\n```\n\n### DOWNLOAD(url, filename, [callback], [timeout])\n\nType: `method`\n\nStiahne URL do súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String|Object` | yes |  | Absolútna alebo relatívna URL, alebo `{ socket, path }`. |\n| `filename` | `String` | yes |  | Cieľový súbor. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n| `timeout` | `Number` | no | `CONF.default_restbuilder_timeout` | Milisekundy. |\n\nReturns: `Promise|undefined` Promise s odpoveďou, keď neodovzdáš callback.\n\nOdošle požiadavku `GET` a zapíše telo odpovede do `filename`. Callback sa spustí po zapísaní súboru. Bez callbacku metóda vracia promise.\n\nRelatívna URL (napríklad `/sitemap.xml`) sa vyžiada z tvojej vlastnej aplikácie; kým aplikácia nie je načítaná, volanie čaká. Objekt `{ socket, path }` namiesto URL odošle požiadavku na Unix socket.\n\nOdpoveď obsahuje `status`, `headers` a `filename`. Stavový kód sa nekontroluje: súbor sa zapíše aj pri `404`.\n\nExample: Uloženie obrázka\n```js\nDOWNLOAD('https://www.example.com/logo.png', PATH.public('img/logo.png'), function(err, response) {\n\tif (err || response.status !== 200)\n\t\tconsole.log('Download failed');\n});\n```\n\nExample: S await\n```js\nvar response = await DOWNLOAD('https://www.example.com/data.json', PATH.databases('data.json'), null, 30000);\n```\n\n### RESTBuilder.GET(url, [data])\n\nType: `method`\n\nVytvorí builder pre požiadavku `GET`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n| `data` | `Object` | no |  | Argumenty query stringu. |\n\nReturns: `RESTBuilder` Nový builder.\n\n`data` sa stane query stringom URL. Požiadavku odošleš pomocou `callback()`, `exec()`, `promise()` alebo `stream()`.\n\nExample: Načítanie zoznamu\n```js\nRESTBuilder.GET('https://api.example.com/products/', { page: 2, limit: 50 }).callback(function(err, response) {\n\t// GET https://api.example.com/products/?page=2&limit=50\n\tconsole.log(response);\n});\n```\n\n### RESTBuilder.POST(url, [data])\n\nType: `method`\n\nVytvorí builder pre požiadavku `POST`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n| `data` | `Object` | no |  | Telo, odoslané ako JSON. |\n\nReturns: `RESTBuilder` Nový builder.\n\nDáta sa odošlú ako JSON. Zavolaj `urlencoded()` alebo `xml()`, ak chceš odoslať iný formát.\n\nExample: Požiadavka POST\n```js\nRESTBuilder.POST('https://api.example.com/products/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PUT(url, [data])\n\nType: `method`\n\nVytvorí builder pre požiadavku `PUT`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n| `data` | `Object` | no |  | Telo, odoslané ako JSON. |\n\nReturns: `RESTBuilder` Nový builder.\n\nDáta sa odošlú ako JSON.\n\nExample: Požiadavka PUT\n```js\nRESTBuilder.PUT('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.PATCH(url, [data])\n\nType: `method`\n\nVytvorí builder pre požiadavku `PATCH`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n| `data` | `Object` | no |  | Telo, odoslané ako JSON. |\n\nReturns: `RESTBuilder` Nový builder.\n\nDáta sa odošlú ako JSON.\n\nExample: Požiadavka PATCH\n```js\nRESTBuilder.PATCH('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.DELETE(url, [data])\n\nType: `method`\n\nVytvorí builder pre požiadavku `DELETE`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n| `data` | `Object` | no |  | Telo, odoslané ako JSON. |\n\nReturns: `RESTBuilder` Nový builder.\n\nDáta, ak nejaké sú, sa odošlú ako JSON.\n\nExample: Požiadavka DELETE\n```js\nRESTBuilder.DELETE('https://api.example.com/products/P01/', { name: 'Bike', price: 150 }).callback(function(err, response, output) {\n\tconsole.log(output.status, response);\n});\n```\n\n### RESTBuilder.HEAD(url)\n\nType: `method`\n\nVytvorí builder pre požiadavku `HEAD`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa. |\n\nReturns: `RESTBuilder` Nový builder.\n\nOdpoveď prečítaš v callbacku z `output.status` a `output.headers`.\n\nExample: Existuje súbor?\n```js\nRESTBuilder.HEAD('https://cdn.example.com/files/report.pdf').callback(function(err, response, output) {\n\tconsole.log(output.status === 200, output.headers['content-length']);\n});\n```\n\n### RESTBuilder.API(url, name, [data])\n\nType: `method`\n\nZavolá operáciu API endpointu Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa API endpointu. |\n| `name` | `String` | yes |  | Názov operácie s jej parametrami (napríklad `products_read/P01`). |\n| `data` | `Object` | no |  | Dáta operácie. |\n\nReturns: `RESTBuilder` Nový builder.\n\nOdošle `POST` s telom JSON `{ schema: name, data: data }`, čo je formát, ktorý čítajú API routy Total.js.\n\nExample: Volanie operácie\n```js\nRESTBuilder.API('https://app.example.com/admin/', 'products_save', { name: 'Bike' }).callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\n### RESTBuilder.make(fn)\n\nType: `method`\n\nVytvorí prázdny builder a odovzdá ho funkcii.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `RESTBuilder` Nový builder.\n\n`fn(builder)` nastaví URL, metódu a všetko ostatné. `RESTBuilder.url(url)` vytvorí builder iba s URL a metóda inštancie `builder.make(fn)` zavolá `fn` s builderom ako `this` aj ako argumentom.\n\nExample: Zostavenie požiadavky\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01' });\n\tbuilder.header('X-Token', CONF.token);\n\tbuilder.callback(console.log);\n});\n```\n\n### RESTBuilder.upgrade(fn)\n\nType: `method`\n\nZmení každý builder pred odoslaním jeho požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `undefined`\n\n`fn(builder)` sa spustí v `exec()` pre každý builder aplikácie, po príprave tela a pred odoslaním požiadavky. Zaregistruj ju raz, v súbore definícií.\n\nExample: Pridanie hlavičky do všetkých požiadaviek\n```js\n// definitions/restbuilder.js\nRESTBuilder.upgrade(function(builder) {\n\tbuilder.header('X-App', 'eshop');\n});\n```\n\n### RESTBuilder.addTransform(name, fn, [isDefault])\n\nType: `method`\n\nZaregistruje funkciu, ktorá mení spracované odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov transformácie. |\n| `fn` | `Function` | yes |  | `function(value, output)`, ktorá vráti novú hodnotu. |\n| `isDefault` | `Boolean` | no | `false` | Použiť ju pre všetky buildery. |\n\nReturns: `undefined`\n\n`fn(value, output)` sa spustí s `this` ako builderom a vráti novú hodnotu. Builder ju použije po `setTransform(name)`; s `isDefault` ju použije každý nový builder. `RESTBuilder.setDefaultTransform(name)` zmení predvolenú transformáciu a `RESTBuilder.setDefaultTransform()` ju odstráni. Transformácia sa nespustí, keď je odpoveď pole chýb Total.js, ktoré sa stane `err`.\n\nExample: Rozbalenie dátovej obálky\n```js\nRESTBuilder.addTransform('envelope', function(value, output) {\n\treturn value && value.data ? value.data : value;\n});\n\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.url([url])\n\nType: `method`\n\nPrečíta alebo nastaví URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Adresa. |\n\nReturns: `RESTBuilder|String` Builder alebo URL pri volaní bez argumentu.\n\nBez argumentu vráti aktuálnu URL.\n\nExample: Nastavenie URL\n```js\nvar builder = RESTBuilder.GET('https://api.example.com/');\nbuilder.url('https://api.example.com/v2/products/');\n```\n\n### builder.method(method, [data])\n\nType: `method`\n\nNastaví HTTP metódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `method` | `String` | yes |  | Napríklad `POST` alebo `put`. |\n| `data` | `Object` | no |  | Telo, odoslané ako JSON. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nNázvy malými písmenami sa prevedú na veľké. `data` sa odošlú ako JSON.\n\nExample: Výber metódy\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.method('PUT', { price: 20 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.get([data])\n\nType: `method`\n\nPrepne na `GET` a nastaví query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Argumenty query stringu. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`data` nahradí query. Alias `builder.GET()`.\n\nExample: Query\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/search/');\n\tbuilder.get({ q: 'bike' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.post([data])\n\nType: `method`\n\nPrepne na `POST` a nastaví telo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Telo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nTelo si ponechá typ nastavený predtým (`urlencoded()`, `xml()`), inak je to JSON. Alias `builder.POST()`.\n\nExample: POST\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/orders/');\n\tbuilder.post({ product: 'P01', count: 1 });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.put([data])\n\nType: `method`\n\nPrepne na `PUT` a nastaví telo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Telo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`builder.patch([data])` a `builder.delete([data])` fungujú rovnako s `PATCH` a `DELETE`; `builder.head()` prepne na `HEAD`. Každá má alias veľkými písmenami (`PUT()`, `PATCH()`, `DELETE()`, `HEAD()`).\n\nExample: PUT a DELETE\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P01/');\n\tbuilder.put({ price: 20 });\n\tbuilder.callback(console.log);\n});\n\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/P02/');\n\tbuilder.delete();\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.header(name, value)\n\nType: `method`\n\nNastaví hlavičku požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov hlavičky. |\n| `value` | `String` | yes |  | Hodnota. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPre CSRF token môžeš použiť aj `builder.csrf(value)` (`X-Csrf-Token`) a `builder.origin(value)` pre `Origin`.\n\nExample: Hlavička s tokenom\n```js\nRESTBuilder.GET('https://api.example.com/me/').header('X-Token', CONF.token).callback(console.log);\n```\n\n### builder.type(value)\n\nType: `method`\n\nNastaví hlavičku `Content-Type`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Typ obsahu. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPrepíše typ, ktorý nastavia `json()`, `xml()` a ostatné metódy pre telo.\n\nExample: Vlastný typ\n```js\nRESTBuilder.POST('https://api.example.com/events/').raw(JSON.stringify(data), 'json').type('application/vnd.api+json').callback(console.log);\n```\n\n### builder.accept(type)\n\nType: `method`\n\nNastaví hlavičku `Accept`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Prípona alebo typ obsahu. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nKrátka hodnota je prípona (`json`, `xml`) a prevedie sa na svoj typ obsahu; dlhšia hodnota sa použije tak, ako je.\n\nExample: Žiadosť o XML\n```js\nRESTBuilder.GET('https://api.example.com/feed/').accept('xml').callback(console.log);\n```\n\n### builder.auth(user, [password])\n\nType: `method`\n\nNastaví hlavičku `Authorization`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `user` | `String` | yes |  | Meno používateľa alebo celá hodnota hlavičky. |\n| `password` | `String` | no |  | Heslo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nS heslom vytvorí Basic autentifikáciu. Bez neho je `user` celá hodnota, napríklad `Bearer TOKEN`.\n\nExample: Basic a Bearer\n```js\nRESTBuilder.GET('https://api.example.com/').auth('admin', 'secret').callback(console.log);\nRESTBuilder.GET('https://api.example.com/').auth('Bearer ' + CONF.token).callback(console.log);\n```\n\n### builder.cookie(name, value)\n\nType: `method`\n\nPridá cookie do požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov. |\n| `value` | `String` | yes |  | Hodnota. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`builder.cookies(obj)` nahradí všetky cookies objektom `{ name: value }`.\n\nExample: Odoslanie session cookie\n```js\nRESTBuilder.GET('https://www.example.com/account/').cookie('session', token).callback(console.log);\n```\n\n### builder.cook([enable])\n\nType: `method`\n\nZbiera cookies z odpovedí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | no | `true` | `false` to vypne. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nCookies nastavené serverom, aj počas presmerovaní, sa uložia do objektu z `cookies()` a vracia ich `output.cookie(name)`. Odovzdaj ten istý objekt ďalšiemu builderu, aby si zachoval session.\n\nExample: Zachovanie session\n```js\nvar jar = {};\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).cookies(jar).cook().callback(function(err, response, output) {\n\tRESTBuilder.GET('https://www.example.com/account/').cookies(jar).callback(console.log);\n});\n```\n\n### builder.json([data])\n\nType: `method`\n\nOdošle telo ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Telo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nZ `GET` sa stane `POST`.\n\nExample: Telo JSON\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://api.example.com/items/');\n\tbuilder.json({ name: 'Item' });\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.urlencoded([data])\n\nType: `method`\n\nOdošle telo ako `application/x-www-form-urlencoded`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object|String` | no |  | Telo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nZ `GET` sa stane `POST`. Objekt sa zakóduje ako formulár.\n\nExample: Telo formulára\n```js\nRESTBuilder.POST('https://www.example.com/contact/').urlencoded({ email: 'info@example.com', message: 'Hello' }).callback(console.log);\n```\n\n### builder.xml([data], [replace])\n\nType: `method`\n\nOdošle telo ako XML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `String` | no |  | XML. |\n| `replace` | `Boolean` | no | `false` | Odovzdá sa do `parseXML()` pre odpoveď. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nNastaví `Content-Type: text/xml`; z `GET` sa stane `POST`. XML odošli ako reťazec. Odpoveď XML sa spracuje pomocou `String.parseXML()`; `replace` je jeho argument.\n\nExample: Volanie v štýle SOAP\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.url('https://service.example.com/rates/');\n\tbuilder.xml('<request><currency>EUR</currency></request>');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.plain([value])\n\nType: `method`\n\nOdošle textové telo a vráti odpoveď ako text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Telo. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nNastaví `Content-Type: text/plain`. Odpoveď sa nespracúva: `response` je surové telo.\n\nExample: Čítanie textu\n```js\nRESTBuilder.GET('https://www.example.com/robots.txt').plain().callback(function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### builder.raw(value, type)\n\nType: `method`\n\nNastaví telo a jeho typ.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object|String|Buffer` | yes |  | Telo. |\n| `type` | `String` | yes |  | Typ tela. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`type` je `json`, `urlencoded`, `xml`, `plain`, `html` alebo `raw` (`application/octet-stream`). Objekt sa serializuje pri odoslaní požiadavky, okrem typu `raw`: tam odošli reťazec alebo `Buffer`.\n\nExample: Binárne telo\n```js\nRESTBuilder.POST('https://api.example.com/blob/').raw(buffer, 'raw').callback(console.log);\n```\n\n### builder.set(name, [value])\n\nType: `method`\n\nNastaví jedno pole tela.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Pole alebo objekt polí. |\n| `value` | `Object` | no |  | Hodnota. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`name` môže byť objekt s viacerými poľami. `builder.rem(name)` odstráni pole. S `file()` sa polia odošlú ako polia formulára.\n\nExample: Polia\n```js\nRESTBuilder.POST('https://api.example.com/items/').set('name', 'Bike').set({ price: 150, stock: 3 }).callback(console.log);\n```\n\n### builder.file(name, filename, [source])\n\nType: `method`\n\nPridá súbor na nahratie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poľa formulára. |\n| `filename` | `String` | yes |  | Názov súboru. |\n| `source` | `Buffer|String` | no |  | Obsah, cesta alebo URL. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPožiadavka sa stane `multipart/form-data` a z `GET` sa stane `POST`. `source` je `Buffer`, cesta alebo URL; URL sa stiahne a prepošle. Bez `source` sa `filename` číta ako cesta a odošle sa iba jeho názov. Typ obsahu sa určí z prípony `filename`.\n\nExample: Nahratie dvoch súborov\n```js\nRESTBuilder.POST('https://api.example.com/upload/')\n\t.file('photo', 'photo.jpg', PATH.public('img/photo.jpg'))\n\t.file('data', 'data.json', Buffer.from(JSON.stringify(data)))\n\t.callback(console.log);\n```\n\n### builder.timeout(ms)\n\nType: `method`\n\nNastaví timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ms` | `Number` | yes | `10000` | Milisekundy. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPredvolená hodnota buildera je `10000`. Po timeoute je `err` text stavu `408`.\n\nExample: Krátky timeout\n```js\nRESTBuilder.GET('https://api.example.com/health/').timeout(2000).callback(console.log);\n```\n\n### builder.keepalive()\n\nType: `method`\n\nOpätovne používa spojenia.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPožiadavka používa zdieľaného keep-alive agenta. S proxy nemá žiadny účinok.\n\nExample: Veľa volaní na jeden hostiteľ\n```js\nRESTBuilder.GET('https://api.example.com/items/').keepalive().callback(console.log);\n```\n\n### builder.proxy(url)\n\nType: `method`\n\nOdošle požiadavku cez proxy server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Napríklad `http://user:password@proxy.example.com:8080`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nURL môže obsahovať prihlasovacie údaje. Pre všetky požiadavky nastav `CONF.default_proxy`.\n\nExample: Proxy\n```js\nRESTBuilder.GET('https://api.example.com/').proxy('http://proxy.example.com:3128').callback(console.log);\n```\n\n### builder.cert(key, cert, [dhparam])\n\nType: `method`\n\nNastaví klientsky TLS certifikát.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `Buffer` | yes |  | Súkromný kľúč. |\n| `cert` | `Buffer` | yes |  | Certifikát. |\n| `dhparam` | `Buffer` | no |  | Parametre Diffie-Hellman. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPouži ho pre služby, ktoré vyžadujú klientske certifikáty. `builder.insecure()` prijíma neplatné serverové certifikáty (iba na testovanie).\n\nExample: Klientsky certifikát\n```js\nRESTBuilder.GET('https://bank.example.com/api/')\n\t.cert(Fs.readFileSync(PATH.root('client.key')), Fs.readFileSync(PATH.root('client.crt')))\n\t.callback(console.log);\n```\n\n### builder.nodnscache()\n\nType: `method`\n\nVypne DNS cache pre túto požiadavku.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nBuilder preloží názov hostiteľa raz a adresu si ponechá; toto ho preloží ako zvyčajne. Lokálne adresy sa nikdy neukladajú do cache.\n\nExample: Čerstvé DNS\n```js\nRESTBuilder.GET('https://api.example.com/').nodnscache().callback(console.log);\n```\n\n### builder.redirect(enable)\n\nType: `method`\n\nZapne alebo vypne nasledovanie presmerovaní.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `enable` | `Boolean` | yes |  | Nasledovať presmerovania. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`redirect(false)` vráti samotnú odpoveď `301` alebo `302`. Presmerovania sa predvolene nasledujú.\n\nExample: Čítanie location\n```js\nRESTBuilder.GET('https://short.example.com/abc').redirect(false).callback(function(err, response, output) {\n\tconsole.log(output.headers.location);\n});\n```\n\n### builder.unixsocket(socket, path)\n\nType: `method`\n\nOdošle požiadavku na Unix socket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `socket` | `String` | yes |  | Cesta k súboru socketu. |\n| `path` | `String` | yes |  | Cesta požiadavky. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nURL nastavená predtým sa stane cestou.\n\nExample: Lokálna služba\n```js\nRESTBuilder.make(function(builder) {\n\tbuilder.unixsocket('/var/run/app.sock', '/api/status/');\n\tbuilder.callback(console.log);\n});\n```\n\n### builder.xhr()\n\nType: `method`\n\nPridá `X-Requested-With: XMLHttpRequest`.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nExample: XHR\n```js\nRESTBuilder.GET('https://www.example.com/api/').xhr().callback(console.log);\n```\n\n### builder.referrer(value)\n\nType: `method`\n\nNastaví hlavičku `Referer`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | URL. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nAlias `builder.referer()`.\n\nExample: Referer\n```js\nRESTBuilder.GET('https://www.example.com/page/').referrer('https://www.example.com/').callback(console.log);\n```\n\n### builder.encrypt([key])\n\nType: `method`\n\nZašifruje telo a dešifruje odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `DEF.secret_encryption` | Kľúč. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPoužije šifrovanie frameworku s `key` alebo `DEF.secret_encryption` a pridá `X-Encryption`. Obe strany musia používať rovnaký kľúč.\n\nExample: Šifrované volanie\n```js\nRESTBuilder.POST('https://node2.example.com/sync/', data).encrypt(CONF.sync_key).callback(console.log);\n```\n\n### builder.cache(expire)\n\nType: `method`\n\nUloží úspešnú odpoveď do cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `expire` | `String` | yes |  | Napríklad `5 minutes`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nOdpoveď so stavom `200` sa uloží do `F.cache` na dobu `expire`; kľúč sa vytvorí z URL a tela. `builder.nocache()` vynechá cache pre jedno volanie.\n\nExample: Cache kurzov\n```js\nRESTBuilder.GET('https://api.example.com/rates/').cache('1 hour').callback(console.log);\n```\n\n### builder.schema(name)\n\nType: `method`\n\nOverí odpoveď schémou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov schémy. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nCallback dostane model vytvorený schémou. Chyby schémy a stavový kód `400` alebo vyšší sa vrátia ako `err`. Metóda vyhodí výnimku, keď schéma neexistuje.\n\nExample: Overenie odpovede\n```js\nNEWSCHEMA('Rate', function(schema) {\n\tschema.define('currency', 'String(3)', true);\n\tschema.define('value', Number, true);\n});\n\nRESTBuilder.GET('https://api.example.com/rate/EUR/').schema('Rate').callback(function(err, rate) {\n\tconsole.log(err, rate);\n});\n```\n\n### builder.map(map)\n\nType: `method`\n\nPonechá a skonvertuje vybrané polia odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `map` | `String` | yes |  | Napríklad `id:number,name:string,dtcreated:date:created`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`map` uvádza dvojice `field:type` oddelené čiarkami. Tretia časť pole premenuje: `source:type:target`. Funguje pre objekt aj pre pole objektov.\n\nExample: Mapovanie zoznamu\n```js\nRESTBuilder.GET('https://api.example.com/users/').map('id:number,name:string').callback(function(err, users) {\n\tconsole.log(users);\n});\n```\n\n### builder.convert(schema)\n\nType: `method`\n\nSkonvertuje polia odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Napríklad `price:number,date:date`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nOdpoveď prejde cez `CONVERT(value, schema)`. Nespúšťa sa spolu so `schema()`.\n\nExample: Konverzia typov\n```js\nRESTBuilder.GET('https://api.example.com/order/1/').convert('total:number,created:date').callback(console.log);\n```\n\n### builder.strict()\n\nType: `method`\n\nPovažuje stavové kódy `400` a vyššie za chyby.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPotom je `err` stavový kód. Bez toho musíš `output.status` kontrolovať sám.\n\nExample: Chyba pri 404\n```js\nRESTBuilder.GET('https://api.example.com/items/X/').strict().callback(function(err, response) {\n\tif (err === 404)\n\t\tconsole.log('Not found');\n});\n```\n\n### builder.noparse()\n\nType: `method`\n\nVráti surové telo bez spracovania.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`response` je telo ako text (alebo `Buffer` pri binárnych typoch).\n\nExample: Surový JSON\n```js\nRESTBuilder.GET('https://api.example.com/export/').noparse().callback(function(err, body) {\n\tFs.writeFile(PATH.temp('export.json'), body, NOOP);\n});\n```\n\n### builder.setTransform(name)\n\nType: `method`\n\nPoužije zaregistrovanú transformáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov transformácie. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nPozri `RESTBuilder.addTransform()`.\n\nExample: Použitie transformácie\n```js\nRESTBuilder.GET('https://api.example.com/users/').setTransform('envelope').callback(console.log);\n```\n\n### builder.progress(fn)\n\nType: `method`\n\nHlási priebeh sťahovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(percentage)`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`fn(percentage)` sa spustí pre každý chunk. Potrebuje hlavičku `Content-Length` v odpovedi; bez nej je percento `0`.\n\nExample: Priebeh\n```js\nRESTBuilder.GET('https://www.example.com/large.json').progress(function(percentage) {\n\tconsole.log(percentage.floor(1) + '%');\n}).callback(console.log);\n```\n\n### builder.debug()\n\nType: `method`\n\nZaloguje požiadavku a odpoveď.\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\nVypíše do konzoly stav, metódu, URL, chybu a surové telo.\n\nExample: Ladenie\n```js\nRESTBuilder.GET('https://api.example.com/').debug().callback(console.log);\n```\n\n### builder.callback([fn])\n\nType: `method`\n\nPošle požiadavku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | no |  | `function(err, response, output)` alebo `$`. |\n\nReturns: `RESTBuilder|Promise` Builder, alebo promise bez funkcie.\n\nS funkciou sa spustí `fn(err, response, output)` s výsledkom. Bez funkcie, alebo s `$` operácie schémy, metóda vráti promise: s `$` ide chyba do `$.invalid()`.\n\nExample: Callback\n```js\nRESTBuilder.GET('https://api.example.com/items/').callback(function(err, response, output) {\n\tconsole.log(err, response, output.status);\n});\n```\n\nExample: Promise\n```js\nvar items = await RESTBuilder.GET('https://api.example.com/items/').callback();\n```\n\n### builder.exec([callback])\n\nType: `method`\n\nOdošle požiadavku okamžite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response, output)`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`callback(err, response, output)` je rovnaký ako v `callback()`; `exec()` odošle okamžite, `callback()` v ďalšom ticku.\n\nExample: Exec\n```js\nRESTBuilder.GET('https://api.example.com/ping/').exec(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### builder.promise([$])\n\nType: `method`\n\nOdošle požiadavku a vráti promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Options operácie. |\n\nReturns: `Promise` Promise so spracovanou odpoveďou.\n\nPromise sa splní so spracovanou odpoveďou. S `$` (options operácie schémy) sa chyba odovzdá do `$.invalid()` a promise sa neukončí; bez neho sa promise zamietne.\n\nExample: V operácii\n```js\nschema.action('sync', {\n\tname: 'Sync',\n\taction: async function($) {\n\t\tvar items = await RESTBuilder.GET('https://api.example.com/items/').promise($);\n\t\t$.callback(items);\n\t}\n});\n```\n\n### builder.stream(callback)\n\nType: `method`\n\nOdošle požiadavku a vráti odpoveď ako stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `RESTBuilder` Builder, na reťazenie.\n\n`callback(err, response)` dostane `status`, `headers`, `origin` a `stream` (prichádzajúcu správu). Telo sa nečíta ani nespracúva.\n\nExample: Presmerovanie do súboru\n```js\nRESTBuilder.GET('https://www.example.com/export.csv').stream(function(err, response) {\n\tif (!err)\n\t\tresponse.stream.pipe(Fs.createWriteStream(PATH.temp('export.csv')));\n});\n```\n\n### output.cookie(name)\n\nType: `method`\n\nPrečíta cookie z odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n\nReturns: `String` Hodnota.\n\n`output` je tretí argument callbacku. Metóda prečíta hlavičky `Set-Cookie` alebo cookies zozbierané pomocou `cook()` a vráti dekódovanú hodnotu alebo prázdny reťazec.\n\nExample: Čítanie cookie\n```js\nRESTBuilder.POST('https://www.example.com/login/', { name: 'user', password: 'pass' }).callback(function(err, response, output) {\n\tvar session = output.cookie('session');\n});\n```\n","entries":[{"type":"method","name":"REQUEST()","signature":"REQUEST(options, [callback])","since":"","deprecated":false},{"type":"method","name":"DOWNLOAD()","signature":"DOWNLOAD(url, filename, [callback], [timeout])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.GET()","signature":"RESTBuilder.GET(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.POST()","signature":"RESTBuilder.POST(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PUT()","signature":"RESTBuilder.PUT(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.PATCH()","signature":"RESTBuilder.PATCH(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.DELETE()","signature":"RESTBuilder.DELETE(url, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.HEAD()","signature":"RESTBuilder.HEAD(url)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.API()","signature":"RESTBuilder.API(url, name, [data])","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.make()","signature":"RESTBuilder.make(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.upgrade()","signature":"RESTBuilder.upgrade(fn)","since":"","deprecated":false},{"type":"method","name":"RESTBuilder.addTransform()","signature":"RESTBuilder.addTransform(name, fn, [isDefault])","since":"","deprecated":false},{"type":"method","name":"builder.url()","signature":"builder.url([url])","since":"","deprecated":false},{"type":"method","name":"builder.method()","signature":"builder.method(method, [data])","since":"","deprecated":false},{"type":"method","name":"builder.get()","signature":"builder.get([data])","since":"","deprecated":false},{"type":"method","name":"builder.post()","signature":"builder.post([data])","since":"","deprecated":false},{"type":"method","name":"builder.put()","signature":"builder.put([data])","since":"","deprecated":false},{"type":"method","name":"builder.header()","signature":"builder.header(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.type()","signature":"builder.type(value)","since":"","deprecated":false},{"type":"method","name":"builder.accept()","signature":"builder.accept(type)","since":"","deprecated":false},{"type":"method","name":"builder.auth()","signature":"builder.auth(user, [password])","since":"","deprecated":false},{"type":"method","name":"builder.cookie()","signature":"builder.cookie(name, value)","since":"","deprecated":false},{"type":"method","name":"builder.cook()","signature":"builder.cook([enable])","since":"","deprecated":false},{"type":"method","name":"builder.json()","signature":"builder.json([data])","since":"","deprecated":false},{"type":"method","name":"builder.urlencoded()","signature":"builder.urlencoded([data])","since":"","deprecated":false},{"type":"method","name":"builder.xml()","signature":"builder.xml([data], [replace])","since":"","deprecated":false},{"type":"method","name":"builder.plain()","signature":"builder.plain([value])","since":"","deprecated":false},{"type":"method","name":"builder.raw()","signature":"builder.raw(value, type)","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"builder.file()","signature":"builder.file(name, filename, [source])","since":"","deprecated":false},{"type":"method","name":"builder.timeout()","signature":"builder.timeout(ms)","since":"","deprecated":false},{"type":"method","name":"builder.keepalive()","signature":"builder.keepalive()","since":"","deprecated":false},{"type":"method","name":"builder.proxy()","signature":"builder.proxy(url)","since":"","deprecated":false},{"type":"method","name":"builder.cert()","signature":"builder.cert(key, cert, [dhparam])","since":"","deprecated":false},{"type":"method","name":"builder.nodnscache()","signature":"builder.nodnscache()","since":"","deprecated":false},{"type":"method","name":"builder.redirect()","signature":"builder.redirect(enable)","since":"","deprecated":false},{"type":"method","name":"builder.unixsocket()","signature":"builder.unixsocket(socket, path)","since":"","deprecated":false},{"type":"method","name":"builder.xhr()","signature":"builder.xhr()","since":"","deprecated":false},{"type":"method","name":"builder.referrer()","signature":"builder.referrer(value)","since":"","deprecated":false},{"type":"method","name":"builder.encrypt()","signature":"builder.encrypt([key])","since":"","deprecated":false},{"type":"method","name":"builder.cache()","signature":"builder.cache(expire)","since":"","deprecated":false},{"type":"method","name":"builder.schema()","signature":"builder.schema(name)","since":"","deprecated":false},{"type":"method","name":"builder.map()","signature":"builder.map(map)","since":"","deprecated":false},{"type":"method","name":"builder.convert()","signature":"builder.convert(schema)","since":"","deprecated":false},{"type":"method","name":"builder.strict()","signature":"builder.strict()","since":"","deprecated":false},{"type":"method","name":"builder.noparse()","signature":"builder.noparse()","since":"","deprecated":false},{"type":"method","name":"builder.setTransform()","signature":"builder.setTransform(name)","since":"","deprecated":false},{"type":"method","name":"builder.progress()","signature":"builder.progress(fn)","since":"","deprecated":false},{"type":"method","name":"builder.debug()","signature":"builder.debug()","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback([fn])","since":"","deprecated":false},{"type":"method","name":"builder.exec()","signature":"builder.exec([callback])","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.stream()","signature":"builder.stream(callback)","since":"","deprecated":false},{"type":"method","name":"output.cookie()","signature":"output.cookie(name)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:57:56.811Z"}
{"id":"JafquF2vr60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"OpenClient","summary":"OPENCLIENT(): a WebSocket client for messages to other services.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT(): a WebSocket client for messages to other services.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOpens a shared WebSocket client for request and response messages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The address of the server (`ws://`, `wss://`, `http://` or `https://`). |\n| `id` | `String` | no | `GUID(10)` | The client identifier. |\n\nReturns: `Object` The client.\n\nConnects to `url` over WebSocket (`http` becomes `ws`, `https` becomes `wss`) and reconnects automatically. Clients with the same URL share one connection; the connection closes when its last client is removed. Passing an existing `id` removes the old client with that id first.\n\nThe client has these methods:\n\n- `send(msg, [callback], [timeout])` sends a JSON message. With a callback, the message gets a `callbackid`, and the callback `function(err, response)` runs when the server answers with the same `callbackid` (fields `error` and `response`). While the connection is down it retries every 500 ms, up to ten times, then calls back with `offline`. A timeout gives `timeout`.\n- `rpc(msg, [timeout])` the same as `send()`, but returns a promise.\n- `cmd(msg, [timeout])` sends without waiting for an answer.\n- `message(fn)`, `error(fn)` and `online(fn)` set handlers. `online(meta)` runs with the `init` message of the server, and with `null` when the connection closes.\n- `close()` or `remove()` removes the client.\n\nProperties: `id`, `url`, `connected`, `meta` (the last `init` message).\n\nExample: Ask the server\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JafquF2vr60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"OpenClient","summary":"OPENCLIENT(): ein WebSocket-Client für Nachrichten an andere Dienste.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT(): ein WebSocket-Client für Nachrichten an andere Dienste.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nÖffnet einen gemeinsam genutzten WebSocket-Client für Anfrage- und Antwortnachrichten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Adresse des Servers (`ws://`, `wss://`, `http://` oder `https://`). |\n| `id` | `String` | no | `GUID(10)` | Die Kennung des Clients. |\n\nReturns: `Object` Der Client.\n\nVerbindet sich über WebSocket mit `url` (`http` wird zu `ws`, `https` zu `wss`) und stellt die Verbindung automatisch wieder her. Clients mit derselben URL teilen sich eine Verbindung; die Verbindung wird geschlossen, wenn ihr letzter Client entfernt wird. Wird eine vorhandene `id` übergeben, wird zuerst der alte Client mit dieser ID entfernt.\n\nDer Client hat diese Methoden:\n\n- `send(msg, [callback], [timeout])` sendet eine JSON-Nachricht. Mit Callback erhält die Nachricht eine `callbackid`, und der Callback `function(err, response)` läuft, wenn der Server mit derselben `callbackid` antwortet (Felder `error` und `response`). Solange die Verbindung unterbrochen ist, versucht er es alle 500 ms erneut, bis zu zehnmal, und ruft dann mit `offline` zurück. Ein Timeout ergibt `timeout`.\n- `rpc(msg, [timeout])` wie `send()`, gibt aber ein Promise zurück.\n- `cmd(msg, [timeout])` sendet, ohne auf eine Antwort zu warten.\n- `message(fn)`, `error(fn)` und `online(fn)` setzen Handler. `online(meta)` läuft mit der `init`-Nachricht des Servers und mit `null`, wenn die Verbindung geschlossen wird.\n- `close()` oder `remove()` entfernt den Client.\n\nEigenschaften: `id`, `url`, `connected`, `meta` (die letzte `init`-Nachricht).\n\nExample: Den Server fragen\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JafquF2vr60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"OpenClient","summary":"OPENCLIENT(): un cliente WebSocket para mensajes a otros servicios.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT(): un cliente WebSocket para mensajes a otros servicios.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nAbre un cliente WebSocket compartido para mensajes de petición y respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección del servidor (`ws://`, `wss://`, `http://` o `https://`). |\n| `id` | `String` | no | `GUID(10)` | El identificador del cliente. |\n\nReturns: `Object` El cliente.\n\nSe conecta a `url` por WebSocket (`http` pasa a ser `ws`, `https` pasa a ser `wss`) y se reconecta automáticamente. Los clientes con la misma URL comparten una conexión; la conexión se cierra cuando se elimina su último cliente. Pasar un `id` existente elimina primero el cliente anterior con ese id.\n\nEl cliente tiene estos métodos:\n\n- `send(msg, [callback], [timeout])` envía un mensaje JSON. Con un callback, el mensaje recibe un `callbackid`, y el callback `function(err, response)` se ejecuta cuando el servidor responde con el mismo `callbackid` (campos `error` y `response`). Mientras la conexión está caída, reintenta cada 500 ms, hasta diez veces, y luego llama al callback con `offline`. Un timeout da `timeout`.\n- `rpc(msg, [timeout])` lo mismo que `send()`, pero devuelve una promesa.\n- `cmd(msg, [timeout])` envía sin esperar respuesta.\n- `message(fn)`, `error(fn)` y `online(fn)` definen manejadores. `online(meta)` se ejecuta con el mensaje `init` del servidor, y con `null` cuando se cierra la conexión.\n- `close()` o `remove()` elimina el cliente.\n\nPropiedades: `id`, `url`, `connected`, `meta` (el último mensaje `init`).\n\nExample: Preguntar al servidor\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JafquF2vr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"OpenClient","summary":"OPENCLIENT() : un client WebSocket pour des messages vers d'autres services.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT() : un client WebSocket pour des messages vers d'autres services.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOuvre un client WebSocket partagé pour des messages de requête et de réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse du serveur (`ws://`, `wss://`, `http://` ou `https://`). |\n| `id` | `String` | no | `GUID(10)` | L'identifiant du client. |\n\nReturns: `Object` Le client.\n\nSe connecte à `url` via WebSocket (`http` devient `ws`, `https` devient `wss`) et se reconnecte automatiquement. Les clients ayant la même URL partagent une connexion ; la connexion se ferme quand son dernier client est supprimé. Passer un `id` existant supprime d'abord l'ancien client ayant cet id.\n\nLe client possède ces méthodes :\n\n- `send(msg, [callback], [timeout])` envoie un message JSON. Avec un callback, le message reçoit un `callbackid`, et le callback `function(err, response)` s'exécute quand le serveur répond avec le même `callbackid` (champs `error` et `response`). Tant que la connexion est coupée, il réessaie toutes les 500 ms, jusqu'à dix fois, puis appelle le callback avec `offline`. Un dépassement du délai donne `timeout`.\n- `rpc(msg, [timeout])` identique à `send()`, mais renvoie une promesse.\n- `cmd(msg, [timeout])` envoie sans attendre de réponse.\n- `message(fn)`, `error(fn)` et `online(fn)` définissent des gestionnaires. `online(meta)` s'exécute avec le message `init` du serveur, et avec `null` quand la connexion se ferme.\n- `close()` ou `remove()` supprime le client.\n\nPropriétés : `id`, `url`, `connected`, `meta` (le dernier message `init`).\n\nExample: Interroger le serveur\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JafquF2vr60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"OpenClient","summary":"OPENCLIENT(): un client WebSocket per i messaggi verso altri servizi.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT(): un client WebSocket per i messaggi verso altri servizi.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nApre un client WebSocket condiviso per messaggi di richiesta e risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo del server (`ws://`, `wss://`, `http://` o `https://`). |\n| `id` | `String` | no | `GUID(10)` | L'identificatore del client. |\n\nReturns: `Object` Il client.\n\nSi connette a `url` tramite WebSocket (`http` diventa `ws`, `https` diventa `wss`) e si riconnette automaticamente. I client con lo stesso URL condividono una sola connessione; la connessione si chiude quando viene rimosso il suo ultimo client. Passare un `id` esistente rimuove prima il vecchio client con quell'id.\n\nIl client ha questi metodi:\n\n- `send(msg, [callback], [timeout])` invia un messaggio JSON. Con una callback, il messaggio riceve un `callbackid`, e la callback `function(err, response)` viene eseguita quando il server risponde con lo stesso `callbackid` (campi `error` e `response`). Mentre la connessione è assente riprova ogni 500 ms, fino a dieci volte, poi richiama la callback con `offline`. Un timeout produce `timeout`.\n- `rpc(msg, [timeout])` come `send()`, ma restituisce una promise.\n- `cmd(msg, [timeout])` invia senza attendere una risposta.\n- `message(fn)`, `error(fn)` e `online(fn)` impostano gli handler. `online(meta)` viene eseguito con il messaggio `init` del server, e con `null` quando la connessione si chiude.\n- `close()` o `remove()` rimuove il client.\n\nProprietà: `id`, `url`, `connected`, `meta` (l'ultimo messaggio `init`).\n\nExample: Interrogare il server\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JafquF2vr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/openclient/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"OpenClient","summary":"OPENCLIENT(): WebSocket klient pre správy iným službám.","markdown":"---\ntitle: OpenClient\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/openclient/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# OpenClient\n\n> OPENCLIENT(): WebSocket klient pre správy iným službám.\n\n## API\n\n### OPENCLIENT(url, [id])\n\nType: `method`\n\nOtvorí zdieľaného WebSocket klienta pre správy typu požiadavka a odpoveď.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Adresa servera (`ws://`, `wss://`, `http://` alebo `https://`). |\n| `id` | `String` | no | `GUID(10)` | Identifikátor klienta. |\n\nReturns: `Object` Klient.\n\nPripojí sa na `url` cez WebSocket (`http` sa zmení na `ws`, `https` na `wss`) a automaticky sa znova pripája. Klienti s rovnakou URL zdieľajú jedno spojenie; spojenie sa zatvorí, keď sa odstráni jeho posledný klient. Odovzdanie existujúceho `id` najprv odstráni starého klienta s týmto id.\n\nKlient má tieto metódy:\n\n- `send(msg, [callback], [timeout])` odošle správu JSON. S callbackom správa dostane `callbackid` a callback `function(err, response)` sa spustí, keď server odpovie s rovnakým `callbackid` (polia `error` a `response`). Kým je spojenie prerušené, skúša to znova každých 500 ms, najviac desaťkrát, potom zavolá callback s `offline`. Timeout vráti `timeout`.\n- `rpc(msg, [timeout])` to isté ako `send()`, ale vracia promise.\n- `cmd(msg, [timeout])` odošle bez čakania na odpoveď.\n- `message(fn)`, `error(fn)` a `online(fn)` nastavia handlery. `online(meta)` sa spustí so správou `init` servera a s `null`, keď sa spojenie zatvorí.\n- `close()` alebo `remove()` odstráni klienta.\n\nVlastnosti: `id`, `url`, `connected`, `meta` (posledná správa `init`).\n\nExample: Otázka na server\n```js\nvar client = OPENCLIENT('https://service.example.com/');\n\nclient.message(function(msg) {\n\tconsole.log('Message:', msg);\n});\n\nclient.send({ type: 'ping' }, function(err, response) {\n\tconsole.log(err, response);\n}, 5000);\n\nvar stats = await client.rpc({ type: 'stats' }, 5000);\n```\n","entries":[{"type":"method","name":"OPENCLIENT()","signature":"OPENCLIENT(url, [id])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"JabZ9x1ee61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Mail","summary":"Global mail functions, the mail configuration, the Mail module and the message object.","markdown":"---\ntitle: Mail\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Mail\n\n> Global mail functions, the mail configuration, the Mail module and the message object.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()` send email with the SMTP server from the configuration; the `Mail` module creates and sends messages to any server. In this reference `message` is a message returned by these functions or by `Mail.create()`. The guide [Sending email](../../guides/mail/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nRenders a view and sends it as an HTML email.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | One email address or an array of addresses; each one becomes a `To` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `view` | `String` | yes |  | The name of a view in `views/`, for example `mails/welcome`. |\n| `model` | `Object` | no |  | The model of the view. |\n| `language` | `String` | no |  | A language for the subject and the view. |\n| `callback` | `Function` | no |  | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. |\n\nReturns: `MailMessage` The message, before it is sent.\n\nThe view is rendered without a layout; the model is available as `model`. With `language`, the subject is translated (a subject with `@(...)` is translated by its parts) and the view is rendered in this language. A view name that starts with `=theme/` is taken from this theme. The sender, reply-to and copies come from the configuration. The message is sent on the next tick, so you can still change it. `callback` can also be the fifth argument and `language` the sixth.\n\nExample: A welcome email\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Translated, with an attachment\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nSends an HTML string as an email.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | One email address or an array of addresses; each one becomes a `To` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The HTML of the message. |\n| `language` | `String` | no |  | A language for the subject and the body. |\n| `callback` | `Function` | no |  | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. |\n\nReturns: `MailMessage` The message, before it is sent.\n\nA body without a `<body>` element is wrapped in a full HTML document with the subject as the title and a `<body>` with normalized CSS (no margin, Arial 14px). With `language`, the subject is translated and the `@(...)` texts of the body are translated too. `callback` can also be the fourth argument.\n\nExample: A short message\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nSends a log or notification email.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | One email address or an array of addresses; each one becomes a `To` recipient. |\n| `subject` | `String` | no | `name and version` | The subject. |\n| `body` | `String|Object` | yes |  | The text or an object to serialize. |\n| `callback` | `Function` | no |  | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. |\n\nReturns: `MailMessage` The message, before it is sent.\n\nThe body is placed in a `<pre>` element; an object is serialized as JSON. Without a subject, the subject is the `name` and the `version` of the configuration, for example `My app v1.0.0`.\n\nExample: Notify the administrator\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Only a body\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nRenders a view and sends it as an email from an action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | One email address or an array of addresses; each one becomes a `To` recipient. |\n| `subject` | `String` | yes |  | The subject; `@(...)` parts are translated. |\n| `view` | `String` | yes |  | The name of a view in `views/`. |\n| `model` | `Object` | no |  | The model of the view. |\n| `callback` | `Function` | no |  | Called with `function(err, message)` when the message has been written to the server, or with the reply line when the server rejects it. |\n\nReturns: `MailMessage` The message, before it is sent.\n\nIt works like `MAIL()`; the subject is translated with the language of the controller (`this.language`), and the view is rendered with it. The layout of the controller is not used for the email.\n\nExample: After an order\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nCreates and schedules every message of `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` and `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | One email address or an array of addresses; each one becomes a `To` recipient. |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The HTML body. |\n| `callback` | `Function` | no |  | The message callback. |\n| `replyTo` | `String` | no |  | A reply-to address instead of `mail_reply`. |\n\nReturns: `MailMessage` The message.\n\nThe default delegate creates a message with `Mail.create()`, adds the recipients, sets the sender from `mail_from` and `name`, adds `replyTo` or `mail_reply`, `mail_bcc` and `mail_cc`, and sends it on the next tick with `message.send2()`. Replace it to send email in another way; it must return a message object, because the callers change it (for example with `manually()`).\n\nExample: Add a header to the subject\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nEmitted for every message just before it is written to the SMTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | The message being sent. |\n\nIt is emitted for messages sent with the configuration and with `Mail.send()`.\n\nExample: Audit outgoing email\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nMakes the next message read `mail_smtp_options` again.\n\nThe options of the SMTP connection are cached after the first message. Run this command after you change `CONF.mail_smtp_options` in code. `LOADCONFIG()` and `Mail.use()` clear the cache themselves.\n\nExample: Change the SMTP account\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nThe host name of the SMTP server.\n\nUsed by `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` and `Mail.send2()`. When it is empty, the framework uses `smtp.` plus the domain of the sender address and stores it here.\n\nExample: In the config file\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nThe options of the SMTP connection.\n\nIn the config file it is a JavaScript object written as text; in code it is an object. Options:\n\n- `port` (default `25`, or `465` with `secure`);\n- `secure` (default `false`): TLS from the start; the options are also passed to the TLS connection;\n- `user` and `password`: the login (`AUTH LOGIN` or `AUTH PLAIN`, as the server offers);\n- `token`: an OAuth 2.0 access token for `AUTH XOAUTH2`, used with `user`;\n- `tls`: options of the TLS connection; the client upgrades the connection with `STARTTLS`;\n- `timeout` (default `10000`): the socket timeout in milliseconds.\n\nWith `user` and `password`, a server that announces ESMTP gets `STARTTLS` before the login.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Submission port with STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nHow long a connection to the SMTP server stays open for the next messages.\n\nDefault `10 minutes`. It is used by `message.send2()` while the application runs a web server; the open connection is reused for all messages to the same host. A number is in minutes. `false` opens a new connection for every message.\n\nExample: Close after each message\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nThe sender address of messages sent with the configuration.\n\nThe sender name is the `name` key of the configuration. `mail_address_from` is an older name of this key.\n\nExample: Sender\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nA `Reply-To` address added to every message sent with the configuration.\n\nNot used when the caller of `DEF.onMail` passes its own `replyTo`. `mail_address_reply` is an older name of this key.\n\nExample: Reply to support\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nA `Cc` address added to every message sent with the configuration.\n\nExample: Copy\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nA `Bcc` address added to every message sent with the configuration.\n\n`mail_address_copy` is an older name of this key.\n\nExample: Archive every message\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nThe global mail module: creates messages and sends them over SMTP.\n\n`Mail` is available everywhere. It sends messages to any server (`Mail.send()`), with the configuration (`Mail.send2()`), checks a server (`Mail.try()`, `Mail.use()`) and emits the events `send` and `error`.\n\nExample: A message to any server\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nCreates an empty message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | The subject. |\n| `body` | `String` | yes |  | The body, HTML by default. |\n\nReturns: `MailMessage` A new message.\n\nThe message has no sender and no recipients, and its type is `html`. It is not sent until you call `message.send()`, `message.send2()`, `Mail.send()` or `Mail.send2()`.\n\nExample: Create and send\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nSends one message or an array of messages over one connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | The host name of the SMTP server. |\n| `options` | `Object` | no | `{}` | The connection options, the same as `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | A message or an array of messages. |\n| `callback` | `Function` | no |  | `function(err)`, called once: when the first message has been written, or when the connection fails. |\n| `cache` | `Boolean|Number|String` | no | `false` | Keeps the connection open: `true` for 10 minutes, a number of minutes, or a text such as `5 minutes`. |\n\nReturns: `Mail` The mail module; nothing when the messages join an open connection.\n\nAll messages go through one connection in their order. `options` can be skipped when `messages` is an array. With `cache`, the connection stays open and later calls for the same host add their messages to it; such a later call does not call its `callback`, so use `message.callback()` there.\n\nExample: Two messages\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nSends messages with `mail_smtp` and `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | A message or an array of messages. |\n| `callback` | `Function` | no |  | `function(err)`, called once: when the first message has been written, or when the connection fails. Use `message.callback()` for each message. |\n\nReturns: `Mail` The mail module.\n\nThe same as `Mail.send()` with the server and the options of the configuration.\n\nExample: A newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nChecks an SMTP server: connects, signs in and quits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | The host name of the SMTP server. |\n| `options` | `Object` | no | `{}` | The connection options, the same as `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` The mail module, or a promise without a callback.\n\nNo message is sent. Without a callback it returns a promise that is rejected with the error.\n\nExample: With a callback\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: With a promise\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nChecks an SMTP server and, when it works, makes it the server of the configuration.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | The host name of the SMTP server. |\n| `options` | `Object` | no |  | The connection options. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nIt calls `Mail.try()`; on success it sets `CONF.mail_smtp` and `CONF.mail_smtp_options` and clears the cached options. Without a callback, an error is logged with `F.error()`.\n\nExample: Settings from a database\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nPrints the SMTP conversation to the console.\n\nReturns: `Boolean`\n\nDefault `false`. Every command sent and every reply received is printed.\n\nExample: Debug a server\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nEmitted when a connection or an SMTP command fails.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | The error or the reply line of the server. |\n| `connection` | `Object` | yes |  | The internal connection object. |\n\nNot emitted for `Mail.try()` or for a connection reset. A message rejected by the server is passed as its reply line.\n\nExample: Log SMTP errors\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nEmitted when a connection to the SMTP server is ready and the client starts the conversation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | The internal connection object. |\n\nExample: Count connections\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nRemoves a handler of a `Mail` event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name, `error` or `send`. |\n| `fn` | `Function` | yes |  | The handler added with `Mail.on()`. |\n\nReturns: `Mail` The mail module.\n\n`Mail.once(name, fn)` adds a handler that runs once; `Mail.removeAllListeners([name])` removes all handlers of one event or of all events.\n\nExample: Stop logging\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nAdds a `To` recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `name` | `String` | no |  | The name of the recipient. |\n| `clear` | `Boolean` | no | `false` | Removes the recipients added before. |\n\nReturns: `MailMessage` The message.\n\nThe address can contain the name: `Peter Sirka <peter@example.com>`. `clear` can be the second argument.\n\nExample: Two recipients\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nAdds a `Cc` recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `name` | `String` | no |  | The name of the recipient. |\n| `clear` | `Boolean` | no | `false` | Removes the `Cc` addresses added before. |\n\nReturns: `MailMessage` The message.\n\nThe address can contain the name, like in `message.to()`. `clear` can be the second argument.\n\nExample: A copy\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nAdds a `Bcc` recipient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `clear` | `Boolean` | no | `false` | Removes the `Bcc` addresses added before, including `mail_bcc`. |\n\nReturns: `MailMessage` The message.\n\nThe address is not written to the headers. Use a plain address without a name.\n\nExample: A hidden copy\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nAdds a `Reply-To` address.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `clear` | `Boolean` | no | `false` | Removes the reply addresses added before, including `mail_reply`. |\n\nReturns: `MailMessage` The message.\n\nUse a plain address without a name.\n\nExample: Replace the configured address\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nSets the sender.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `name` | `String` | no |  | The name of the sender. |\n\nReturns: `MailMessage` The message.\n\nThe address can contain the name: `My app <info@example.com>`. Messages created by `MAIL()` and the other global functions already have the sender from `mail_from` and `name`.\n\nExample: Sender with a name\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nAn alias of `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | The email address. |\n| `name` | `String` | no |  | The name of the sender. |\n\nReturns: `MailMessage` The message.\n\nExample: Sender\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nThe subject of the message.\n\nReturns: `String`\n\nYou can change it before the message is sent. Non-ASCII characters are encoded for you.\n\nExample: Prefix\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nThe body of the message.\n\nReturns: `String`\n\nHTML by default; see `message.type`.\n\nExample: Set the body later\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nThe content type of the body: `html` or `plain`.\n\nReturns: `String`\n\nDefault `html`. The body is sent as `text/` plus this value.\n\nExample: A plain text message\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nAdds a file from the disk as an attachment.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The path of the file. |\n| `name` | `String` | no | `the name of the file` | The file name shown in the email. |\n| `contentid` | `String` | no |  | A Content-ID for an inline attachment, unique in the message. |\n\nReturns: `MailMessage` The message.\n\nThe content type comes from the extension of `name`. With `contentid`, the file is an inline attachment and the HTML refers to it as `cid:contentid`. An `.ics` file is sent as a calendar invitation.\n\nExample: A PDF\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: An inline image\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAdds a file from a `FILESTORAGE()` as an attachment.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | The name of the file storage. |\n| `id` | `String` | yes |  | The identifier of the file. |\n| `name` | `String` | no | `the stored name` | The file name shown in the email. |\n| `contentid` | `String` | no |  | A Content-ID for an inline attachment. |\n\nReturns: `MailMessage` The message.\n\nWithout `name`, the name and the content type come from the stored file. A file that cannot be read is skipped and the error is logged.\n\nExample: A stored file\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nAdds the `List-Unsubscribe` headers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | An unsubscribe URL or email address. |\n\nReturns: `MailMessage` The message.\n\nA URL that starts with `http:` or `https:` is used as a link; any other value is used as a `mailto:` address. The header `List-Unsubscribe-Post: List-Unsubscribe=One-Click` is added too.\n\nExample: A newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nSets the callback of the message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` The message.\n\nThe callback runs when the message has been written to the server, or when the server rejects it; the error is then the reply line of the server. Connection errors are not passed here: they are logged and emitted as `Mail.on('error')`.\n\nExample: Mark as sent\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nStops the automatic sending of a message from `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` or `controller.mail()`.\n\nReturns: `MailMessage` The message.\n\nCall it in the same call stack, then send the message yourself with `message.send2()`.\n\nExample: Attach a generated file\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nSends the message with `mail_smtp` and `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Called when the message has been written, on a new connection. |\n\nReturns: `MailMessage` The message.\n\nWithout `mail_smtp`, the server is `smtp.` plus the domain of the sender; without a sender it throws `Missing SMTP settings`. While the application runs a web server, the connection is kept open for `mail_smtp_keepalive`; when the message goes to such an open connection, `callback` is not called, so prefer `message.callback()`.\n\nExample: Send a created message\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nSends the message to an SMTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | The host name of the SMTP server. |\n| `options` | `Object` | yes |  | The connection options, the same as `mail_smtp_options`; pass `{}` for none. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Keeps the connection open, like in `Mail.send()`. |\n\nReturns: `MailMessage` The message.\n\nUses its own connection to `smtp`; the configuration is not used.\n\nExample: Another server\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZ9x1ee61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Mail","summary":"Globale Mail-Funktionen, die Mail-Konfiguration, das Modul Mail und das Nachrichtenobjekt.","markdown":"---\ntitle: Mail\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Mail\n\n> Globale Mail-Funktionen, die Mail-Konfiguration, das Modul Mail und das Nachrichtenobjekt.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `controller.mail()` senden E-Mails über den SMTP-Server aus der Konfiguration; das Modul `Mail` erstellt Nachrichten und sendet sie an einen beliebigen Server. In dieser Referenz ist `message` eine Nachricht, die von diesen Funktionen oder von `Mail.create()` zurückgegeben wird. Der Guide [E-Mails senden](../../guides/mail/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nRendert eine View und sendet sie als HTML-E-Mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Eine E-Mail-Adresse oder ein Array von Adressen; jede wird zu einem `To`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `view` | `String` | yes |  | Der Name einer View in `views/`, zum Beispiel `mails/welcome`. |\n| `model` | `Object` | no |  | Das Model der View. |\n| `language` | `String` | no |  | Eine Sprache für den Betreff und die View. |\n| `callback` | `Function` | no |  | Wird mit `function(err, message)` aufgerufen, wenn die Nachricht an den Server geschrieben wurde, oder mit der Antwortzeile, wenn der Server sie ablehnt. |\n\nReturns: `MailMessage` Die Nachricht, bevor sie gesendet wird.\n\nDie View wird ohne Layout gerendert; das Model steht als `model` zur Verfügung. Mit `language` wird der Betreff übersetzt (ein Betreff mit `@(...)` wird teilweise übersetzt) und die View in dieser Sprache gerendert. Ein View-Name, der mit `=theme/` beginnt, wird aus diesem Theme genommen. Absender, Reply-To und Kopien stammen aus der Konfiguration. Die Nachricht wird im nächsten Tick gesendet, sodass du sie noch ändern kannst. `callback` kann auch das fünfte Argument sein und `language` das sechste.\n\nExample: Eine Willkommens-E-Mail\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Übersetzt, mit einem Anhang\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nSendet einen HTML-String als E-Mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Eine E-Mail-Adresse oder ein Array von Adressen; jede wird zu einem `To`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Das HTML der Nachricht. |\n| `language` | `String` | no |  | Eine Sprache für den Betreff und den Inhalt. |\n| `callback` | `Function` | no |  | Wird mit `function(err, message)` aufgerufen, wenn die Nachricht an den Server geschrieben wurde, oder mit der Antwortzeile, wenn der Server sie ablehnt. |\n\nReturns: `MailMessage` Die Nachricht, bevor sie gesendet wird.\n\nEin Inhalt ohne Element `<body>` wird in ein vollständiges HTML-Dokument mit dem Betreff als Titel und einem `<body>` mit normalisiertem CSS (kein Rand, Arial 14px) eingebettet. Mit `language` wird der Betreff übersetzt, und auch die `@(...)`-Texte des Inhalts werden übersetzt. `callback` kann auch das vierte Argument sein.\n\nExample: Eine kurze Nachricht\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nSendet eine Log- oder Benachrichtigungs-E-Mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Eine E-Mail-Adresse oder ein Array von Adressen; jede wird zu einem `To`-Empfänger. |\n| `subject` | `String` | no | `name and version` | Der Betreff. |\n| `body` | `String|Object` | yes |  | Der Text oder ein zu serialisierendes Objekt. |\n| `callback` | `Function` | no |  | Wird mit `function(err, message)` aufgerufen, wenn die Nachricht an den Server geschrieben wurde, oder mit der Antwortzeile, wenn der Server sie ablehnt. |\n\nReturns: `MailMessage` Die Nachricht, bevor sie gesendet wird.\n\nDer Inhalt wird in ein Element `<pre>` gesetzt; ein Objekt wird als JSON serialisiert. Ohne Betreff besteht der Betreff aus `name` und `version` der Konfiguration, zum Beispiel `My app v1.0.0`.\n\nExample: Den Administrator benachrichtigen\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Nur ein Inhalt\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nRendert eine View und sendet sie aus einer Action als E-Mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Eine E-Mail-Adresse oder ein Array von Adressen; jede wird zu einem `To`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff; `@(...)`-Teile werden übersetzt. |\n| `view` | `String` | yes |  | Der Name einer View in `views/`. |\n| `model` | `Object` | no |  | Das Model der View. |\n| `callback` | `Function` | no |  | Wird mit `function(err, message)` aufgerufen, wenn die Nachricht an den Server geschrieben wurde, oder mit der Antwortzeile, wenn der Server sie ablehnt. |\n\nReturns: `MailMessage` Die Nachricht, bevor sie gesendet wird.\n\nEs funktioniert wie `MAIL()`; der Betreff wird mit der Sprache des Controllers (`this.language`) übersetzt, und die View wird damit gerendert. Das Layout des Controllers wird für die E-Mail nicht verwendet.\n\nExample: Nach einer Bestellung\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nErstellt und plant jede Nachricht von `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` und `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Eine E-Mail-Adresse oder ein Array von Adressen; jede wird zu einem `To`-Empfänger. |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Der HTML-Inhalt. |\n| `callback` | `Function` | no |  | Das Callback der Nachricht. |\n| `replyTo` | `String` | no |  | Eine Reply-To-Adresse anstelle von `mail_reply`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDas Standard-Delegate erstellt eine Nachricht mit `Mail.create()`, fügt die Empfänger hinzu, setzt den Absender aus `mail_from` und `name`, fügt `replyTo` oder `mail_reply`, `mail_bcc` und `mail_cc` hinzu und sendet sie im nächsten Tick mit `message.send2()`. Ersetze es, um E-Mails auf andere Weise zu senden; es muss ein Nachrichtenobjekt zurückgeben, weil die Aufrufer es ändern (zum Beispiel mit `manually()`).\n\nExample: Dem Betreff einen Header hinzufügen\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nWird für jede Nachricht ausgelöst, unmittelbar bevor sie an den SMTP-Server geschrieben wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Die Nachricht, die gesendet wird. |\n\nEs wird für Nachrichten ausgelöst, die mit der Konfiguration und mit `Mail.send()` gesendet werden.\n\nExample: Ausgehende E-Mails prüfen\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nSorgt dafür, dass die nächste Nachricht `mail_smtp_options` erneut liest.\n\nDie Optionen der SMTP-Verbindung werden nach der ersten Nachricht gecacht. Führe diesen Befehl aus, nachdem du `CONF.mail_smtp_options` im Code geändert hast. `LOADCONFIG()` und `Mail.use()` leeren den Cache selbst.\n\nExample: Das SMTP-Konto wechseln\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nDer Hostname des SMTP-Servers.\n\nWird von `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` und `Mail.send2()` verwendet. Ist er leer, verwendet das Framework `smtp.` plus die Domain der Absenderadresse und speichert den Wert hier.\n\nExample: In der Konfigurationsdatei\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nDie Optionen der SMTP-Verbindung.\n\nIn der Konfigurationsdatei ist es ein als Text geschriebenes JavaScript-Objekt, im Code ein Objekt. Optionen:\n\n- `port` (Standard `25` oder `465` mit `secure`);\n- `secure` (Standard `false`): TLS von Anfang an; die Optionen werden auch an die TLS-Verbindung übergeben;\n- `user` und `password`: die Anmeldung (`AUTH LOGIN` oder `AUTH PLAIN`, je nachdem, was der Server anbietet);\n- `token`: ein OAuth-2.0-Access-Token für `AUTH XOAUTH2`, verwendet mit `user`;\n- `tls`: Optionen der TLS-Verbindung; der Client stuft die Verbindung mit `STARTTLS` hoch;\n- `timeout` (Standard `10000`): das Socket-Timeout in Millisekunden.\n\nMit `user` und `password` erhält ein Server, der ESMTP ankündigt, vor der Anmeldung `STARTTLS`.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Submission-Port mit STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nWie lange eine Verbindung zum SMTP-Server für die nächsten Nachrichten offen bleibt.\n\nStandard `10 minutes`. Es wird von `message.send2()` verwendet, solange die Anwendung einen Webserver betreibt; die offene Verbindung wird für alle Nachrichten an denselben Host wiederverwendet. Eine Zahl bedeutet Minuten. `false` öffnet für jede Nachricht eine neue Verbindung.\n\nExample: Nach jeder Nachricht schließen\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nDie Absenderadresse der Nachrichten, die mit der Konfiguration gesendet werden.\n\nDer Absendername ist der Schlüssel `name` der Konfiguration. `mail_address_from` ist ein älterer Name dieses Schlüssels.\n\nExample: Absender\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nEine `Reply-To`-Adresse, die jeder mit der Konfiguration gesendeten Nachricht hinzugefügt wird.\n\nWird nicht verwendet, wenn der Aufrufer von `DEF.onMail` ein eigenes `replyTo` übergibt. `mail_address_reply` ist ein älterer Name dieses Schlüssels.\n\nExample: Antworten an den Support\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nEine `Cc`-Adresse, die jeder mit der Konfiguration gesendeten Nachricht hinzugefügt wird.\n\nExample: Kopie\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nEine `Bcc`-Adresse, die jeder mit der Konfiguration gesendeten Nachricht hinzugefügt wird.\n\n`mail_address_copy` ist ein älterer Name dieses Schlüssels.\n\nExample: Jede Nachricht archivieren\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nDas globale Mail-Modul: erstellt Nachrichten und sendet sie über SMTP.\n\n`Mail` ist überall verfügbar. Es sendet Nachrichten an einen beliebigen Server (`Mail.send()`) oder mit der Konfiguration (`Mail.send2()`), prüft einen Server (`Mail.try()`, `Mail.use()`) und löst die Events `send` und `error` aus.\n\nExample: Eine Nachricht an einen beliebigen Server\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nErstellt eine leere Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | Der Betreff. |\n| `body` | `String` | yes |  | Der Inhalt, standardmäßig HTML. |\n\nReturns: `MailMessage` Eine neue Nachricht.\n\nDie Nachricht hat keinen Absender und keine Empfänger, und ihr Typ ist `html`. Sie wird erst gesendet, wenn du `message.send()`, `message.send2()`, `Mail.send()` oder `Mail.send2()` aufrufst.\n\nExample: Erstellen und senden\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nSendet eine Nachricht oder ein Array von Nachrichten über eine Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Der Hostname des SMTP-Servers. |\n| `options` | `Object` | no | `{}` | Die Verbindungsoptionen, dieselben wie bei `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | Eine Nachricht oder ein Array von Nachrichten. |\n| `callback` | `Function` | no |  | `function(err)`, einmal aufgerufen: wenn die erste Nachricht geschrieben wurde oder wenn die Verbindung fehlschlägt. |\n| `cache` | `Boolean|Number|String` | no | `false` | Hält die Verbindung offen: `true` für 10 Minuten, eine Anzahl Minuten oder ein Text wie `5 minutes`. |\n\nReturns: `Mail` Das Mail-Modul; nichts, wenn die Nachrichten einer offenen Verbindung hinzugefügt werden.\n\nAlle Nachrichten gehen in ihrer Reihenfolge über eine Verbindung. `options` kann weggelassen werden, wenn `messages` ein Array ist. Mit `cache` bleibt die Verbindung offen, und spätere Aufrufe für denselben Host fügen ihre Nachrichten hinzu; ein solcher späterer Aufruf ruft sein `callback` nicht auf, verwende dort also `message.callback()`.\n\nExample: Zwei Nachrichten\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nSendet Nachrichten mit `mail_smtp` und `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | Eine Nachricht oder ein Array von Nachrichten. |\n| `callback` | `Function` | no |  | `function(err)`, einmal aufgerufen: wenn die erste Nachricht geschrieben wurde oder wenn die Verbindung fehlschlägt. Verwende `message.callback()` für jede Nachricht. |\n\nReturns: `Mail` Das Mail-Modul.\n\nDasselbe wie `Mail.send()` mit dem Server und den Optionen der Konfiguration.\n\nExample: Ein Newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nPrüft einen SMTP-Server: verbindet sich, meldet sich an und beendet die Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Der Hostname des SMTP-Servers. |\n| `options` | `Object` | no | `{}` | Die Verbindungsoptionen, dieselben wie bei `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` Das Mail-Modul oder ohne Callback eine Promise.\n\nEs wird keine Nachricht gesendet. Ohne Callback gibt es eine Promise zurück, die mit dem Fehler abgelehnt wird.\n\nExample: Mit einem Callback\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: Mit einer Promise\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nPrüft einen SMTP-Server und macht ihn, wenn er funktioniert, zum Server der Konfiguration.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Der Hostname des SMTP-Servers. |\n| `options` | `Object` | no |  | Die Verbindungsoptionen. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nEs ruft `Mail.try()` auf; bei Erfolg setzt es `CONF.mail_smtp` und `CONF.mail_smtp_options` und leert die gecachten Optionen. Ohne Callback wird ein Fehler mit `F.error()` protokolliert.\n\nExample: Einstellungen aus einer Datenbank\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nGibt die SMTP-Kommunikation in der Konsole aus.\n\nReturns: `Boolean`\n\nStandard `false`. Jeder gesendete Befehl und jede empfangene Antwort wird ausgegeben.\n\nExample: Einen Server debuggen\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nWird ausgelöst, wenn eine Verbindung oder ein SMTP-Befehl fehlschlägt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Der Fehler oder die Antwortzeile des Servers. |\n| `connection` | `Object` | yes |  | Das interne Verbindungsobjekt. |\n\nWird nicht für `Mail.try()` oder für einen Verbindungsabbruch ausgelöst. Eine vom Server abgelehnte Nachricht wird als dessen Antwortzeile übergeben.\n\nExample: SMTP-Fehler protokollieren\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nWird ausgelöst, wenn eine Verbindung zum SMTP-Server bereit ist und der Client die Kommunikation beginnt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | Das interne Verbindungsobjekt. |\n\nExample: Verbindungen zählen\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nEntfernt einen Handler eines `Mail`-Events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events, `error` oder `send`. |\n| `fn` | `Function` | yes |  | Der mit `Mail.on()` hinzugefügte Handler. |\n\nReturns: `Mail` Das Mail-Modul.\n\n`Mail.once(name, fn)` fügt einen Handler hinzu, der einmal läuft; `Mail.removeAllListeners([name])` entfernt alle Handler eines Events oder aller Events.\n\nExample: Protokollierung beenden\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nFügt einen `To`-Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `name` | `String` | no |  | Der Name des Empfängers. |\n| `clear` | `Boolean` | no | `false` | Entfernt die zuvor hinzugefügten Empfänger. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDie Adresse kann den Namen enthalten: `Peter Sirka <peter@example.com>`. `clear` kann das zweite Argument sein.\n\nExample: Zwei Empfänger\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nFügt einen `Cc`-Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `name` | `String` | no |  | Der Name des Empfängers. |\n| `clear` | `Boolean` | no | `false` | Entfernt die zuvor hinzugefügten `Cc`-Adressen. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDie Adresse kann den Namen enthalten, wie bei `message.to()`. `clear` kann das zweite Argument sein.\n\nExample: Eine Kopie\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nFügt einen `Bcc`-Empfänger hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `clear` | `Boolean` | no | `false` | Entfernt die zuvor hinzugefügten `Bcc`-Adressen, einschließlich `mail_bcc`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDie Adresse wird nicht in die Header geschrieben. Verwende eine einfache Adresse ohne Namen.\n\nExample: Eine verdeckte Kopie\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nFügt eine `Reply-To`-Adresse hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `clear` | `Boolean` | no | `false` | Entfernt die zuvor hinzugefügten Antwortadressen, einschließlich `mail_reply`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nVerwende eine einfache Adresse ohne Namen.\n\nExample: Die konfigurierte Adresse ersetzen\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nSetzt den Absender.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `name` | `String` | no |  | Der Name des Absenders. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDie Adresse kann den Namen enthalten: `My app <info@example.com>`. Nachrichten, die von `MAIL()` und den anderen globalen Funktionen erstellt werden, haben bereits den Absender aus `mail_from` und `name`.\n\nExample: Absender mit Namen\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nEin Alias von `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | Die E-Mail-Adresse. |\n| `name` | `String` | no |  | Der Name des Absenders. |\n\nReturns: `MailMessage` Die Nachricht.\n\nExample: Absender\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nDer Betreff der Nachricht.\n\nReturns: `String`\n\nDu kannst ihn ändern, bevor die Nachricht gesendet wird. Nicht-ASCII-Zeichen werden für dich kodiert.\n\nExample: Präfix\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nDer Inhalt der Nachricht.\n\nReturns: `String`\n\nStandardmäßig HTML; siehe `message.type`.\n\nExample: Den Inhalt später setzen\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nDer Content-Type des Inhalts: `html` oder `plain`.\n\nReturns: `String`\n\nStandard `html`. Der Inhalt wird als `text/` plus diesem Wert gesendet.\n\nExample: Eine Nachricht als reiner Text\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nFügt eine Datei von der Festplatte als Anhang hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der Pfad der Datei. |\n| `name` | `String` | no | `the name of the file` | Der Dateiname, der in der E-Mail angezeigt wird. |\n| `contentid` | `String` | no |  | Eine Content-ID für einen Inline-Anhang, eindeutig innerhalb der Nachricht. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDer Content-Type ergibt sich aus der Endung von `name`. Mit `contentid` ist die Datei ein Inline-Anhang, und das HTML verweist darauf als `cid:contentid`. Eine `.ics`-Datei wird als Kalendereinladung gesendet.\n\nExample: Eine PDF-Datei\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: Ein Inline-Bild\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nFügt eine Datei aus einem `FILESTORAGE()` als Anhang hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Der Name des Dateispeichers. |\n| `id` | `String` | yes |  | Die Kennung der Datei. |\n| `name` | `String` | no | `the stored name` | Der Dateiname, der in der E-Mail angezeigt wird. |\n| `contentid` | `String` | no |  | Eine Content-ID für einen Inline-Anhang. |\n\nReturns: `MailMessage` Die Nachricht.\n\nOhne `name` stammen der Name und der Content-Type aus der gespeicherten Datei. Eine Datei, die nicht gelesen werden kann, wird übersprungen und der Fehler protokolliert.\n\nExample: Eine gespeicherte Datei\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nFügt die Header `List-Unsubscribe` hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Eine Abmelde-URL oder E-Mail-Adresse. |\n\nReturns: `MailMessage` Die Nachricht.\n\nEine URL, die mit `http:` oder `https:` beginnt, wird als Link verwendet; jeder andere Wert wird als `mailto:`-Adresse verwendet. Der Header `List-Unsubscribe-Post: List-Unsubscribe=One-Click` wird ebenfalls hinzugefügt.\n\nExample: Ein Newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nSetzt das Callback der Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nDas Callback läuft, wenn die Nachricht an den Server geschrieben wurde oder wenn der Server sie ablehnt; der Fehler ist dann die Antwortzeile des Servers. Verbindungsfehler werden hier nicht übergeben: Sie werden protokolliert und als `Mail.on('error')` ausgelöst.\n\nExample: Als gesendet markieren\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nStoppt das automatische Senden einer Nachricht aus `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` oder `controller.mail()`.\n\nReturns: `MailMessage` Die Nachricht.\n\nRufe es im selben Call-Stack auf und sende die Nachricht dann selbst mit `message.send2()`.\n\nExample: Eine generierte Datei anhängen\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nSendet die Nachricht mit `mail_smtp` und `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn die Nachricht über eine neue Verbindung geschrieben wurde. |\n\nReturns: `MailMessage` Die Nachricht.\n\nOhne `mail_smtp` ist der Server `smtp.` plus die Domain des Absenders; ohne Absender wirft es `Missing SMTP settings`. Solange die Anwendung einen Webserver betreibt, bleibt die Verbindung für `mail_smtp_keepalive` offen; geht die Nachricht an eine solche offene Verbindung, wird `callback` nicht aufgerufen, verwende also besser `message.callback()`.\n\nExample: Eine erstellte Nachricht senden\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nSendet die Nachricht an einen SMTP-Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Der Hostname des SMTP-Servers. |\n| `options` | `Object` | yes |  | Die Verbindungsoptionen, dieselben wie bei `mail_smtp_options`; übergib `{}` für keine. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Hält die Verbindung offen, wie bei `Mail.send()`. |\n\nReturns: `MailMessage` Die Nachricht.\n\nVerwendet eine eigene Verbindung zu `smtp`; die Konfiguration wird nicht verwendet.\n\nExample: Ein anderer Server\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZ9x1ee61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Correo electrónico","summary":"Funciones globales de correo, la configuración de correo, el módulo Mail y el objeto mensaje.","markdown":"---\ntitle: \"Correo electrónico\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Correo electrónico\n\n> Funciones globales de correo, la configuración de correo, el módulo Mail y el objeto mensaje.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `controller.mail()` envían correos con el servidor SMTP de la configuración; el módulo `Mail` crea y envía mensajes a cualquier servidor. En esta referencia, `message` es un mensaje devuelto por estas funciones o por `Mail.create()`. La guía [Enviar correo electrónico](../../guides/mail/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nRenderiza una vista y la envía como correo HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Una dirección de correo o un array de direcciones; cada una se convierte en un destinatario `To`. |\n| `subject` | `String` | yes |  | El asunto. |\n| `view` | `String` | yes |  | El nombre de una vista en `views/`, por ejemplo `mails/welcome`. |\n| `model` | `Object` | no |  | El modelo de la vista. |\n| `language` | `String` | no |  | Un idioma para el asunto y la vista. |\n| `callback` | `Function` | no |  | Se llama con `function(err, message)` cuando el mensaje se ha escrito en el servidor, o con la línea de respuesta cuando el servidor lo rechaza. |\n\nReturns: `MailMessage` El mensaje, antes de enviarse.\n\nLa vista se renderiza sin plantilla (layout); el modelo está disponible como `model`. Con `language`, el asunto se traduce (un asunto con `@(...)` se traduce por partes) y la vista se renderiza en este idioma. Un nombre de vista que empieza con `=theme/` se toma de este tema. El remitente, la dirección de respuesta y las copias salen de la configuración. El mensaje se envía en el siguiente tick, así que todavía puedes cambiarlo. `callback` también puede ser el quinto argumento y `language` el sexto.\n\nExample: Un correo de bienvenida\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Traducido, con un adjunto\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nEnvía una cadena HTML como correo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Una dirección de correo o un array de direcciones; cada una se convierte en un destinatario `To`. |\n| `subject` | `String` | yes |  | El asunto. |\n| `body` | `String` | yes |  | El HTML del mensaje. |\n| `language` | `String` | no |  | Un idioma para el asunto y el cuerpo. |\n| `callback` | `Function` | no |  | Se llama con `function(err, message)` cuando el mensaje se ha escrito en el servidor, o con la línea de respuesta cuando el servidor lo rechaza. |\n\nReturns: `MailMessage` El mensaje, antes de enviarse.\n\nUn cuerpo sin elemento `<body>` se envuelve en un documento HTML completo con el asunto como título y un `<body>` con CSS normalizado (sin margen, Arial 14px). Con `language`, el asunto se traduce y los textos `@(...)` del cuerpo también. `callback` también puede ser el cuarto argumento.\n\nExample: Un mensaje corto\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nEnvía un correo de log o de notificación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Una dirección de correo o un array de direcciones; cada una se convierte en un destinatario `To`. |\n| `subject` | `String` | no | `name and version` | El asunto. |\n| `body` | `String|Object` | yes |  | El texto o un objeto que se serializa. |\n| `callback` | `Function` | no |  | Se llama con `function(err, message)` cuando el mensaje se ha escrito en el servidor, o con la línea de respuesta cuando el servidor lo rechaza. |\n\nReturns: `MailMessage` El mensaje, antes de enviarse.\n\nEl cuerpo se coloca en un elemento `<pre>`; un objeto se serializa como JSON. Sin asunto, el asunto es el `name` y la `version` de la configuración, por ejemplo `My app v1.0.0`.\n\nExample: Avisar al administrador\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Solo un cuerpo\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nRenderiza una vista y la envía como correo desde una acción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Una dirección de correo o un array de direcciones; cada una se convierte en un destinatario `To`. |\n| `subject` | `String` | yes |  | El asunto; las partes `@(...)` se traducen. |\n| `view` | `String` | yes |  | El nombre de una vista en `views/`. |\n| `model` | `Object` | no |  | El modelo de la vista. |\n| `callback` | `Function` | no |  | Se llama con `function(err, message)` cuando el mensaje se ha escrito en el servidor, o con la línea de respuesta cuando el servidor lo rechaza. |\n\nReturns: `MailMessage` El mensaje, antes de enviarse.\n\nFunciona como `MAIL()`; el asunto se traduce con el idioma del controlador (`this.language`), y la vista se renderiza con él. La plantilla (layout) del controlador no se usa para el correo.\n\nExample: Después de un pedido\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nCrea y programa cada mensaje de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` y `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Una dirección de correo o un array de direcciones; cada una se convierte en un destinatario `To`. |\n| `subject` | `String` | yes |  | El asunto. |\n| `body` | `String` | yes |  | El cuerpo HTML. |\n| `callback` | `Function` | no |  | El callback del mensaje. |\n| `replyTo` | `String` | no |  | Una dirección de respuesta en lugar de `mail_reply`. |\n\nReturns: `MailMessage` El mensaje.\n\nEl delegado por defecto crea un mensaje con `Mail.create()`, añade los destinatarios, define el remitente a partir de `mail_from` y `name`, añade `replyTo` o `mail_reply`, `mail_bcc` y `mail_cc`, y lo envía en el siguiente tick con `message.send2()`. Reemplázalo para enviar correo de otra forma; debe devolver un objeto mensaje, porque quienes lo llaman lo modifican (por ejemplo con `manually()`).\n\nExample: Añadir una cabecera al asunto\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nSe emite para cada mensaje justo antes de escribirse en el servidor SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | El mensaje que se envía. |\n\nSe emite para los mensajes enviados con la configuración y con `Mail.send()`.\n\nExample: Auditar el correo saliente\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nHace que el siguiente mensaje vuelva a leer `mail_smtp_options`.\n\nLas opciones de la conexión SMTP se guardan en caché tras el primer mensaje. Ejecuta este comando después de cambiar `CONF.mail_smtp_options` en el código. `LOADCONFIG()` y `Mail.use()` borran la caché por sí mismos.\n\nExample: Cambiar la cuenta SMTP\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nEl nombre de host del servidor SMTP.\n\nLo usan `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` y `Mail.send2()`. Cuando está vacío, el framework usa `smtp.` más el dominio de la dirección del remitente y lo guarda aquí.\n\nExample: En el archivo config\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nLas opciones de la conexión SMTP.\n\nEn el archivo config es un objeto JavaScript escrito como texto; en el código es un objeto. Opciones:\n\n- `port` (por defecto `25`, o `465` con `secure`);\n- `secure` (por defecto `false`): TLS desde el principio; las opciones también se pasan a la conexión TLS;\n- `user` y `password`: el inicio de sesión (`AUTH LOGIN` o `AUTH PLAIN`, según lo que ofrezca el servidor);\n- `token`: un token de acceso OAuth 2.0 para `AUTH XOAUTH2`, usado con `user`;\n- `tls`: opciones de la conexión TLS; el cliente actualiza la conexión con `STARTTLS`;\n- `timeout` (por defecto `10000`): el tiempo de espera del socket en milisegundos.\n\nCon `user` y `password`, un servidor que anuncia ESMTP recibe `STARTTLS` antes del inicio de sesión.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Puerto de envío con STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nCuánto tiempo permanece abierta una conexión con el servidor SMTP para los siguientes mensajes.\n\nPor defecto `10 minutes`. Lo usa `message.send2()` mientras la aplicación ejecuta un servidor web; la conexión abierta se reutiliza para todos los mensajes al mismo host. Un número se interpreta en minutos. `false` abre una conexión nueva en cada mensaje.\n\nExample: Cerrar después de cada mensaje\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nLa dirección del remitente de los mensajes enviados con la configuración.\n\nEl nombre del remitente es la clave `name` de la configuración. `mail_address_from` es un nombre antiguo de esta clave.\n\nExample: Remitente\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nUna dirección `Reply-To` que se añade a cada mensaje enviado con la configuración.\n\nNo se usa cuando quien llama a `DEF.onMail` pasa su propio `replyTo`. `mail_address_reply` es un nombre antiguo de esta clave.\n\nExample: Responder a soporte\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nUna dirección `Cc` que se añade a cada mensaje enviado con la configuración.\n\nExample: Copia\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nUna dirección `Bcc` que se añade a cada mensaje enviado con la configuración.\n\n`mail_address_copy` es un nombre antiguo de esta clave.\n\nExample: Archivar cada mensaje\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nEl módulo global de correo: crea mensajes y los envía por SMTP.\n\n`Mail` está disponible en todas partes. Envía mensajes a cualquier servidor (`Mail.send()`), con la configuración (`Mail.send2()`), comprueba un servidor (`Mail.try()`, `Mail.use()`) y emite los eventos `send` y `error`.\n\nExample: Un mensaje a cualquier servidor\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nCrea un mensaje vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | El asunto. |\n| `body` | `String` | yes |  | El cuerpo, HTML por defecto. |\n\nReturns: `MailMessage` Un mensaje nuevo.\n\nEl mensaje no tiene remitente ni destinatarios, y su tipo es `html`. No se envía hasta que llamas a `message.send()`, `message.send2()`, `Mail.send()` o `Mail.send2()`.\n\nExample: Crear y enviar\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nEnvía un mensaje o un array de mensajes por una sola conexión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | El nombre de host del servidor SMTP. |\n| `options` | `Object` | no | `{}` | Las opciones de conexión, las mismas que `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | Un mensaje o un array de mensajes. |\n| `callback` | `Function` | no |  | `function(err)`, se llama una vez: cuando se ha escrito el primer mensaje, o cuando falla la conexión. |\n| `cache` | `Boolean|Number|String` | no | `false` | Mantiene la conexión abierta: `true` durante 10 minutos, un número de minutos, o un texto como `5 minutes`. |\n\nReturns: `Mail` El módulo de correo; nada cuando los mensajes se unen a una conexión abierta.\n\nTodos los mensajes pasan por una conexión en su orden. `options` puede omitirse cuando `messages` es un array. Con `cache`, la conexión permanece abierta y las llamadas posteriores para el mismo host le añaden sus mensajes; esa llamada posterior no llama a su `callback`, así que usa `message.callback()` en ese caso.\n\nExample: Dos mensajes\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nEnvía mensajes con `mail_smtp` y `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | Un mensaje o un array de mensajes. |\n| `callback` | `Function` | no |  | `function(err)`, se llama una vez: cuando se ha escrito el primer mensaje, o cuando falla la conexión. Usa `message.callback()` para cada mensaje. |\n\nReturns: `Mail` El módulo de correo.\n\nLo mismo que `Mail.send()` con el servidor y las opciones de la configuración.\n\nExample: Una newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nComprueba un servidor SMTP: conecta, inicia sesión y sale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | El nombre de host del servidor SMTP. |\n| `options` | `Object` | no | `{}` | Las opciones de conexión, las mismas que `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` El módulo de correo, o una promesa sin callback.\n\nNo se envía ningún mensaje. Sin callback, devuelve una promesa que se rechaza con el error.\n\nExample: Con un callback\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: Con una promesa\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nComprueba un servidor SMTP y, si funciona, lo convierte en el servidor de la configuración.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | El nombre de host del servidor SMTP. |\n| `options` | `Object` | no |  | Las opciones de conexión. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nLlama a `Mail.try()`; si tiene éxito, define `CONF.mail_smtp` y `CONF.mail_smtp_options` y borra las opciones en caché. Sin callback, un error se registra con `F.error()`.\n\nExample: Ajustes desde una base de datos\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nImprime la conversación SMTP en la consola.\n\nReturns: `Boolean`\n\nPor defecto `false`. Se imprime cada comando enviado y cada respuesta recibida.\n\nExample: Depurar un servidor\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nSe emite cuando falla una conexión o un comando SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | El error o la línea de respuesta del servidor. |\n| `connection` | `Object` | yes |  | El objeto interno de la conexión. |\n\nNo se emite para `Mail.try()` ni para un reinicio de la conexión. Un mensaje rechazado por el servidor se pasa como su línea de respuesta.\n\nExample: Registrar errores SMTP\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nSe emite cuando una conexión con el servidor SMTP está lista y el cliente empieza la conversación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | El objeto interno de la conexión. |\n\nExample: Contar conexiones\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nElimina un manejador de un evento de `Mail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento, `error` o `send`. |\n| `fn` | `Function` | yes |  | El manejador añadido con `Mail.on()`. |\n\nReturns: `Mail` El módulo de correo.\n\n`Mail.once(name, fn)` añade un manejador que se ejecuta una vez; `Mail.removeAllListeners([name])` elimina todos los manejadores de un evento o de todos los eventos.\n\nExample: Dejar de registrar\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nAñade un destinatario `To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `name` | `String` | no |  | El nombre del destinatario. |\n| `clear` | `Boolean` | no | `false` | Elimina los destinatarios añadidos antes. |\n\nReturns: `MailMessage` El mensaje.\n\nLa dirección puede contener el nombre: `Peter Sirka <peter@example.com>`. `clear` puede ser el segundo argumento.\n\nExample: Dos destinatarios\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nAñade un destinatario `Cc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `name` | `String` | no |  | El nombre del destinatario. |\n| `clear` | `Boolean` | no | `false` | Elimina las direcciones `Cc` añadidas antes. |\n\nReturns: `MailMessage` El mensaje.\n\nLa dirección puede contener el nombre, como en `message.to()`. `clear` puede ser el segundo argumento.\n\nExample: Una copia\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nAñade un destinatario `Bcc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `clear` | `Boolean` | no | `false` | Elimina las direcciones `Bcc` añadidas antes, incluida `mail_bcc`. |\n\nReturns: `MailMessage` El mensaje.\n\nLa dirección no se escribe en las cabeceras. Usa una dirección simple sin nombre.\n\nExample: Una copia oculta\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nAñade una dirección `Reply-To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `clear` | `Boolean` | no | `false` | Elimina las direcciones de respuesta añadidas antes, incluida `mail_reply`. |\n\nReturns: `MailMessage` El mensaje.\n\nUsa una dirección simple sin nombre.\n\nExample: Reemplazar la dirección configurada\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nDefine el remitente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `name` | `String` | no |  | El nombre del remitente. |\n\nReturns: `MailMessage` El mensaje.\n\nLa dirección puede contener el nombre: `My app <info@example.com>`. Los mensajes creados por `MAIL()` y las demás funciones globales ya tienen el remitente de `mail_from` y `name`.\n\nExample: Remitente con nombre\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nUn alias de `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | La dirección de correo. |\n| `name` | `String` | no |  | El nombre del remitente. |\n\nReturns: `MailMessage` El mensaje.\n\nExample: Remitente\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nEl asunto del mensaje.\n\nReturns: `String`\n\nPuedes cambiarlo antes de que se envíe el mensaje. Los caracteres no ASCII se codifican por ti.\n\nExample: Prefijo\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nEl cuerpo del mensaje.\n\nReturns: `String`\n\nHTML por defecto; consulta `message.type`.\n\nExample: Definir el cuerpo más tarde\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nEl tipo de contenido del cuerpo: `html` o `plain`.\n\nReturns: `String`\n\nPor defecto `html`. El cuerpo se envía como `text/` más este valor.\n\nExample: Un mensaje de texto plano\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nAñade un archivo del disco como adjunto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta del archivo. |\n| `name` | `String` | no | `the name of the file` | El nombre de archivo que se muestra en el correo. |\n| `contentid` | `String` | no |  | Un Content-ID para un adjunto en línea, único en el mensaje. |\n\nReturns: `MailMessage` El mensaje.\n\nEl tipo de contenido sale de la extensión de `name`. Con `contentid`, el archivo es un adjunto en línea y el HTML se refiere a él como `cid:contentid`. Un archivo `.ics` se envía como invitación de calendario.\n\nExample: Un PDF\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: Una imagen en línea\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAñade un archivo de un `FILESTORAGE()` como adjunto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | El nombre del almacenamiento de archivos. |\n| `id` | `String` | yes |  | El identificador del archivo. |\n| `name` | `String` | no | `the stored name` | El nombre de archivo que se muestra en el correo. |\n| `contentid` | `String` | no |  | Un Content-ID para un adjunto en línea. |\n\nReturns: `MailMessage` El mensaje.\n\nSin `name`, el nombre y el tipo de contenido salen del archivo guardado. Un archivo que no se puede leer se omite y el error se registra.\n\nExample: Un archivo guardado\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nAñade las cabeceras `List-Unsubscribe`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una URL o dirección de correo para darse de baja. |\n\nReturns: `MailMessage` El mensaje.\n\nUna URL que empieza con `http:` o `https:` se usa como enlace; cualquier otro valor se usa como dirección `mailto:`. También se añade la cabecera `List-Unsubscribe-Post: List-Unsubscribe=One-Click`.\n\nExample: Una newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nDefine el callback del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` El mensaje.\n\nEl callback se ejecuta cuando el mensaje se ha escrito en el servidor, o cuando el servidor lo rechaza; el error es entonces la línea de respuesta del servidor. Los errores de conexión no se pasan aquí: se registran y se emiten como `Mail.on('error')`.\n\nExample: Marcar como enviado\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nDetiene el envío automático de un mensaje de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` o `controller.mail()`.\n\nReturns: `MailMessage` El mensaje.\n\nLlámalo en la misma pila de llamadas y luego envía tú mismo el mensaje con `message.send2()`.\n\nExample: Adjuntar un archivo generado\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nEnvía el mensaje con `mail_smtp` y `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se llama cuando el mensaje se ha escrito, en una conexión nueva. |\n\nReturns: `MailMessage` El mensaje.\n\nSin `mail_smtp`, el servidor es `smtp.` más el dominio del remitente; sin remitente lanza `Missing SMTP settings`. Mientras la aplicación ejecuta un servidor web, la conexión se mantiene abierta durante `mail_smtp_keepalive`; cuando el mensaje va a una conexión ya abierta, `callback` no se llama, así que es preferible `message.callback()`.\n\nExample: Enviar un mensaje creado\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nEnvía el mensaje a un servidor SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | El nombre de host del servidor SMTP. |\n| `options` | `Object` | yes |  | Las opciones de conexión, las mismas que `mail_smtp_options`; pasa `{}` para ninguna. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Mantiene la conexión abierta, como en `Mail.send()`. |\n\nReturns: `MailMessage` El mensaje.\n\nUsa su propia conexión con `smtp`; la configuración no se usa.\n\nExample: Otro servidor\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZ9x1ee61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Mail","summary":"Fonctions globales d'envoi d'e-mails, configuration des e-mails, module Mail et objet message.","markdown":"---\ntitle: Mail\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Mail\n\n> Fonctions globales d'envoi d'e-mails, configuration des e-mails, module Mail et objet message.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `controller.mail()` envoient des e-mails avec le serveur SMTP de la configuration ; le module `Mail` crée des messages et les envoie à n'importe quel serveur. Dans cette référence, `message` désigne un message renvoyé par ces fonctions ou par `Mail.create()`. Le guide [Envoyer des e-mails](../../guides/mail/) explique comment les utiliser avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nRend une vue et l'envoie comme e-mail HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Une adresse e-mail ou un tableau d'adresses ; chacune devient un destinataire `To`. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `view` | `String` | yes |  | Le nom d'une vue de `views/`, par exemple `mails/welcome`. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n| `language` | `String` | no |  | Une langue pour le sujet et la vue. |\n| `callback` | `Function` | no |  | Appelée avec `function(err, message)` quand le message a été écrit sur le serveur, ou avec la ligne de réponse quand le serveur le rejette. |\n\nReturns: `MailMessage` Le message, avant son envoi.\n\nLa vue est rendue sans layout ; le modèle est disponible sous le nom `model`. Avec `language`, le sujet est traduit (un sujet contenant `@(...)` est traduit par parties) et la vue est rendue dans cette langue. Un nom de vue qui commence par `=theme/` est pris dans ce thème. L'expéditeur, l'adresse de réponse et les copies viennent de la configuration. Le message est envoyé au tick suivant, tu peux donc encore le modifier. `callback` peut aussi être le cinquième argument et `language` le sixième.\n\nExample: Un e-mail de bienvenue\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Traduit, avec une pièce jointe\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nEnvoie une chaîne HTML comme e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Une adresse e-mail ou un tableau d'adresses ; chacune devient un destinataire `To`. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le HTML du message. |\n| `language` | `String` | no |  | Une langue pour le sujet et le corps. |\n| `callback` | `Function` | no |  | Appelée avec `function(err, message)` quand le message a été écrit sur le serveur, ou avec la ligne de réponse quand le serveur le rejette. |\n\nReturns: `MailMessage` Le message, avant son envoi.\n\nUn corps sans élément `<body>` est enveloppé dans un document HTML complet avec le sujet comme titre et un `<body>` au CSS normalisé (sans marge, Arial 14px). Avec `language`, le sujet est traduit, ainsi que les textes `@(...)` du corps. `callback` peut aussi être le quatrième argument.\n\nExample: Un message court\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nEnvoie un e-mail de log ou de notification.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Une adresse e-mail ou un tableau d'adresses ; chacune devient un destinataire `To`. |\n| `subject` | `String` | no | `name and version` | Le sujet. |\n| `body` | `String|Object` | yes |  | Le texte ou un objet à sérialiser. |\n| `callback` | `Function` | no |  | Appelée avec `function(err, message)` quand le message a été écrit sur le serveur, ou avec la ligne de réponse quand le serveur le rejette. |\n\nReturns: `MailMessage` Le message, avant son envoi.\n\nLe corps est placé dans un élément `<pre>` ; un objet est sérialisé en JSON. Sans sujet, le sujet est le `name` et la `version` de la configuration, par exemple `My app v1.0.0`.\n\nExample: Notifier l'administrateur\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Seulement un corps\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nRend une vue et l'envoie comme e-mail depuis une action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Une adresse e-mail ou un tableau d'adresses ; chacune devient un destinataire `To`. |\n| `subject` | `String` | yes |  | Le sujet ; les parties `@(...)` sont traduites. |\n| `view` | `String` | yes |  | Le nom d'une vue de `views/`. |\n| `model` | `Object` | no |  | Le modèle de la vue. |\n| `callback` | `Function` | no |  | Appelée avec `function(err, message)` quand le message a été écrit sur le serveur, ou avec la ligne de réponse quand le serveur le rejette. |\n\nReturns: `MailMessage` Le message, avant son envoi.\n\nFonctionne comme `MAIL()` ; le sujet est traduit avec la langue du contrôleur (`this.language`), et la vue est rendue avec elle. Le layout du contrôleur n'est pas utilisé pour l'e-mail.\n\nExample: Après une commande\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nCrée et planifie chaque message de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` et `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Une adresse e-mail ou un tableau d'adresses ; chacune devient un destinataire `To`. |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le corps HTML. |\n| `callback` | `Function` | no |  | Le callback du message. |\n| `replyTo` | `String` | no |  | Une adresse de réponse à la place de `mail_reply`. |\n\nReturns: `MailMessage` Le message.\n\nLe délégué par défaut crée un message avec `Mail.create()`, ajoute les destinataires, définit l'expéditeur à partir de `mail_from` et `name`, ajoute `replyTo` ou `mail_reply`, `mail_bcc` et `mail_cc`, et l'envoie au tick suivant avec `message.send2()`. Remplace-le pour envoyer les e-mails autrement ; il doit renvoyer un objet message, car les appelants le modifient (par exemple avec `manually()`).\n\nExample: Ajouter un en-tête au sujet\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nÉmis pour chaque message juste avant qu'il soit écrit sur le serveur SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Le message en cours d'envoi. |\n\nIl est émis pour les messages envoyés avec la configuration et avec `Mail.send()`.\n\nExample: Auditer les e-mails sortants\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nFait relire `mail_smtp_options` au message suivant.\n\nLes options de la connexion SMTP sont mises en cache après le premier message. Exécute cette commande après avoir modifié `CONF.mail_smtp_options` dans le code. `LOADCONFIG()` et `Mail.use()` vident le cache eux-mêmes.\n\nExample: Changer de compte SMTP\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nLe nom d'hôte du serveur SMTP.\n\nUtilisé par `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` et `Mail.send2()`. Quand il est vide, le framework utilise `smtp.` suivi du domaine de l'adresse de l'expéditeur et l'enregistre ici.\n\nExample: Dans le fichier de configuration\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nLes options de la connexion SMTP.\n\nDans le fichier de configuration, c'est un objet JavaScript écrit sous forme de texte ; dans le code, c'est un objet. Options :\n\n- `port` (par défaut `25`, ou `465` avec `secure`) ;\n- `secure` (par défaut `false`) : TLS dès le départ ; les options sont aussi passées à la connexion TLS ;\n- `user` et `password` : l'identifiant (`AUTH LOGIN` ou `AUTH PLAIN`, selon ce que propose le serveur) ;\n- `token` : un token d'accès OAuth 2.0 pour `AUTH XOAUTH2`, utilisé avec `user` ;\n- `tls` : options de la connexion TLS ; le client met à niveau la connexion avec `STARTTLS` ;\n- `timeout` (par défaut `10000`) : le délai d'expiration du socket en millisecondes.\n\nAvec `user` et `password`, un serveur qui annonce ESMTP reçoit `STARTTLS` avant l'authentification.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Port de soumission avec STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nDurée pendant laquelle une connexion au serveur SMTP reste ouverte pour les messages suivants.\n\nPar défaut `10 minutes`. Utilisé par `message.send2()` tant que l'application exécute un serveur web ; la connexion ouverte est réutilisée pour tous les messages vers le même hôte. Un nombre est exprimé en minutes. `false` ouvre une nouvelle connexion à chaque message.\n\nExample: Fermer après chaque message\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nL'adresse de l'expéditeur des messages envoyés avec la configuration.\n\nLe nom de l'expéditeur est la clé `name` de la configuration. `mail_address_from` est un ancien nom de cette clé.\n\nExample: Expéditeur\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nUne adresse `Reply-To` ajoutée à chaque message envoyé avec la configuration.\n\nNon utilisée quand l'appelant de `DEF.onMail` passe son propre `replyTo`. `mail_address_reply` est un ancien nom de cette clé.\n\nExample: Répondre au support\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nUne adresse `Cc` ajoutée à chaque message envoyé avec la configuration.\n\nExample: Copie\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nUne adresse `Bcc` ajoutée à chaque message envoyé avec la configuration.\n\n`mail_address_copy` est un ancien nom de cette clé.\n\nExample: Archiver chaque message\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nLe module global d'e-mail : crée des messages et les envoie via SMTP.\n\n`Mail` est disponible partout. Il envoie des messages à n'importe quel serveur (`Mail.send()`), avec la configuration (`Mail.send2()`), vérifie un serveur (`Mail.try()`, `Mail.use()`) et émet les événements `send` et `error`.\n\nExample: Un message vers n'importe quel serveur\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nCrée un message vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | Le sujet. |\n| `body` | `String` | yes |  | Le corps, en HTML par défaut. |\n\nReturns: `MailMessage` Un nouveau message.\n\nLe message n'a ni expéditeur ni destinataires, et son type est `html`. Il n'est pas envoyé tant que tu n'appelles pas `message.send()`, `message.send2()`, `Mail.send()` ou `Mail.send2()`.\n\nExample: Créer et envoyer\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nEnvoie un message ou un tableau de messages sur une seule connexion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Le nom d'hôte du serveur SMTP. |\n| `options` | `Object` | no | `{}` | Les options de connexion, identiques à `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | Un message ou un tableau de messages. |\n| `callback` | `Function` | no |  | `function(err)`, appelée une seule fois : quand le premier message a été écrit, ou quand la connexion échoue. |\n| `cache` | `Boolean|Number|String` | no | `false` | Garde la connexion ouverte : `true` pour 10 minutes, un nombre de minutes, ou un texte comme `5 minutes`. |\n\nReturns: `Mail` Le module mail ; rien quand les messages rejoignent une connexion ouverte.\n\nTous les messages passent par une seule connexion, dans leur ordre. `options` peut être omis quand `messages` est un tableau. Avec `cache`, la connexion reste ouverte et les appels suivants pour le même hôte y ajoutent leurs messages ; un tel appel ultérieur n'appelle pas son `callback`, utilise donc `message.callback()` dans ce cas.\n\nExample: Deux messages\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nEnvoie des messages avec `mail_smtp` et `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | Un message ou un tableau de messages. |\n| `callback` | `Function` | no |  | `function(err)`, appelée une seule fois : quand le premier message a été écrit, ou quand la connexion échoue. Utilise `message.callback()` pour chaque message. |\n\nReturns: `Mail` Le module mail.\n\nÉquivaut à `Mail.send()` avec le serveur et les options de la configuration.\n\nExample: Une newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nVérifie un serveur SMTP : se connecte, s'authentifie et quitte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Le nom d'hôte du serveur SMTP. |\n| `options` | `Object` | no | `{}` | Les options de connexion, identiques à `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` Le module mail, ou une promesse en l'absence de callback.\n\nAucun message n'est envoyé. Sans callback, renvoie une promesse qui est rejetée avec l'erreur.\n\nExample: Avec un callback\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: Avec une promesse\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nVérifie un serveur SMTP et, s'il fonctionne, en fait le serveur de la configuration.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Le nom d'hôte du serveur SMTP. |\n| `options` | `Object` | no |  | Les options de connexion. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nAppelle `Mail.try()` ; en cas de succès, définit `CONF.mail_smtp` et `CONF.mail_smtp_options` et vide les options en cache. Sans callback, une erreur est journalisée avec `F.error()`.\n\nExample: Paramètres depuis une base de données\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nAffiche l'échange SMTP dans la console.\n\nReturns: `Boolean`\n\nPar défaut `false`. Chaque commande envoyée et chaque réponse reçue sont affichées.\n\nExample: Déboguer un serveur\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nÉmis quand une connexion ou une commande SMTP échoue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'erreur ou la ligne de réponse du serveur. |\n| `connection` | `Object` | yes |  | L'objet de connexion interne. |\n\nNon émis pour `Mail.try()` ni pour une réinitialisation de connexion. Un message rejeté par le serveur est transmis sous forme de sa ligne de réponse.\n\nExample: Journaliser les erreurs SMTP\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nÉmis quand une connexion au serveur SMTP est prête et que le client commence l'échange.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | L'objet de connexion interne. |\n\nExample: Compter les connexions\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nSupprime un gestionnaire d'un événement de `Mail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement, `error` ou `send`. |\n| `fn` | `Function` | yes |  | Le gestionnaire ajouté avec `Mail.on()`. |\n\nReturns: `Mail` Le module mail.\n\n`Mail.once(name, fn)` ajoute un gestionnaire qui ne s'exécute qu'une fois ; `Mail.removeAllListeners([name])` supprime tous les gestionnaires d'un événement ou de tous les événements.\n\nExample: Arrêter la journalisation\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nAjoute un destinataire `To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `name` | `String` | no |  | Le nom du destinataire. |\n| `clear` | `Boolean` | no | `false` | Supprime les destinataires ajoutés auparavant. |\n\nReturns: `MailMessage` Le message.\n\nL'adresse peut contenir le nom : `Peter Sirka <peter@example.com>`. `clear` peut être le deuxième argument.\n\nExample: Deux destinataires\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nAjoute un destinataire `Cc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `name` | `String` | no |  | Le nom du destinataire. |\n| `clear` | `Boolean` | no | `false` | Supprime les adresses `Cc` ajoutées auparavant. |\n\nReturns: `MailMessage` Le message.\n\nL'adresse peut contenir le nom, comme dans `message.to()`. `clear` peut être le deuxième argument.\n\nExample: Une copie\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nAjoute un destinataire `Bcc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `clear` | `Boolean` | no | `false` | Supprime les adresses `Bcc` ajoutées auparavant, y compris `mail_bcc`. |\n\nReturns: `MailMessage` Le message.\n\nL'adresse n'est pas écrite dans les en-têtes. Utilise une adresse simple, sans nom.\n\nExample: Une copie cachée\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nAjoute une adresse `Reply-To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `clear` | `Boolean` | no | `false` | Supprime les adresses de réponse ajoutées auparavant, y compris `mail_reply`. |\n\nReturns: `MailMessage` Le message.\n\nUtilise une adresse simple, sans nom.\n\nExample: Remplacer l'adresse configurée\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nDéfinit l'expéditeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `name` | `String` | no |  | Le nom de l'expéditeur. |\n\nReturns: `MailMessage` Le message.\n\nL'adresse peut contenir le nom : `My app <info@example.com>`. Les messages créés par `MAIL()` et les autres fonctions globales ont déjà l'expéditeur issu de `mail_from` et `name`.\n\nExample: Expéditeur avec un nom\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nUn alias de `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'adresse e-mail. |\n| `name` | `String` | no |  | Le nom de l'expéditeur. |\n\nReturns: `MailMessage` Le message.\n\nExample: Expéditeur\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nLe sujet du message.\n\nReturns: `String`\n\nTu peux le modifier avant l'envoi du message. Les caractères non ASCII sont encodés pour toi.\n\nExample: Préfixe\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nLe corps du message.\n\nReturns: `String`\n\nHTML par défaut ; voir `message.type`.\n\nExample: Définir le corps plus tard\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nLe type de contenu du corps : `html` ou `plain`.\n\nReturns: `String`\n\nPar défaut `html`. Le corps est envoyé comme `text/` suivi de cette valeur.\n\nExample: Un message en texte brut\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nAjoute un fichier du disque comme pièce jointe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin du fichier. |\n| `name` | `String` | no | `the name of the file` | Le nom du fichier affiché dans l'e-mail. |\n| `contentid` | `String` | no |  | Un Content-ID pour une pièce jointe intégrée, unique dans le message. |\n\nReturns: `MailMessage` Le message.\n\nLe type de contenu vient de l'extension de `name`. Avec `contentid`, le fichier est une pièce jointe intégrée et le HTML le référence avec `cid:contentid`. Un fichier `.ics` est envoyé comme invitation de calendrier.\n\nExample: Un PDF\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: Une image intégrée\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAjoute un fichier d'un `FILESTORAGE()` comme pièce jointe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Le nom du stockage de fichiers. |\n| `id` | `String` | yes |  | L'identifiant du fichier. |\n| `name` | `String` | no | `the stored name` | Le nom du fichier affiché dans l'e-mail. |\n| `contentid` | `String` | no |  | Un Content-ID pour une pièce jointe intégrée. |\n\nReturns: `MailMessage` Le message.\n\nSans `name`, le nom et le type de contenu viennent du fichier stocké. Un fichier qui ne peut pas être lu est ignoré et l'erreur est journalisée.\n\nExample: Un fichier stocké\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nAjoute les en-têtes `List-Unsubscribe`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Une URL ou une adresse e-mail de désabonnement. |\n\nReturns: `MailMessage` Le message.\n\nUne URL qui commence par `http:` ou `https:` est utilisée comme lien ; toute autre valeur est utilisée comme adresse `mailto:`. L'en-tête `List-Unsubscribe-Post: List-Unsubscribe=One-Click` est ajouté aussi.\n\nExample: Une newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nDéfinit le callback du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` Le message.\n\nLe callback s'exécute quand le message a été écrit sur le serveur, ou quand le serveur le rejette ; l'erreur est alors la ligne de réponse du serveur. Les erreurs de connexion ne sont pas transmises ici : elles sont journalisées et émises comme `Mail.on('error')`.\n\nExample: Marquer comme envoyé\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nArrête l'envoi automatique d'un message de `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` ou `controller.mail()`.\n\nReturns: `MailMessage` Le message.\n\nAppelle-la dans la même pile d'appels, puis envoie toi-même le message avec `message.send2()`.\n\nExample: Joindre un fichier généré\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nEnvoie le message avec `mail_smtp` et `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Appelée quand le message a été écrit, sur une nouvelle connexion. |\n\nReturns: `MailMessage` Le message.\n\nSans `mail_smtp`, le serveur est `smtp.` suivi du domaine de l'expéditeur ; sans expéditeur, elle lève `Missing SMTP settings`. Tant que l'application exécute un serveur web, la connexion reste ouverte pendant `mail_smtp_keepalive` ; quand le message part sur une telle connexion ouverte, `callback` n'est pas appelé, préfère donc `message.callback()`.\n\nExample: Envoyer un message créé\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nEnvoie le message à un serveur SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Le nom d'hôte du serveur SMTP. |\n| `options` | `Object` | yes |  | Les options de connexion, identiques à `mail_smtp_options` ; passe `{}` pour aucune. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Garde la connexion ouverte, comme dans `Mail.send()`. |\n\nReturns: `MailMessage` Le message.\n\nUtilise sa propre connexion vers `smtp` ; la configuration n'est pas utilisée.\n\nExample: Un autre serveur\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZ9x1ee61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Mail","summary":"Funzioni email globali, la configurazione delle email, il modulo Mail e l'oggetto messaggio.","markdown":"---\ntitle: Mail\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Mail\n\n> Funzioni email globali, la configurazione delle email, il modulo Mail e l'oggetto messaggio.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `controller.mail()` inviano email con il server SMTP della configurazione; il modulo `Mail` crea e invia messaggi a qualsiasi server. In questo riferimento `message` è un messaggio restituito da queste funzioni o da `Mail.create()`. La guida [Invio di email](../../guides/mail/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nEsegue il rendering di una vista e la invia come email HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Un indirizzo email o un array di indirizzi; ognuno diventa un destinatario `To`. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `view` | `String` | yes |  | Il nome di una vista in `views/`, per esempio `mails/welcome`. |\n| `model` | `Object` | no |  | Il modello della vista. |\n| `language` | `String` | no |  | Una lingua per l'oggetto e la vista. |\n| `callback` | `Function` | no |  | Chiamata con `function(err, message)` quando il messaggio è stato scritto sul server, oppure con la riga di risposta quando il server lo rifiuta. |\n\nReturns: `MailMessage` Il messaggio, prima che venga inviato.\n\nIl rendering della vista avviene senza layout; il modello è disponibile come `model`. Con `language`, l'oggetto viene tradotto (un oggetto con `@(...)` viene tradotto per parti) e il rendering della vista avviene in questa lingua. Un nome di vista che inizia con `=theme/` viene preso da questo tema. Il mittente, il reply-to e le copie provengono dalla configurazione. Il messaggio viene inviato al tick successivo, così puoi ancora modificarlo. `callback` può anche essere il quinto argomento e `language` il sesto.\n\nExample: Un'email di benvenuto\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Tradotta, con un allegato\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nInvia una stringa HTML come email.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Un indirizzo email o un array di indirizzi; ognuno diventa un destinatario `To`. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `body` | `String` | yes |  | L'HTML del messaggio. |\n| `language` | `String` | no |  | Una lingua per l'oggetto e il corpo. |\n| `callback` | `Function` | no |  | Chiamata con `function(err, message)` quando il messaggio è stato scritto sul server, oppure con la riga di risposta quando il server lo rifiuta. |\n\nReturns: `MailMessage` Il messaggio, prima che venga inviato.\n\nUn corpo senza un elemento `<body>` viene racchiuso in un documento HTML completo con l'oggetto come titolo e un `<body>` con CSS normalizzato (nessun margine, Arial 14px). Con `language`, l'oggetto viene tradotto e vengono tradotti anche i testi `@(...)` del corpo. `callback` può anche essere il quarto argomento.\n\nExample: Un messaggio breve\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nInvia un'email di log o di notifica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Un indirizzo email o un array di indirizzi; ognuno diventa un destinatario `To`. |\n| `subject` | `String` | no | `name and version` | L'oggetto. |\n| `body` | `String|Object` | yes |  | Il testo o un oggetto da serializzare. |\n| `callback` | `Function` | no |  | Chiamata con `function(err, message)` quando il messaggio è stato scritto sul server, oppure con la riga di risposta quando il server lo rifiuta. |\n\nReturns: `MailMessage` Il messaggio, prima che venga inviato.\n\nIl corpo viene inserito in un elemento `<pre>`; un oggetto viene serializzato come JSON. Senza oggetto, l'oggetto è il `name` e la `version` della configurazione, per esempio `My app v1.0.0`.\n\nExample: Notificare l'amministratore\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Solo un corpo\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nEsegue il rendering di una vista e la invia come email da un'azione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Un indirizzo email o un array di indirizzi; ognuno diventa un destinatario `To`. |\n| `subject` | `String` | yes |  | L'oggetto; le parti `@(...)` vengono tradotte. |\n| `view` | `String` | yes |  | Il nome di una vista in `views/`. |\n| `model` | `Object` | no |  | Il modello della vista. |\n| `callback` | `Function` | no |  | Chiamata con `function(err, message)` quando il messaggio è stato scritto sul server, oppure con la riga di risposta quando il server lo rifiuta. |\n\nReturns: `MailMessage` Il messaggio, prima che venga inviato.\n\nFunziona come `MAIL()`; l'oggetto viene tradotto con la lingua del controller (`this.language`) e il rendering della vista avviene con essa. Il layout del controller non viene usato per l'email.\n\nExample: Dopo un ordine\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nCrea e pianifica ogni messaggio di `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` e `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Un indirizzo email o un array di indirizzi; ognuno diventa un destinatario `To`. |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `body` | `String` | yes |  | Il corpo HTML. |\n| `callback` | `Function` | no |  | La callback del messaggio. |\n| `replyTo` | `String` | no |  | Un indirizzo di reply-to al posto di `mail_reply`. |\n\nReturns: `MailMessage` Il messaggio.\n\nIl delegato predefinito crea un messaggio con `Mail.create()`, aggiunge i destinatari, imposta il mittente da `mail_from` e `name`, aggiunge `replyTo` o `mail_reply`, `mail_bcc` e `mail_cc`, e lo invia al tick successivo con `message.send2()`. Sostituiscilo per inviare email in un altro modo; deve restituire un oggetto messaggio, perché i chiamanti lo modificano (per esempio con `manually()`).\n\nExample: Aggiungere un'intestazione all'oggetto\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nEmesso per ogni messaggio appena prima che venga scritto sul server SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Il messaggio in fase di invio. |\n\nViene emesso per i messaggi inviati con la configurazione e con `Mail.send()`.\n\nExample: Verificare le email in uscita\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nFa sì che il messaggio successivo legga di nuovo `mail_smtp_options`.\n\nLe opzioni della connessione SMTP vengono messe in cache dopo il primo messaggio. Esegui questo comando dopo aver modificato `CONF.mail_smtp_options` nel codice. `LOADCONFIG()` e `Mail.use()` svuotano la cache da soli.\n\nExample: Cambiare l'account SMTP\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nIl nome host del server SMTP.\n\nUsato da `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` e `Mail.send2()`. Quando è vuoto, il framework usa `smtp.` più il dominio dell'indirizzo del mittente e lo salva qui.\n\nExample: Nel file di configurazione\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nLe opzioni della connessione SMTP.\n\nNel file di configurazione è un oggetto JavaScript scritto come testo; nel codice è un oggetto. Opzioni:\n\n- `port` (predefinito `25`, oppure `465` con `secure`);\n- `secure` (predefinito `false`): TLS fin dall'inizio; le opzioni vengono passate anche alla connessione TLS;\n- `user` e `password`: le credenziali di accesso (`AUTH LOGIN` o `AUTH PLAIN`, a seconda di cosa offre il server);\n- `token`: un access token OAuth 2.0 per `AUTH XOAUTH2`, usato con `user`;\n- `tls`: opzioni della connessione TLS; il client aggiorna la connessione con `STARTTLS`;\n- `timeout` (predefinito `10000`): il timeout del socket in millisecondi.\n\nCon `user` e `password`, un server che annuncia ESMTP riceve `STARTTLS` prima dell'accesso.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Porta di submission con STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nPer quanto tempo una connessione al server SMTP resta aperta per i messaggi successivi.\n\nPredefinito `10 minutes`. Viene usato da `message.send2()` mentre l'applicazione esegue un web server; la connessione aperta viene riutilizzata per tutti i messaggi verso lo stesso host. Un numero è espresso in minuti. `false` apre una nuova connessione per ogni messaggio.\n\nExample: Chiudere dopo ogni messaggio\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nL'indirizzo del mittente dei messaggi inviati con la configurazione.\n\nIl nome del mittente è la chiave `name` della configurazione. `mail_address_from` è un nome più vecchio di questa chiave.\n\nExample: Mittente\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nUn indirizzo `Reply-To` aggiunto a ogni messaggio inviato con la configurazione.\n\nNon viene usato quando il chiamante di `DEF.onMail` passa un proprio `replyTo`. `mail_address_reply` è un nome più vecchio di questa chiave.\n\nExample: Rispondere al supporto\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nUn indirizzo `Cc` aggiunto a ogni messaggio inviato con la configurazione.\n\nExample: Copia\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nUn indirizzo `Bcc` aggiunto a ogni messaggio inviato con la configurazione.\n\n`mail_address_copy` è un nome più vecchio di questa chiave.\n\nExample: Archiviare ogni messaggio\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nIl modulo email globale: crea i messaggi e li invia via SMTP.\n\n`Mail` è disponibile ovunque. Invia messaggi a qualsiasi server (`Mail.send()`), con la configurazione (`Mail.send2()`), verifica un server (`Mail.try()`, `Mail.use()`) ed emette gli eventi `send` ed `error`.\n\nExample: Un messaggio a qualsiasi server\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nCrea un messaggio vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | L'oggetto. |\n| `body` | `String` | yes |  | Il corpo, HTML per impostazione predefinita. |\n\nReturns: `MailMessage` Un nuovo messaggio.\n\nIl messaggio non ha mittente né destinatari, e il suo tipo è `html`. Non viene inviato finché non chiami `message.send()`, `message.send2()`, `Mail.send()` o `Mail.send2()`.\n\nExample: Creare e inviare\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nInvia un messaggio o un array di messaggi su un'unica connessione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Il nome host del server SMTP. |\n| `options` | `Object` | no | `{}` | Le opzioni di connessione, le stesse di `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | Un messaggio o un array di messaggi. |\n| `callback` | `Function` | no |  | `function(err)`, chiamata una sola volta: quando il primo messaggio è stato scritto, oppure quando la connessione fallisce. |\n| `cache` | `Boolean|Number|String` | no | `false` | Mantiene aperta la connessione: `true` per 10 minuti, un numero di minuti, oppure un testo come `5 minutes`. |\n\nReturns: `Mail` Il modulo email; nulla quando i messaggi si aggiungono a una connessione aperta.\n\nTutti i messaggi passano attraverso un'unica connessione, nel loro ordine. `options` può essere omesso quando `messages` è un array. Con `cache`, la connessione resta aperta e le chiamate successive per lo stesso host vi aggiungono i loro messaggi; una tale chiamata successiva non chiama la sua `callback`, quindi lì usa `message.callback()`.\n\nExample: Due messaggi\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nInvia messaggi con `mail_smtp` e `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | Un messaggio o un array di messaggi. |\n| `callback` | `Function` | no |  | `function(err)`, chiamata una sola volta: quando il primo messaggio è stato scritto, oppure quando la connessione fallisce. Usa `message.callback()` per ogni messaggio. |\n\nReturns: `Mail` Il modulo email.\n\nEquivale a `Mail.send()` con il server e le opzioni della configurazione.\n\nExample: Una newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nVerifica un server SMTP: si connette, si autentica ed esce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Il nome host del server SMTP. |\n| `options` | `Object` | no | `{}` | Le opzioni di connessione, le stesse di `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` Il modulo email, oppure una promise senza callback.\n\nNon viene inviato alcun messaggio. Senza callback restituisce una promise che viene rifiutata con l'errore.\n\nExample: Con una callback\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: Con una promise\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nVerifica un server SMTP e, se funziona, lo rende il server della configurazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Il nome host del server SMTP. |\n| `options` | `Object` | no |  | Le opzioni di connessione. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nChiama `Mail.try()`; in caso di successo imposta `CONF.mail_smtp` e `CONF.mail_smtp_options` e svuota le opzioni in cache. Senza callback, un errore viene registrato nel log con `F.error()`.\n\nExample: Impostazioni da un database\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nStampa nella console la conversazione SMTP.\n\nReturns: `Boolean`\n\nPredefinito `false`. Ogni comando inviato e ogni risposta ricevuta vengono stampati.\n\nExample: Fare il debug di un server\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nEmesso quando una connessione o un comando SMTP fallisce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'errore o la riga di risposta del server. |\n| `connection` | `Object` | yes |  | L'oggetto di connessione interno. |\n\nNon viene emesso per `Mail.try()` né per un reset della connessione. Un messaggio rifiutato dal server viene passato come la sua riga di risposta.\n\nExample: Registrare nel log gli errori SMTP\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nEmesso quando una connessione al server SMTP è pronta e il client inizia la conversazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | L'oggetto di connessione interno. |\n\nExample: Contare le connessioni\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nRimuove un gestore di un evento di `Mail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento, `error` o `send`. |\n| `fn` | `Function` | yes |  | Il gestore aggiunto con `Mail.on()`. |\n\nReturns: `Mail` Il modulo email.\n\n`Mail.once(name, fn)` aggiunge un gestore che viene eseguito una volta; `Mail.removeAllListeners([name])` rimuove tutti i gestori di un evento o di tutti gli eventi.\n\nExample: Smettere di registrare nel log\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nAggiunge un destinatario `To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `name` | `String` | no |  | Il nome del destinatario. |\n| `clear` | `Boolean` | no | `false` | Rimuove i destinatari aggiunti in precedenza. |\n\nReturns: `MailMessage` Il messaggio.\n\nL'indirizzo può contenere il nome: `Peter Sirka <peter@example.com>`. `clear` può essere il secondo argomento.\n\nExample: Due destinatari\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nAggiunge un destinatario `Cc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `name` | `String` | no |  | Il nome del destinatario. |\n| `clear` | `Boolean` | no | `false` | Rimuove gli indirizzi `Cc` aggiunti in precedenza. |\n\nReturns: `MailMessage` Il messaggio.\n\nL'indirizzo può contenere il nome, come in `message.to()`. `clear` può essere il secondo argomento.\n\nExample: Una copia\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nAggiunge un destinatario `Bcc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `clear` | `Boolean` | no | `false` | Rimuove gli indirizzi `Bcc` aggiunti in precedenza, incluso `mail_bcc`. |\n\nReturns: `MailMessage` Il messaggio.\n\nL'indirizzo non viene scritto negli header. Usa un indirizzo semplice senza nome.\n\nExample: Una copia nascosta\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nAggiunge un indirizzo `Reply-To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `clear` | `Boolean` | no | `false` | Rimuove gli indirizzi di risposta aggiunti in precedenza, incluso `mail_reply`. |\n\nReturns: `MailMessage` Il messaggio.\n\nUsa un indirizzo semplice senza nome.\n\nExample: Sostituire l'indirizzo configurato\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nImposta il mittente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `name` | `String` | no |  | Il nome del mittente. |\n\nReturns: `MailMessage` Il messaggio.\n\nL'indirizzo può contenere il nome: `My app <info@example.com>`. I messaggi creati da `MAIL()` e dalle altre funzioni globali hanno già il mittente da `mail_from` e `name`.\n\nExample: Mittente con un nome\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nUn alias di `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | L'indirizzo email. |\n| `name` | `String` | no |  | Il nome del mittente. |\n\nReturns: `MailMessage` Il messaggio.\n\nExample: Mittente\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nL'oggetto del messaggio.\n\nReturns: `String`\n\nPuoi modificarlo prima che il messaggio venga inviato. I caratteri non ASCII vengono codificati al posto tuo.\n\nExample: Prefisso\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nIl corpo del messaggio.\n\nReturns: `String`\n\nHTML per impostazione predefinita; vedi `message.type`.\n\nExample: Impostare il corpo in seguito\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nIl content type del corpo: `html` o `plain`.\n\nReturns: `String`\n\nPredefinito `html`. Il corpo viene inviato come `text/` più questo valore.\n\nExample: Un messaggio in testo semplice\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nAggiunge un file dal disco come allegato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso del file. |\n| `name` | `String` | no | `the name of the file` | Il nome del file mostrato nell'email. |\n| `contentid` | `String` | no |  | Un Content-ID per un allegato inline, univoco nel messaggio. |\n\nReturns: `MailMessage` Il messaggio.\n\nIl content type deriva dall'estensione di `name`. Con `contentid`, il file è un allegato inline e l'HTML vi fa riferimento come `cid:contentid`. Un file `.ics` viene inviato come invito di calendario.\n\nExample: Un PDF\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: Un'immagine inline\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nAggiunge un file da un `FILESTORAGE()` come allegato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Il nome dello storage dei file. |\n| `id` | `String` | yes |  | L'identificatore del file. |\n| `name` | `String` | no | `the stored name` | Il nome del file mostrato nell'email. |\n| `contentid` | `String` | no |  | Un Content-ID per un allegato inline. |\n\nReturns: `MailMessage` Il messaggio.\n\nSenza `name`, il nome e il content type provengono dal file salvato. Un file che non può essere letto viene saltato e l'errore viene registrato nel log.\n\nExample: Un file salvato\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nAggiunge gli header `List-Unsubscribe`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un URL o un indirizzo email per la disiscrizione. |\n\nReturns: `MailMessage` Il messaggio.\n\nUn URL che inizia con `http:` o `https:` viene usato come link; qualsiasi altro valore viene usato come indirizzo `mailto:`. Viene aggiunto anche l'header `List-Unsubscribe-Post: List-Unsubscribe=One-Click`.\n\nExample: Una newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nImposta la callback del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` Il messaggio.\n\nLa callback viene eseguita quando il messaggio è stato scritto sul server, oppure quando il server lo rifiuta; l'errore è allora la riga di risposta del server. Gli errori di connessione non vengono passati qui: vengono registrati nel log ed emessi come `Mail.on('error')`.\n\nExample: Segnare come inviato\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nFerma l'invio automatico di un messaggio da `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` o `controller.mail()`.\n\nReturns: `MailMessage` Il messaggio.\n\nChiamalo nello stesso call stack, poi invia tu stesso il messaggio con `message.send2()`.\n\nExample: Allegare un file generato\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nInvia il messaggio con `mail_smtp` e `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Chiamata quando il messaggio è stato scritto, su una nuova connessione. |\n\nReturns: `MailMessage` Il messaggio.\n\nSenza `mail_smtp`, il server è `smtp.` più il dominio del mittente; senza un mittente lancia `Missing SMTP settings`. Mentre l'applicazione esegue un web server, la connessione viene mantenuta aperta per `mail_smtp_keepalive`; quando il messaggio va su una connessione già aperta, `callback` non viene chiamata, quindi preferisci `message.callback()`.\n\nExample: Inviare un messaggio creato\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nInvia il messaggio a un server SMTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Il nome host del server SMTP. |\n| `options` | `Object` | yes |  | Le opzioni di connessione, le stesse di `mail_smtp_options`; passa `{}` per nessuna. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Mantiene aperta la connessione, come in `Mail.send()`. |\n\nReturns: `MailMessage` Il messaggio.\n\nUsa una propria connessione verso `smtp`; la configurazione non viene usata.\n\nExample: Un altro server\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabZ9x1ee61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/mail/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Mail","summary":"Globálne funkcie pre e-maily, konfigurácia e-mailov, modul Mail a objekt správy.","markdown":"---\ntitle: Mail\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/mail/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Mail\n\n> Globálne funkcie pre e-maily, konfigurácia e-mailov, modul Mail a objekt správy.\n\n`MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `controller.mail()` odosielajú e-maily cez SMTP server z konfigurácie; modul `Mail` vytvára správy a posiela ich na ľubovoľný server. V tejto referencii je `message` správa, ktorú vrátili tieto funkcie alebo `Mail.create()`. Príručka [Odosielanie e-mailov](../../guides/mail/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### MAIL(address, subject, view, [model], [language], [callback])\n\nType: `method`\n\nVykreslí view a pošle ho ako HTML e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Jedna e-mailová adresa alebo pole adries; každá sa stane príjemcom `To`. |\n| `subject` | `String` | yes |  | Predmet. |\n| `view` | `String` | yes |  | Názov view vo `views/`, napríklad `mails/welcome`. |\n| `model` | `Object` | no |  | Model view. |\n| `language` | `String` | no |  | Jazyk pre predmet a view. |\n| `callback` | `Function` | no |  | Volá sa s `function(err, message)`, keď bola správa zapísaná na server, alebo s riadkom odpovede, keď ju server odmietne. |\n\nReturns: `MailMessage` Správa pred odoslaním.\n\nView sa vykreslí bez layoutu; model je dostupný ako `model`. S `language` sa preloží predmet (predmet s `@(...)` sa prekladá po častiach) a view sa vykreslí v tomto jazyku. Názov view, ktorý začína na `=theme/`, sa vezme z tejto témy. Odosielateľ, reply-to a kópie pochádzajú z konfigurácie. Správa sa odošle v ďalšom ticku, takže ju môžeš ešte zmeniť. `callback` môže byť aj piaty argument a `language` šiesty.\n\nExample: Uvítací e-mail\n```js\nMAIL('peter@example.com', 'Welcome', 'mails/welcome', { name: 'Peter' }, function(err) {\n\terr && console.log('Not sent', err);\n});\n```\n\nExample: Preložený, s prílohou\n```js\nMAIL(user.email, '@(Your invoice)', 'mails/invoice', invoice, user.language).attachment(filename, 'invoice.pdf');\n```\n\n### HTMLMAIL(address, subject, body, [language], [callback])\n\nType: `method`\n\nPošle HTML reťazec ako e-mail.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Jedna e-mailová adresa alebo pole adries; každá sa stane príjemcom `To`. |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | HTML správy. |\n| `language` | `String` | no |  | Jazyk pre predmet a telo. |\n| `callback` | `Function` | no |  | Volá sa s `function(err, message)`, keď bola správa zapísaná na server, alebo s riadkom odpovede, keď ju server odmietne. |\n\nReturns: `MailMessage` Správa pred odoslaním.\n\nTelo bez prvku `<body>` sa zabalí do celého HTML dokumentu s predmetom ako titulkom a s `<body>` s normalizovaným CSS (bez okrajov, Arial 14px). S `language` sa preloží predmet a preložia sa aj texty `@(...)` v tele. `callback` môže byť aj štvrtý argument.\n\nExample: Krátka správa\n```js\nHTMLMAIL('peter@example.com', 'Reset password', '<p>Your code is <b>' + code + '</b>.</p>');\n```\n\n### LOGMAIL(address, [subject], body, [callback])\n\nType: `method`\n\nPošle e-mail s logom alebo notifikáciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Jedna e-mailová adresa alebo pole adries; každá sa stane príjemcom `To`. |\n| `subject` | `String` | no | `name and version` | Predmet. |\n| `body` | `String|Object` | yes |  | Text alebo objekt na serializáciu. |\n| `callback` | `Function` | no |  | Volá sa s `function(err, message)`, keď bola správa zapísaná na server, alebo s riadkom odpovede, keď ju server odmietne. |\n\nReturns: `MailMessage` Správa pred odoslaním.\n\nTelo sa vloží do prvku `<pre>`; objekt sa serializuje ako JSON. Bez predmetu je predmetom `name` a `version` z konfigurácie, napríklad `My app v1.0.0`.\n\nExample: Upozornenie administrátora\n```js\nLOGMAIL('admin@example.com', 'New order', { id: order.id, price: order.price });\n```\n\nExample: Len telo\n```js\nLOGMAIL('admin@example.com', 'The import has finished.');\n```\n\n### controller.mail(address, subject, view, [model], [callback])\n\nType: `method`\n\nVykreslí view a pošle ho ako e-mail z akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Jedna e-mailová adresa alebo pole adries; každá sa stane príjemcom `To`. |\n| `subject` | `String` | yes |  | Predmet; časti `@(...)` sa prekladajú. |\n| `view` | `String` | yes |  | Názov view vo `views/`. |\n| `model` | `Object` | no |  | Model view. |\n| `callback` | `Function` | no |  | Volá sa s `function(err, message)`, keď bola správa zapísaná na server, alebo s riadkom odpovede, keď ju server odmietne. |\n\nReturns: `MailMessage` Správa pred odoslaním.\n\nFunguje ako `MAIL()`; predmet sa preloží do jazyka kontroléra (`this.language`) a view sa v ňom vykreslí. Layout kontroléra sa pre e-mail nepoužije.\n\nExample: Po objednávke\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', order);\n};\n\nfunction order() {\n\tvar self = this;\n\tself.mail(self.body.email, '@(Your order)', 'mails/order', self.body);\n\tself.success();\n}\n```\n\n### DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}\n\nType: `delegate`\n\nVytvorí a naplánuje každú správu z `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` a `controller.mail()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String|Array` | yes |  | Jedna e-mailová adresa alebo pole adries; každá sa stane príjemcom `To`. |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | HTML telo. |\n| `callback` | `Function` | no |  | Callback správy. |\n| `replyTo` | `String` | no |  | Adresa reply-to namiesto `mail_reply`. |\n\nReturns: `MailMessage` Správa.\n\nPredvolený delegát vytvorí správu pomocou `Mail.create()`, pridá príjemcov, nastaví odosielateľa z `mail_from` a `name`, pridá `replyTo` alebo `mail_reply`, `mail_bcc` a `mail_cc` a odošle ju v ďalšom ticku pomocou `message.send2()`. Nahraď ho, ak chceš e-maily posielať inak; musí vrátiť objekt správy, pretože volajúci ho menia (napríklad pomocou `manually()`).\n\nExample: Pridanie hlavičky k predmetu\n```js\nvar onmail = DEF.onMail;\n\nDEF.onMail = function(address, subject, body, callback, replyTo) {\n\treturn onmail(address, '[My app] ' + subject, body, callback, replyTo);\n};\n```\n\n### ON('mail', function(message) {})\n\nType: `event`\n\nEmituje sa pre každú správu tesne pred jej zápisom na SMTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Odosielaná správa. |\n\nEmituje sa pre správy odosielané s konfiguráciou aj pomocou `Mail.send()`.\n\nExample: Audit odchádzajúcich e-mailov\n```js\nON('mail', function(message) {\n\tconsole.log('Mail to', message.address_to, message.subject);\n});\n```\n\n### CMD('clear_smtpcache')\n\nType: `command`\n\nZabezpečí, že ďalšia správa znova načíta `mail_smtp_options`.\n\nMožnosti SMTP spojenia sa po prvej správe uložia do cache. Tento príkaz spusti, keď v kóde zmeníš `CONF.mail_smtp_options`. `LOADCONFIG()` a `Mail.use()` cache vymažú samy.\n\nExample: Zmena SMTP účtu\n```js\nCONF.mail_smtp = 'smtp.example.com';\nCONF.mail_smtp_options = { port: 465, secure: true, user: 'info@example.com', password: 'secret' };\nCMD('clear_smtpcache');\n```\n\n### mail_smtp : smtp.example.com\n\nType: `config`\n\nNázov hostiteľa SMTP servera.\n\nPoužívajú ho `MAIL()`, `HTMLMAIL()`, `LOGMAIL()`, `controller.mail()`, `message.send2()` a `Mail.send2()`. Keď je prázdny, framework použije `smtp.` plus doménu adresy odosielateľa a uloží to sem.\n\nExample: V konfiguračnom súbore\n```text\nmail_smtp : smtp.example.com\n```\n\n### mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }\n\nType: `config`\n\nMožnosti SMTP spojenia.\n\nV konfiguračnom súbore je to JavaScript objekt zapísaný ako text; v kóde je to objekt. Možnosti:\n\n- `port` (predvolene `25` alebo `465` so `secure`);\n- `secure` (predvolene `false`): TLS od začiatku; možnosti sa odovzdajú aj TLS spojeniu;\n- `user` a `password`: prihlasovacie údaje (`AUTH LOGIN` alebo `AUTH PLAIN` podľa toho, čo server ponúka);\n- `token`: prístupový token OAuth 2.0 pre `AUTH XOAUTH2`, používa sa s `user`;\n- `tls`: možnosti TLS spojenia; klient spojenie povýši pomocou `STARTTLS`;\n- `timeout` (predvolene `10000`): časový limit socketu v milisekundách.\n\nS `user` a `password` dostane server, ktorý ohlási ESMTP, pred prihlásením `STARTTLS`.\n\nExample: SMTPS\n```text\nmail_smtp_options : { port: 465, secure: true, user: 'info@example.com', password: 'secret' }\n```\n\nExample: Port submission so STARTTLS\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', password: 'secret' }\n```\n\nExample: OAuth 2.0\n```text\nmail_smtp_options : { port: 587, user: 'info@example.com', token: 'ya29...' }\n```\n\n### mail_smtp_keepalive : 10 minutes\n\nType: `config`\n\nAko dlho zostáva spojenie so SMTP serverom otvorené pre ďalšie správy.\n\nPredvolene `10 minutes`. Používa ho `message.send2()`, kým aplikácia beží ako webový server; otvorené spojenie sa opakovane používa pre všetky správy na toho istého hostiteľa. Číslo je v minútach. `false` otvorí pre každú správu nové spojenie.\n\nExample: Zatvorenie po každej správe\n```text\nmail_smtp_keepalive : false\n```\n\n### mail_from : info@example.com\n\nType: `config`\n\nAdresa odosielateľa správ odosielaných s konfiguráciou.\n\nMeno odosielateľa je kľúč `name` konfigurácie. `mail_address_from` je starší názov tohto kľúča.\n\nExample: Odosielateľ\n```text\nname      : My app\nmail_from : info@example.com\n```\n\n### mail_reply : support@example.com\n\nType: `config`\n\nAdresa `Reply-To` pridaná ku každej správe odosielanej s konfiguráciou.\n\nNepoužije sa, keď volajúci `DEF.onMail` odovzdá vlastné `replyTo`. `mail_address_reply` je starší názov tohto kľúča.\n\nExample: Odpoveď na podporu\n```text\nmail_reply : support@example.com\n```\n\n### mail_cc : office@example.com\n\nType: `config`\n\nAdresa `Cc` pridaná ku každej správe odosielanej s konfiguráciou.\n\nExample: Kópia\n```text\nmail_cc : office@example.com\n```\n\n### mail_bcc : archive@example.com\n\nType: `config`\n\nAdresa `Bcc` pridaná ku každej správe odosielanej s konfiguráciou.\n\n`mail_address_copy` je starší názov tohto kľúča.\n\nExample: Archivovanie každej správy\n```text\nmail_bcc : archive@example.com\n```\n\n### Mail\n\nType: `class`\n\nGlobálny modul pre e-maily: vytvára správy a odosiela ich cez SMTP.\n\n`Mail` je dostupný všade. Posiela správy na ľubovoľný server (`Mail.send()`), s konfiguráciou (`Mail.send2()`), overuje server (`Mail.try()`, `Mail.use()`) a emituje udalosti `send` a `error`.\n\nExample: Správa na ľubovoľný server\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from('info@example.com');\nmessage.to('peter@example.com');\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [message], NOOP);\n```\n\n### Mail.create(subject, body)\n\nType: `method`\n\nVytvorí prázdnu správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `subject` | `String` | yes |  | Predmet. |\n| `body` | `String` | yes |  | Telo, predvolene HTML. |\n\nReturns: `MailMessage` Nová správa.\n\nSpráva nemá odosielateľa ani príjemcov a jej typ je `html`. Neodošle sa, kým nezavoláš `message.send()`, `message.send2()`, `Mail.send()` alebo `Mail.send2()`.\n\nExample: Vytvorenie a odoslanie\n```js\nvar message = Mail.create('Report', '<p>See the attachment.</p>');\nmessage.from('info@example.com', 'My app');\nmessage.to('peter@example.com');\nmessage.attachment(PATH.root('report.pdf'));\nmessage.send2();\n```\n\n### Mail.send(smtp, [options], messages, [callback], [cache])\n\nType: `method`\n\nPošle jednu správu alebo pole správ cez jedno spojenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Názov hostiteľa SMTP servera. |\n| `options` | `Object` | no | `{}` | Možnosti spojenia, rovnaké ako `mail_smtp_options`. |\n| `messages` | `MailMessage|Array` | yes |  | Správa alebo pole správ. |\n| `callback` | `Function` | no |  | `function(err)`, volá sa raz: keď bola zapísaná prvá správa, alebo keď spojenie zlyhá. |\n| `cache` | `Boolean|Number|String` | no | `false` | Ponechá spojenie otvorené: `true` na 10 minút, počet minút alebo text ako `5 minutes`. |\n\nReturns: `Mail` Modul mail; nič, keď sa správy pripoja k otvorenému spojeniu.\n\nVšetky správy idú cez jedno spojenie v poradí. `options` môžeš vynechať, keď je `messages` pole. S `cache` zostane spojenie otvorené a neskoršie volania pre toho istého hostiteľa doň pridajú svoje správy; takéto neskoršie volanie nezavolá svoj `callback`, preto tam použi `message.callback()`.\n\nExample: Dve správy\n```js\nMail.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, [a, b], function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.send2(messages, [callback])\n\nType: `method`\n\nPošle správy s `mail_smtp` a `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `messages` | `MailMessage|Array` | yes |  | Správa alebo pole správ. |\n| `callback` | `Function` | no |  | `function(err)`, volá sa raz: keď bola zapísaná prvá správa, alebo keď spojenie zlyhá. Pre každú správu použi `message.callback()`. |\n\nReturns: `Mail` Modul mail.\n\nTo isté ako `Mail.send()` so serverom a možnosťami z konfigurácie.\n\nExample: Newsletter\n```js\nvar messages = users.map(function(user) {\n\tvar message = Mail.create('News', html);\n\tmessage.from(CONF.mail_from, CONF.name);\n\tmessage.to(user.email);\n\treturn message;\n});\n\nMail.send2(messages, function(err) {\n\terr && console.log(err);\n});\n```\n\n### Mail.try(smtp, [options], [callback])\n\nType: `method`\n\nOverí SMTP server: pripojí sa, prihlási a skončí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Názov hostiteľa SMTP servera. |\n| `options` | `Object` | no | `{}` | Možnosti spojenia, rovnaké ako `mail_smtp_options`. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `Mail|Promise` Modul mail alebo promise bez callbacku.\n\nNeodošle sa žiadna správa. Bez callbacku vráti promise, ktorý sa zamietne s chybou.\n\nExample: S callbackom\n```js\nMail.try('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Works');\n});\n```\n\nExample: S promise\n```js\ntry {\n\tawait Mail.try('smtp.example.com', { port: 587, user: 'info@example.com', password: 'secret' });\n} catch (err) {\n\tconsole.log('SMTP failed', err);\n}\n```\n\n### Mail.use(smtp, [options], [callback])\n\nType: `method`\n\nOverí SMTP server a ak funguje, nastaví ho ako server konfigurácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Názov hostiteľa SMTP servera. |\n| `options` | `Object` | no |  | Možnosti spojenia. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nZavolá `Mail.try()`; pri úspechu nastaví `CONF.mail_smtp` a `CONF.mail_smtp_options` a vymaže možnosti v cache. Bez callbacku sa chyba zaloguje pomocou `F.error()`.\n\nExample: Nastavenia z databázy\n```js\nMail.use(settings.smtp, settings.smtpoptions, function(err) {\n\terr && console.log('SMTP is not available', err);\n});\n```\n\n### Mail.debug = true\n\nType: `property`\n\nVypíše SMTP komunikáciu do konzoly.\n\nReturns: `Boolean`\n\nPredvolene `false`. Vypíše sa každý odoslaný príkaz a každá prijatá odpoveď.\n\nExample: Ladenie servera\n```js\nMail.debug = true;\n```\n\n### Mail.on('error', function(err, connection) {})\n\nType: `event`\n\nEmituje sa, keď zlyhá spojenie alebo SMTP príkaz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Chyba alebo riadok odpovede servera. |\n| `connection` | `Object` | yes |  | Interný objekt spojenia. |\n\nNeemituje sa pre `Mail.try()` ani pri resetovaní spojenia. Správa odmietnutá serverom sa odovzdá ako jeho riadok odpovede.\n\nExample: Logovanie SMTP chýb\n```js\nMail.on('error', function(err) {\n\tconsole.log('SMTP error', err);\n});\n```\n\n### Mail.on('send', function(connection) {})\n\nType: `event`\n\nEmituje sa, keď je spojenie so SMTP serverom pripravené a klient začína komunikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `connection` | `Object` | yes |  | Interný objekt spojenia. |\n\nExample: Počítanie spojení\n```js\nMail.on('send', function() {\n\tconsole.log('SMTP connection');\n});\n```\n\n### Mail.removeListener(name, fn)\n\nType: `method`\n\nOdstráni obsluhu udalosti `Mail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti, `error` alebo `send`. |\n| `fn` | `Function` | yes |  | Obsluha pridaná pomocou `Mail.on()`. |\n\nReturns: `Mail` Modul mail.\n\n`Mail.once(name, fn)` pridá obsluhu, ktorá sa spustí raz; `Mail.removeAllListeners([name])` odstráni všetky obsluhy jednej udalosti alebo všetkých udalostí.\n\nExample: Zastavenie logovania\n```js\nfunction log(err) {\n\tconsole.log(err);\n}\n\nMail.on('error', log);\nMail.removeListener('error', log);\n```\n\n### message.to(address, [name], [clear])\n\nType: `method`\n\nPridá príjemcu `To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `name` | `String` | no |  | Meno príjemcu. |\n| `clear` | `Boolean` | no | `false` | Odstráni predtým pridaných príjemcov. |\n\nReturns: `MailMessage` Správa.\n\nAdresa môže obsahovať meno: `Peter Sirka <peter@example.com>`. `clear` môže byť druhý argument.\n\nExample: Dvaja príjemcovia\n```js\nmessage.to('peter@example.com', 'Peter');\nmessage.to('Lucia <lucia@example.com>');\n```\n\n### message.cc(address, [name], [clear])\n\nType: `method`\n\nPridá príjemcu `Cc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `name` | `String` | no |  | Meno príjemcu. |\n| `clear` | `Boolean` | no | `false` | Odstráni predtým pridané adresy `Cc`. |\n\nReturns: `MailMessage` Správa.\n\nAdresa môže obsahovať meno, ako v `message.to()`. `clear` môže byť druhý argument.\n\nExample: Kópia\n```js\nmessage.cc('office@example.com');\n```\n\n### message.bcc(address, [clear])\n\nType: `method`\n\nPridá príjemcu `Bcc`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `clear` | `Boolean` | no | `false` | Odstráni predtým pridané adresy `Bcc`, vrátane `mail_bcc`. |\n\nReturns: `MailMessage` Správa.\n\nAdresa sa nezapíše do hlavičiek. Použi obyčajnú adresu bez mena.\n\nExample: Skrytá kópia\n```js\nmessage.bcc('archive@example.com');\n```\n\n### message.reply(address, [clear])\n\nType: `method`\n\nPridá adresu `Reply-To`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `clear` | `Boolean` | no | `false` | Odstráni predtým pridané adresy na odpoveď, vrátane `mail_reply`. |\n\nReturns: `MailMessage` Správa.\n\nPouži obyčajnú adresu bez mena.\n\nExample: Nahradenie nakonfigurovanej adresy\n```js\nmessage.reply('billing@example.com', true);\n```\n\n### message.from(address, [name])\n\nType: `method`\n\nNastaví odosielateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `name` | `String` | no |  | Meno odosielateľa. |\n\nReturns: `MailMessage` Správa.\n\nAdresa môže obsahovať meno: `My app <info@example.com>`. Správy vytvorené pomocou `MAIL()` a ostatných globálnych funkcií už majú odosielateľa z `mail_from` a `name`.\n\nExample: Odosielateľ s menom\n```js\nmessage.from('info@example.com', 'My app');\n```\n\n### message.sender(address, [name])\n\nType: `method`\n\nAlias metódy `message.from()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `address` | `String` | yes |  | E-mailová adresa. |\n| `name` | `String` | no |  | Meno odosielateľa. |\n\nReturns: `MailMessage` Správa.\n\nExample: Odosielateľ\n```js\nmessage.sender('info@example.com', 'My app');\n```\n\n### message.subject\n\nType: `property`\n\nPredmet správy.\n\nReturns: `String`\n\nMôžeš ho zmeniť pred odoslaním správy. Znaky mimo ASCII sa zakódujú za teba.\n\nExample: Prefix\n```js\nmessage.subject = '[Test] ' + message.subject;\n```\n\n### message.body\n\nType: `property`\n\nTelo správy.\n\nReturns: `String`\n\nPredvolene HTML; pozri `message.type`.\n\nExample: Nastavenie tela neskôr\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '');\nmessage.manually();\nrender(function(html) {\n\tmessage.body = html;\n\tmessage.send2();\n});\n```\n\n### message.type\n\nType: `property`\n\nTyp obsahu tela: `html` alebo `plain`.\n\nReturns: `String`\n\nPredvolene `html`. Telo sa posiela ako `text/` plus táto hodnota.\n\nExample: Správa s obyčajným textom\n```js\nvar message = Mail.create('Hello', 'Hello,\\nthis is plain text.');\nmessage.type = 'plain';\n```\n\n### message.attachment(filename, [name], [contentid])\n\nType: `method`\n\nPridá súbor z disku ako prílohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Cesta k súboru. |\n| `name` | `String` | no | `the name of the file` | Názov súboru zobrazený v e-maile. |\n| `contentid` | `String` | no |  | Content-ID pre vloženú prílohu, jedinečné v rámci správy. |\n\nReturns: `MailMessage` Správa.\n\nTyp obsahu sa určí podľa prípony `name`. S `contentid` je súbor vloženou prílohou a HTML sa naň odkazuje ako `cid:contentid`. Súbor `.ics` sa pošle ako pozvánka do kalendára.\n\nExample: PDF\n```js\nmessage.attachment(PATH.root('invoices/2024-001.pdf'), 'invoice.pdf');\n```\n\nExample: Vložený obrázok\n```js\nvar message = HTMLMAIL('peter@example.com', 'Report', '<img src=\"cid:chart1\" />');\nmessage.attachment(PATH.public('img/chart.png'), 'chart.png', 'chart1');\n```\n\n### message.attachmentfs(storage, id, [name], [contentid])\n\nType: `method`\n\nPridá súbor z `FILESTORAGE()` ako prílohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Názov úložiska súborov. |\n| `id` | `String` | yes |  | Identifikátor súboru. |\n| `name` | `String` | no | `the stored name` | Názov súboru zobrazený v e-maile. |\n| `contentid` | `String` | no |  | Content-ID pre vloženú prílohu. |\n\nReturns: `MailMessage` Správa.\n\nBez `name` sa názov a typ obsahu vezmú z uloženého súboru. Súbor, ktorý sa nedá prečítať, sa preskočí a chyba sa zaloguje.\n\nExample: Uložený súbor\n```js\nmessage.attachmentfs('documents', doc.fileid);\n```\n\n### message.unsubscribe(url)\n\nType: `method`\n\nPridá hlavičky `List-Unsubscribe`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL alebo e-mailová adresa na odhlásenie odberu. |\n\nReturns: `MailMessage` Správa.\n\nURL, ktorá začína na `http:` alebo `https:`, sa použije ako odkaz; akákoľvek iná hodnota sa použije ako adresa `mailto:`. Pridá sa aj hlavička `List-Unsubscribe-Post: List-Unsubscribe=One-Click`.\n\nExample: Newsletter\n```js\nmessage.unsubscribe('https://example.com/unsubscribe/?id=' + user.id);\n```\n\n### message.callback(fn)\n\nType: `method`\n\nNastaví callback správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err, message)`. |\n\nReturns: `MailMessage` Správa.\n\nCallback sa spustí, keď bola správa zapísaná na server, alebo keď ju server odmietne; chybou je potom riadok odpovede servera. Chyby spojenia sa sem neodovzdávajú: logujú sa a emitujú ako `Mail.on('error')`.\n\nExample: Označenie ako odoslanej\n```js\nmessage.callback(function(err) {\n\tif (!err)\n\t\tNOSQL('orders').modify({ mailed: true }).id(order.id);\n});\n```\n\n### message.manually()\n\nType: `method`\n\nZastaví automatické odoslanie správy z `MAIL()`, `HTMLMAIL()`, `LOGMAIL()` alebo `controller.mail()`.\n\nReturns: `MailMessage` Správa.\n\nZavolaj ju v tom istom zásobníku volaní a potom správu odošli sám pomocou `message.send2()`.\n\nExample: Priloženie vygenerovaného súboru\n```js\nvar message = HTMLMAIL('peter@example.com', 'Export', '<p>The file is attached.</p>');\nmessage.manually();\n\ncreateexport(function(filename) {\n\tmessage.attachment(filename, 'export.csv');\n\tmessage.send2();\n});\n```\n\n### message.send2([callback])\n\nType: `method`\n\nPošle správu s `mail_smtp` a `mail_smtp_options`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Volá sa po zápise správy, pri novom spojení. |\n\nReturns: `MailMessage` Správa.\n\nBez `mail_smtp` je serverom `smtp.` plus doména odosielateľa; bez odosielateľa vyhodí `Missing SMTP settings`. Kým aplikácia beží ako webový server, spojenie zostáva otvorené počas `mail_smtp_keepalive`; keď správa ide do takého otvoreného spojenia, `callback` sa nezavolá, preto uprednostni `message.callback()`.\n\nExample: Odoslanie vytvorenej správy\n```js\nvar message = Mail.create('Hello', '<p>Hello.</p>');\nmessage.from(CONF.mail_from, CONF.name);\nmessage.to('peter@example.com');\nmessage.callback(function(err) {\n\terr && console.log(err);\n});\nmessage.send2();\n```\n\n### message.send(smtp, options, [callback], [cache])\n\nType: `method`\n\nPošle správu na SMTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `smtp` | `String` | yes |  | Názov hostiteľa SMTP servera. |\n| `options` | `Object` | yes |  | Možnosti spojenia, rovnaké ako `mail_smtp_options`; pre žiadne odovzdaj `{}`. |\n| `callback` | `Function` | no |  | `function(err, message)`. |\n| `cache` | `Boolean|Number|String` | no | `false` | Ponechá spojenie otvorené, ako v `Mail.send()`. |\n\nReturns: `MailMessage` Správa.\n\nPoužíva vlastné spojenie na `smtp`; konfigurácia sa nepoužije.\n\nExample: Iný server\n```js\nmessage.send('smtp.example.com', { port: 465, secure: true, user: 'info@example.com', password: 'secret' }, function(err) {\n\tconsole.log(err ? 'Failed' : 'Sent');\n});\n```\n","entries":[{"type":"method","name":"MAIL()","signature":"MAIL(address, subject, view, [model], [language], [callback])","since":"","deprecated":false},{"type":"method","name":"HTMLMAIL()","signature":"HTMLMAIL(address, subject, body, [language], [callback])","since":"","deprecated":false},{"type":"method","name":"LOGMAIL()","signature":"LOGMAIL(address, [subject], body, [callback])","since":"","deprecated":false},{"type":"method","name":"controller.mail()","signature":"controller.mail(address, subject, view, [model], [callback])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onMail","signature":"DEF.onMail = function(address, subject, body, [callback], [replyTo]) {}","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message) {})","since":"","deprecated":false},{"type":"command","name":"CMD('clear_smtpcache')","signature":"CMD('clear_smtpcache')","since":"","deprecated":false},{"type":"config","name":"mail_smtp","signature":"mail_smtp : smtp.example.com","since":"","deprecated":false},{"type":"config","name":"mail_smtp_options","signature":"mail_smtp_options : { port: 465, secure: true, user: '...', password: '...' }","since":"","deprecated":false},{"type":"config","name":"mail_smtp_keepalive","signature":"mail_smtp_keepalive : 10 minutes","since":"","deprecated":false},{"type":"config","name":"mail_from","signature":"mail_from : info@example.com","since":"","deprecated":false},{"type":"config","name":"mail_reply","signature":"mail_reply : support@example.com","since":"","deprecated":false},{"type":"config","name":"mail_cc","signature":"mail_cc : office@example.com","since":"","deprecated":false},{"type":"config","name":"mail_bcc","signature":"mail_bcc : archive@example.com","since":"","deprecated":false},{"type":"class","name":"Mail","signature":"Mail","since":"","deprecated":false},{"type":"method","name":"Mail.create()","signature":"Mail.create(subject, body)","since":"","deprecated":false},{"type":"method","name":"Mail.send()","signature":"Mail.send(smtp, [options], messages, [callback], [cache])","since":"","deprecated":false},{"type":"method","name":"Mail.send2()","signature":"Mail.send2(messages, [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.try()","signature":"Mail.try(smtp, [options], [callback])","since":"","deprecated":false},{"type":"method","name":"Mail.use()","signature":"Mail.use(smtp, [options], [callback])","since":"","deprecated":false},{"type":"property","name":"Mail.debug","signature":"Mail.debug = true","since":"","deprecated":false},{"type":"event","name":"Mail.on('error')","signature":"Mail.on('error', function(err, connection) {})","since":"","deprecated":false},{"type":"event","name":"Mail.on('send')","signature":"Mail.on('send', function(connection) {})","since":"","deprecated":false},{"type":"method","name":"Mail.removeListener()","signature":"Mail.removeListener(name, fn)","since":"","deprecated":false},{"type":"method","name":"message.to()","signature":"message.to(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.cc()","signature":"message.cc(address, [name], [clear])","since":"","deprecated":false},{"type":"method","name":"message.bcc()","signature":"message.bcc(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.reply()","signature":"message.reply(address, [clear])","since":"","deprecated":false},{"type":"method","name":"message.from()","signature":"message.from(address, [name])","since":"","deprecated":false},{"type":"method","name":"message.sender()","signature":"message.sender(address, [name])","since":"","deprecated":false},{"type":"property","name":"message.subject","signature":"message.subject","since":"","deprecated":false},{"type":"property","name":"message.body","signature":"message.body","since":"","deprecated":false},{"type":"property","name":"message.type","signature":"message.type","since":"","deprecated":false},{"type":"method","name":"message.attachment()","signature":"message.attachment(filename, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.attachmentfs()","signature":"message.attachmentfs(storage, id, [name], [contentid])","since":"","deprecated":false},{"type":"method","name":"message.unsubscribe()","signature":"message.unsubscribe(url)","since":"","deprecated":false},{"type":"method","name":"message.callback()","signature":"message.callback(fn)","since":"","deprecated":false},{"type":"method","name":"message.manually()","signature":"message.manually()","since":"","deprecated":false},{"type":"method","name":"message.send2()","signature":"message.send2([callback])","since":"","deprecated":false},{"type":"method","name":"message.send()","signature":"message.send(smtp, options, [callback], [cache])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"JabnPa1il61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Scheduling and events","summary":"SCHEDULE(), the event functions, every built-in event and the timing helpers.","markdown":"---\ntitle: Scheduling and events\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Scheduling and events\n\n> SCHEDULE(), the event functions, every built-in event and the timing helpers.\n\nThe scheduler `SCHEDULE()`, the event functions `ON()`, `ONCE()`, `OFF()`, `EMIT()` and `EMIT2()`, every built-in framework event, and the timing helpers `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` and `CLEANUP()`. The guide [Scheduling and events](../../guides/scheduling-and-events/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nRegisters a job that runs at a time, repeatedly, or by a cron expression.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | A cron expression, a date or time string, a timestamp or a Date. |\n| `repeat` | `String` | no |  | A repeat period such as `'1 day'` or `'each hour'`. Not used with a cron expression. |\n| `fn` | `Function` | yes |  | The job. It gets no arguments. |\n\nReturns: `Object` The job, with `id`, `remove()` and `exec()`.\n\nThe framework checks the jobs once a minute, in its service, so a job runs on the first check at or after its time.\n\n- A **string with a space** is a cron expression with five fields (minute, hour, day of month, month, day of week). The job runs at every minute that matches; it takes no `repeat`.\n- A **string without a space** is parsed as a date or time (for example `'03:00'`) in the application time zone (`default_timezone`). If it has already passed and `repeat` is set, the first run moves forward by one `repeat`.\n- A **number** is a timestamp in milliseconds; a **Date** is used as it is.\n\n`repeat` is a period for `Date.add()`, such as `'5 minutes'` or `'1 day'`; the word `each` is read as `1` (`'each day'`). Without `repeat` a date job runs once and is then removed.\n\nCron fields accept `*`, a number, a list (`1,15,30`) and a range (`9-17`). Days of the week are `0`-`6` (Sunday is `0`) or names, of which only the first two letters count (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Every day at 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron: working days at 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Once at a specific date\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nThe identifier of the job.\n\nReturns: `String`\n\nA short random string that `SCHEDULE()` creates for each job.\n\n### schedule.remove()\n\nType: `method`\n\nStops the job and removes it from the scheduler.\n\nUse it to stop a repeating or cron job. A one-time job removes itself after it runs.\n\nExample: Stop after the first run\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nRuns the job now.\n\nCalls the job function immediately. The planned time of the next run does not change.\n\nExample: Run at start and then every hour\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAdds a listener to an event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name. |\n| `fn` | `Function` | yes |  | The listener. |\n\n`fn` is called with the arguments of `EMIT()`, and `this` is the framework. Listeners run in the order they were added.\n\nFor `init`, `load` and `ready`, if the application has already loaded, `fn` is called immediately (and is not stored).\n\nExample: React to the start\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAdds a listener that is removed after its first call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name. |\n| `fn` | `Function` | yes |  | The listener. |\n\nWorks like `ON()`; the listener is removed after the first `EMIT()` of the event.\n\nExample: First request only\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nRemoves event listeners.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The event name. |\n| `fn` | `Function` | no |  | The listener to remove. |\n\n- `OFF(name, fn)` removes that one listener. It must be the same function you passed to `ON()`.\n- `OFF(name)` removes all listeners of the event, including the framework's own.\n- `OFF()` removes all listeners of all events.\n\nExample: Remove one listener\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nCalls all listeners of an event in the current process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name. |\n| `a...g` | `Object` | no |  | Up to seven arguments for the listeners. |\n\nPasses up to seven arguments. The listeners run synchronously, in the order they were added. Listeners added with `ONCE()` are removed afterwards. An event without listeners does nothing.\n\nExample: Your own event\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nSends an event to the other processes of the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name. |\n| `a...e` | `Object` | no |  | Up to five serialisable arguments. |\n\nThe event goes to the threads (from the main process, which also calls its own listeners), to the cluster, or from a thread or worker back to its parent. Up to five arguments, sent as IPC messages, so use plain serialisable values. In a single process without threads or a cluster nothing happens; use `EMIT()` there.\n\nExample: Clear a cache in every process\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nWaits until a condition is true.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Returns `true` when the wait is over. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximum wait in milliseconds. |\n| `interval` | `Number` | no | `500` | Check interval in milliseconds. |\n\nIf `validator()` already returns `true`, `callback(null, true)` runs immediately. Otherwise `validator()` is checked every `interval` ms. When it returns `true` the callback gets `(null, true)`; after `timeout` ms it gets `(Error(\"Timeout\"), false)`.\n\nExample: Wait for a connection\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nA named timeout: each call with the same name restarts the timer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the timer. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Delay in milliseconds. |\n| `limit` | `Number` | no |  | Maximum number of postponements before `fn` runs at once. |\n| `param` | `Object` | no |  | An argument for `fn`. |\n\nReturns: `Timeout` The Node.js timer, or nothing when `fn` ran immediately.\n\nCancels the previous timer of the same name and starts a new one, so `fn` runs once, `timeout` ms after the last call (a debounce). With `limit`, after `limit` postponements `fn` runs immediately (without `param`) and the counter resets. `param` is passed to `fn`.\n\nExample: Save once after a burst of changes\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nCancels a timer created by setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name used in `setTimeout2()`. |\n\nReturns: `Boolean` `true` if a timer was cancelled.\n\nReturns `true` if a pending timer with that name was cancelled.\n\nExample: Cancel\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPauses the server: every request gets 503 while a name is paused.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A name for the pause. |\n| `enable` | `Boolean` | no |  | `true` pauses, `false` resumes. When omitted, the state toggles. |\n\nReturns: `Boolean` `true` if `name` is now paused.\n\nEach `name` is one reason to pause. While at least one name is paused, HTTP requests are answered with `503` and WebSocket upgrades are refused. With `enable` the state is set; without it the state of `name` is toggled. `F.wait()` is the same function.\n\nExample: Pause during a migration\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinutes between clean-ups of the temporary file and view cache.\n\nReturns: `Number`\n\nCounted in service ticks (one per minute). Each clean-up emits `clear` with the type `'temporary'`.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinutes between clean-ups of the loaded resources.\n\nReturns: `Number`\n\nCounted in service ticks. Each clean-up emits `clear` with the type `'resources'`.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinutes between clean-ups of the DNS cache.\n\nReturns: `Number`\n\nCounted in service ticks. Each clean-up emits `clear` with the type `'dns'`.\n\n### ON('init', function())\n\nType: `event`\n\nConfiguration is loaded; the application files are not loaded yet.\n\nEmitted once at start, before definitions, models, controllers and the other files load. If you call `ON('init')` after the application has loaded, the function runs immediately.\n\nExample: Listen\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nAll application files are loaded.\n\nEmitted once, right before `ready`. If the application has already loaded, the function runs immediately.\n\nExample: Listen\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nThe application is ready.\n\nEmitted once after `load`, when all files are loaded. The usual place for start-up code. If the application has already loaded, the function runs immediately.\n\nExample: Listen\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nEmitted every minute by the framework service.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | The number of service runs. |\n\n`counter` is the number of runs since the application started (1, 2, 3...). Use the remainder to run code every few minutes. In a worker, adding this listener starts the timer.\n\nExample: Listen\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nThe application is stopping.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | The signal; `15` (SIGTERM) when none was given. |\n\nEmitted once when the framework stops, after it has sent the signal to its workers and threads. Keep the work synchronous; the process ends soon after.\n\nExample: Listen\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nA request arrived, before routing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `res` | `Response` | yes |  | The response. |\n\nEmitted for each HTTP request after the proxies are checked and before redirects and routing.\n\nExample: Listen\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nThe request is prepared for routing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `res` | `Response` | yes |  | The response. |\n\nEmitted after the request has been parsed (headers, XHR flag), before the route is looked up.\n\nExample: Listen\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nThe response to a request has finished.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `res` | `Response` | yes |  | The response. |\n\nEmitted when the framework has finished sending a response.\n\nExample: Listen\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nA route action is about to run.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | The controller of the request. |\n| `name` | `String` | yes |  | The controller name. |\n| `options` | `Object` | yes |  | The custom options of the route. |\n\nEmitted before the action of a route runs. Call `controller.cancel()` to stop the action here. `name` is the name of the controller file that declared the route.\n\nExample: Listen\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nA route action of one controller is about to run.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | The controller of the request. |\n| `name` | `String` | yes |  | The controller name. |\n| `options` | `Object` | yes |  | The custom options of the route. |\n\nLike `controller`, but only for routes declared in the controller file `name`: `ON('@admin')` runs for the routes in `controllers/admin.js`.\n\nExample: Listen\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nAn error response is sent, for example error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `res` | `Response` | yes |  | The response. |\n| `exception` | `Error` | yes |  | The problem, if any. |\n\nThe name is `error` plus the HTTP status: `error400`, `error401`, `error404`, `error500`... Emitted when the framework answers with that status.\n\nExample: Listen\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nThe framework logged an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nEmitted by the default `DEF.onError` handler for each error it records. The last five errors are also kept in `F.errors`.\n\nExample: Listen\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nA route was registered.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` or `file`. |\n| `route` | `Object` | yes |  | The internal route object. |\n\n`type` is `'web'` for `ROUTE()` routes, `'websocket'` for WebSocket routes and `'file'` for file routes.\n\nExample: Listen\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nA file of the application was installed.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | For example `'controller'` or `'model'`. |\n| `name` | `String` | yes |  | The name of the file. |\n| `module` | `Object` | yes |  | The exports of the file. |\n\nEmitted after the framework installs a controller, model, definition, plugin, module, source and other types. `module` is what the file exports.\n\nExample: Listen\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nThe configuration was loaded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | The configuration. |\n\nEmitted each time the configuration files are read, at start and on reload.\n\nExample: Listen\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() has finished.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | The errors, or `null`. |\n\nEmitted when the update scripts of `UPDATE()` have run, with the errors if any.\n\nExample: Listen\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nAn internal cache was cleared.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` or `dns`. |\n| `value` | `Object` | no |  | The temporary storage, for `temporary` only. |\n\n`type` is `'temporary'` (with the temporary storage as `value`), `'resources'` or `'dns'`. The service clears them by the `default_interval_clear_*` settings.\n\nExample: Listen\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nA value was stored with CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n| `value` | `Object` | yes |  | The value. |\n| `expire` | `Date` | yes |  | The expiration. |\n| `sync` | `Boolean` | yes |  | An internal flag for synchronised caches. |\n\nEmitted by `CACHE.set()`.\n\nExample: Listen\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nA CACHE value expired.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n| `value` | `Object` | yes |  | The expired value. |\n\nEmitted when the cache removes an expired item (checked every minute) or finds one when reading it.\n\nExample: Listen\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nA view is about to print its meta tags.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | The controller that renders the view. |\n\nEmitted when a layout renders `@{meta}`, before the tags are built. Change `controller.repository` here to adjust them.\n\nExample: Listen\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nA WebSocket upgrade request arrived.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | The request. |\n| `socket` | `Socket` | yes |  | The network socket. |\n| `head` | `Buffer` | yes |  | The first packet of the upgraded stream. |\n\nEmitted after a matching WebSocket route was found, before the connection is accepted.\n\nExample: Listen\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nA WebSocket client connected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | The WebSocket controller. |\n| `client` | `WebSocketClient` | yes |  | The client. |\n\nEmitted when a client is added to its WebSocket controller, before its `open` event.\n\nExample: Listen\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nA WebSocket client disconnected.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | The WebSocket controller. |\n| `client` | `WebSocketClient` | yes |  | The client. |\n\nEmitted when a client is removed from its WebSocket controller.\n\nExample: Listen\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() is about to download components.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` holds `name` and `components` from the `COMPONENTATOR()` call.\n\nExample: Listen\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nAn email message is being sent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | The message. |\n\nEmitted for each message as the SMTP sender writes it.\n\nExample: Listen\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nThe process received an IPC message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message. |\n| `handle` | `Object` | yes |  | The handle sent with the message, if any. |\n\nEmitted for every message the process gets from its parent (`process.on('message')`), after the framework has handled its own.\n\nExample: Listen\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nThe watcher (re)started the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | The application process, or `null`. |\n\nEmitted in the main process of `debug` or `release` mode with the file watcher, each time it starts the application process.\n\nExample: Listen\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nThe application started in debug mode.\n\nEmitted in the application process when it starts the first time in debug mode.\n\nExample: Listen\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nThe application restarted in debug mode.\n\nEmitted instead of `debug_start` when the debug watcher restarts the application after a change.\n\nExample: Listen\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nDestroys a stream after it has finished.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | A readable or writable stream. |\n| `callback` | `Function` | no |  | Called after the stream is destroyed. |\n\nReturns: `Promise` Only when `callback` is not set.\n\nWaits until the stream finishes or fails, destroys it and calls `callback`. Without a callback it returns a Promise.\n\nExample: Close a file after piping\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: With await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPa1il61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Zeitplanung und Events","summary":"SCHEDULE(), die Event-Funktionen, jedes eingebaute Event und die Zeit-Helfer.","markdown":"---\ntitle: Zeitplanung und Events\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Zeitplanung und Events\n\n> SCHEDULE(), die Event-Funktionen, jedes eingebaute Event und die Zeit-Helfer.\n\nDer Scheduler `SCHEDULE()`, die Event-Funktionen `ON()`, `ONCE()`, `OFF()`, `EMIT()` und `EMIT2()`, jedes eingebaute Event des Frameworks und die Zeit-Helfer `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` und `CLEANUP()`. Der Leitfaden [Zeitplanung und Events](../../guides/scheduling-and-events/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nRegistriert einen Job, der zu einer Uhrzeit, wiederholt oder nach einem Cron-Ausdruck läuft.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | Ein Cron-Ausdruck, ein Datums- oder Uhrzeit-String, ein Zeitstempel oder ein Date. |\n| `repeat` | `String` | no |  | Ein Wiederholungszeitraum wie `'1 day'` oder `'each hour'`. Wird mit einem Cron-Ausdruck nicht verwendet. |\n| `fn` | `Function` | yes |  | Der Job. Er erhält keine Argumente. |\n\nReturns: `Object` Der Job, mit `id`, `remove()` und `exec()`.\n\nDas Framework prüft die Jobs einmal pro Minute in seinem Service, ein Job läuft also bei der ersten Prüfung zu oder nach seiner Zeit.\n\n- Ein **String mit Leerzeichen** ist ein Cron-Ausdruck mit fünf Feldern (Minute, Stunde, Tag des Monats, Monat, Wochentag). Der Job läuft in jeder passenden Minute; er nimmt kein `repeat`.\n- Ein **String ohne Leerzeichen** wird als Datum oder Uhrzeit (zum Beispiel `'03:00'`) in der Zeitzone der Anwendung (`default_timezone`) geparst. Ist er schon vorbei und `repeat` gesetzt, verschiebt sich der erste Lauf um ein `repeat` nach vorn.\n- Eine **Zahl** ist ein Zeitstempel in Millisekunden; ein **Date** wird unverändert verwendet.\n\n`repeat` ist ein Zeitraum für `Date.add()`, etwa `'5 minutes'` oder `'1 day'`; das Wort `each` wird als `1` gelesen (`'each day'`). Ohne `repeat` läuft ein Datums-Job einmal und wird dann entfernt.\n\nCron-Felder akzeptieren `*`, eine Zahl, eine Liste (`1,15,30`) und einen Bereich (`9-17`). Wochentage sind `0`-`6` (Sonntag ist `0`) oder Namen, von denen nur die ersten zwei Buchstaben zählen (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Jeden Tag um 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron: Werktage um 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Einmal zu einem bestimmten Datum\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nDie Kennung des Jobs.\n\nReturns: `String`\n\nEin kurzer zufälliger String, den `SCHEDULE()` für jeden Job erzeugt.\n\n### schedule.remove()\n\nType: `method`\n\nStoppt den Job und entfernt ihn aus dem Scheduler.\n\nNutze die Methode, um einen wiederholten oder Cron-Job zu stoppen. Ein einmaliger Job entfernt sich nach seinem Lauf selbst.\n\nExample: Nach dem ersten Lauf stoppen\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nFührt den Job jetzt aus.\n\nRuft die Job-Funktion sofort auf. Die geplante Zeit des nächsten Laufs ändert sich nicht.\n\nExample: Beim Start und dann jede Stunde ausführen\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nFügt einem Event einen Listener hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | yes |  | Der Listener. |\n\n`fn` wird mit den Argumenten von `EMIT()` aufgerufen, und `this` ist das Framework. Listener laufen in der Reihenfolge, in der sie hinzugefügt wurden.\n\nBei `init`, `load` und `ready` wird `fn` sofort aufgerufen (und nicht gespeichert), wenn die Anwendung bereits geladen ist.\n\nExample: Auf den Start reagieren\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nFügt einen Listener hinzu, der nach seinem ersten Aufruf entfernt wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | yes |  | Der Listener. |\n\nFunktioniert wie `ON()`; der Listener wird nach dem ersten `EMIT()` des Events entfernt.\n\nExample: Nur die erste Anfrage\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nEntfernt Event-Listener.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name des Events. |\n| `fn` | `Function` | no |  | Der zu entfernende Listener. |\n\n- `OFF(name, fn)` entfernt genau diesen einen Listener. Es muss dieselbe Funktion sein, die du an `ON()` übergeben hast.\n- `OFF(name)` entfernt alle Listener des Events, auch die des Frameworks selbst.\n- `OFF()` entfernt alle Listener aller Events.\n\nExample: Einen Listener entfernen\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nRuft alle Listener eines Events im aktuellen Prozess auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `a...g` | `Object` | no |  | Bis zu sieben Argumente für die Listener. |\n\nÜbergibt bis zu sieben Argumente. Die Listener laufen synchron, in der Reihenfolge, in der sie hinzugefügt wurden. Mit `ONCE()` hinzugefügte Listener werden danach entfernt. Ein Event ohne Listener tut nichts.\n\nExample: Ein eigenes Event\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nSendet ein Event an die anderen Prozesse der Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `a...e` | `Object` | no |  | Bis zu fünf serialisierbare Argumente. |\n\nDas Event geht an die Threads (vom Hauptprozess aus, der auch seine eigenen Listener aufruft), an den Cluster oder von einem Thread oder Worker zurück an seinen Elternprozess. Bis zu fünf Argumente, als IPC-Nachrichten gesendet, verwende also einfache serialisierbare Werte. In einem einzelnen Prozess ohne Threads oder Cluster passiert nichts; verwende dort `EMIT()`.\n\nExample: Einen Cache in jedem Prozess leeren\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nWartet, bis eine Bedingung erfüllt ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Gibt `true` zurück, wenn das Warten vorbei ist. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximale Wartezeit in Millisekunden. |\n| `interval` | `Number` | no | `500` | Prüfintervall in Millisekunden. |\n\nGibt `validator()` bereits `true` zurück, läuft `callback(null, true)` sofort. Sonst wird `validator()` alle `interval` ms geprüft. Gibt es `true` zurück, erhält der Callback `(null, true)`; nach `timeout` ms erhält er `(Error(\"Timeout\"), false)`.\n\nExample: Auf eine Verbindung warten\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nEin benanntes Timeout: Jeder Aufruf mit demselben Namen startet den Timer neu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Timers. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Verzögerung in Millisekunden. |\n| `limit` | `Number` | no |  | Maximale Anzahl an Verschiebungen, bevor `fn` sofort läuft. |\n| `param` | `Object` | no |  | Ein Argument für `fn`. |\n\nReturns: `Timeout` Der Node.js-Timer oder nichts, wenn `fn` sofort lief.\n\nBricht den vorherigen Timer mit demselben Namen ab und startet einen neuen, sodass `fn` einmal läuft, `timeout` ms nach dem letzten Aufruf (ein Debounce). Mit `limit` läuft `fn` nach `limit` Verschiebungen sofort (ohne `param`), und der Zähler wird zurückgesetzt. `param` wird an `fn` übergeben.\n\nExample: Nach einer Reihe von Änderungen einmal speichern\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nBricht einen mit setTimeout2() erstellten Timer ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der in `setTimeout2()` verwendete Name. |\n\nReturns: `Boolean` `true`, wenn ein Timer abgebrochen wurde.\n\nGibt `true` zurück, wenn ein wartender Timer mit diesem Namen abgebrochen wurde.\n\nExample: Abbrechen\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPausiert den Server: Jede Anfrage erhält 503, solange ein Name pausiert ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein Name für die Pause. |\n| `enable` | `Boolean` | no |  | `true` pausiert, `false` setzt fort. Ohne Angabe wird der Zustand umgeschaltet. |\n\nReturns: `Boolean` `true`, wenn `name` jetzt pausiert ist.\n\nJeder `name` ist ein Grund für die Pause. Solange mindestens ein Name pausiert ist, werden HTTP-Anfragen mit `503` beantwortet und WebSocket-Upgrades abgelehnt. Mit `enable` wird der Zustand gesetzt; ohne wird der Zustand von `name` umgeschaltet. `F.wait()` ist dieselbe Funktion.\n\nExample: Während einer Migration pausieren\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinuten zwischen den Bereinigungen des temporären Datei- und View-Caches.\n\nReturns: `Number`\n\nGezählt in Service-Ticks (einer pro Minute). Jede Bereinigung löst `clear` mit dem Typ `'temporary'` aus.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinuten zwischen den Bereinigungen der geladenen Ressourcen.\n\nReturns: `Number`\n\nGezählt in Service-Ticks. Jede Bereinigung löst `clear` mit dem Typ `'resources'` aus.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinuten zwischen den Bereinigungen des DNS-Caches.\n\nReturns: `Number`\n\nGezählt in Service-Ticks. Jede Bereinigung löst `clear` mit dem Typ `'dns'` aus.\n\n### ON('init', function())\n\nType: `event`\n\nDie Konfiguration ist geladen; die Dateien der Anwendung sind noch nicht geladen.\n\nWird einmal beim Start ausgelöst, bevor Definitionen, Models, Controller und die anderen Dateien geladen werden. Rufst du `ON('init')` auf, nachdem die Anwendung geladen ist, läuft die Funktion sofort.\n\nExample: Zuhören\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nAlle Dateien der Anwendung sind geladen.\n\nWird einmal ausgelöst, direkt vor `ready`. Ist die Anwendung bereits geladen, läuft die Funktion sofort.\n\nExample: Zuhören\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nDie Anwendung ist bereit.\n\nWird einmal nach `load` ausgelöst, wenn alle Dateien geladen sind. Der übliche Ort für Startcode. Ist die Anwendung bereits geladen, läuft die Funktion sofort.\n\nExample: Zuhören\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nWird jede Minute vom Service des Frameworks ausgelöst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Die Anzahl der Service-Läufe. |\n\n`counter` ist die Anzahl der Läufe seit dem Start der Anwendung (1, 2, 3 ...). Nutze den Rest einer Division, um Code alle paar Minuten auszuführen. In einem Worker startet das Hinzufügen dieses Listeners den Timer.\n\nExample: Zuhören\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nDie Anwendung wird beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | Das Signal; `15` (SIGTERM), wenn keines angegeben wurde. |\n\nWird einmal ausgelöst, wenn das Framework stoppt, nachdem es das Signal an seine Worker und Threads gesendet hat. Halte die Arbeit synchron; der Prozess endet kurz danach.\n\nExample: Zuhören\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nEine Anfrage ist eingetroffen, vor dem Routing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `res` | `Response` | yes |  | Die Antwort. |\n\nWird für jede HTTP-Anfrage ausgelöst, nachdem die Proxys geprüft wurden und vor Weiterleitungen und Routing.\n\nExample: Zuhören\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nDie Anfrage wird für das Routing vorbereitet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `res` | `Response` | yes |  | Die Antwort. |\n\nWird ausgelöst, nachdem die Anfrage geparst wurde (Header, XHR-Flag), bevor die Route gesucht wird.\n\nExample: Zuhören\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nDie Antwort auf eine Anfrage ist abgeschlossen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `res` | `Response` | yes |  | Die Antwort. |\n\nWird ausgelöst, wenn das Framework das Senden einer Antwort abgeschlossen hat.\n\nExample: Zuhören\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nEine Routen-Aktion wird gleich ausgeführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Der Controller der Anfrage. |\n| `name` | `String` | yes |  | Der Name des Controllers. |\n| `options` | `Object` | yes |  | Die eigenen Optionen der Route. |\n\nWird ausgelöst, bevor die Aktion einer Route läuft. Rufe hier `controller.cancel()` auf, um die Aktion zu stoppen. `name` ist der Name der Controller-Datei, die die Route deklariert hat.\n\nExample: Zuhören\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nEine Routen-Aktion eines bestimmten Controllers wird gleich ausgeführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Der Controller der Anfrage. |\n| `name` | `String` | yes |  | Der Name des Controllers. |\n| `options` | `Object` | yes |  | Die eigenen Optionen der Route. |\n\nWie `controller`, aber nur für Routen, die in der Controller-Datei `name` deklariert sind: `ON('@admin')` läuft für die Routen in `controllers/admin.js`.\n\nExample: Zuhören\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nEine Fehlerantwort wird gesendet, zum Beispiel error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `res` | `Response` | yes |  | Die Antwort. |\n| `exception` | `Error` | yes |  | Das Problem, falls vorhanden. |\n\nDer Name ist `error` plus der HTTP-Status: `error400`, `error401`, `error404`, `error500` ... Wird ausgelöst, wenn das Framework mit diesem Status antwortet.\n\nExample: Zuhören\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nDas Framework hat einen Fehler protokolliert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nWird vom Standard-Handler `DEF.onError` für jeden Fehler ausgelöst, den er aufzeichnet. Die letzten fünf Fehler werden außerdem in `F.errors` aufbewahrt.\n\nExample: Zuhören\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nEine Route wurde registriert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` oder `file`. |\n| `route` | `Object` | yes |  | Das interne Routenobjekt. |\n\n`type` ist `'web'` für `ROUTE()`-Routen, `'websocket'` für WebSocket-Routen und `'file'` für Datei-Routen.\n\nExample: Zuhören\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nEine Datei der Anwendung wurde installiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Zum Beispiel `'controller'` oder `'model'`. |\n| `name` | `String` | yes |  | Der Name der Datei. |\n| `module` | `Object` | yes |  | Die Exporte der Datei. |\n\nWird ausgelöst, nachdem das Framework einen Controller, ein Model, eine Definition, ein Plugin, ein Modul, eine Quelle oder andere Typen installiert hat. `module` ist das, was die Datei exportiert.\n\nExample: Zuhören\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nDie Konfiguration wurde geladen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | Die Konfiguration. |\n\nWird jedes Mal ausgelöst, wenn die Konfigurationsdateien gelesen werden, beim Start und beim Neuladen.\n\nExample: Zuhören\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() ist abgeschlossen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | Die Fehler oder `null`. |\n\nWird ausgelöst, wenn die Update-Skripte von `UPDATE()` gelaufen sind, gegebenenfalls mit den Fehlern.\n\nExample: Zuhören\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nEin interner Cache wurde geleert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` oder `dns`. |\n| `value` | `Object` | no |  | Der temporäre Speicher, nur bei `temporary`. |\n\n`type` ist `'temporary'` (mit dem temporären Speicher als `value`), `'resources'` oder `'dns'`. Der Service leert sie gemäß den Einstellungen `default_interval_clear_*`.\n\nExample: Zuhören\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nEin Wert wurde mit CACHE gespeichert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `Object` | yes |  | Der Wert. |\n| `expire` | `Date` | yes |  | Das Ablaufdatum. |\n| `sync` | `Boolean` | yes |  | Ein internes Flag für synchronisierte Caches. |\n\nWird von `CACHE.set()` ausgelöst.\n\nExample: Zuhören\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nEin CACHE-Wert ist abgelaufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `Object` | yes |  | Der abgelaufene Wert. |\n\nWird ausgelöst, wenn der Cache einen abgelaufenen Eintrag entfernt (jede Minute geprüft) oder beim Lesen einen findet.\n\nExample: Zuhören\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nEine View gibt gleich ihre Meta-Tags aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Der Controller, der die View rendert. |\n\nWird ausgelöst, wenn ein Layout `@{meta}` rendert, bevor die Tags erzeugt werden. Ändere hier `controller.repository`, um sie anzupassen.\n\nExample: Zuhören\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nEine WebSocket-Upgrade-Anfrage ist eingetroffen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Die Anfrage. |\n| `socket` | `Socket` | yes |  | Der Netzwerk-Socket. |\n| `head` | `Buffer` | yes |  | Das erste Paket des umgestellten Streams. |\n\nWird ausgelöst, nachdem eine passende WebSocket-Route gefunden wurde, bevor die Verbindung angenommen wird.\n\nExample: Zuhören\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nEin WebSocket-Client hat sich verbunden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Der WebSocket-Controller. |\n| `client` | `WebSocketClient` | yes |  | Der Client. |\n\nWird ausgelöst, wenn ein Client zu seinem WebSocket-Controller hinzugefügt wird, vor seinem Event `open`.\n\nExample: Zuhören\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nEin WebSocket-Client hat die Verbindung getrennt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Der WebSocket-Controller. |\n| `client` | `WebSocketClient` | yes |  | Der Client. |\n\nWird ausgelöst, wenn ein Client aus seinem WebSocket-Controller entfernt wird.\n\nExample: Zuhören\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() lädt gleich Komponenten herunter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` enthält `name` und `components` aus dem Aufruf von `COMPONENTATOR()`.\n\nExample: Zuhören\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nEine E-Mail-Nachricht wird gesendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Die Nachricht. |\n\nWird für jede Nachricht ausgelöst, während der SMTP-Sender sie schreibt.\n\nExample: Zuhören\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nDer Prozess hat eine IPC-Nachricht empfangen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht. |\n| `handle` | `Object` | yes |  | Das mit der Nachricht gesendete Handle, falls vorhanden. |\n\nWird für jede Nachricht ausgelöst, die der Prozess von seinem Elternprozess erhält (`process.on('message')`), nachdem das Framework seine eigenen verarbeitet hat.\n\nExample: Zuhören\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nDer Watcher hat die Anwendung (neu) gestartet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | Der Anwendungsprozess oder `null`. |\n\nWird im Hauptprozess des Modus `debug` oder `release` mit dem Datei-Watcher ausgelöst, jedes Mal, wenn er den Anwendungsprozess startet.\n\nExample: Zuhören\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nDie Anwendung wurde im Debug-Modus gestartet.\n\nWird im Anwendungsprozess ausgelöst, wenn er zum ersten Mal im Debug-Modus startet.\n\nExample: Zuhören\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nDie Anwendung wurde im Debug-Modus neu gestartet.\n\nWird statt `debug_start` ausgelöst, wenn der Debug-Watcher die Anwendung nach einer Änderung neu startet.\n\nExample: Zuhören\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nZerstört einen Stream, nachdem er fertig ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Ein lesbarer oder schreibbarer Stream. |\n| `callback` | `Function` | no |  | Wird aufgerufen, nachdem der Stream zerstört wurde. |\n\nReturns: `Promise` Nur wenn `callback` nicht gesetzt ist.\n\nWartet, bis der Stream fertig ist oder fehlschlägt, zerstört ihn und ruft `callback` auf. Ohne Callback gibt es eine Promise zurück.\n\nExample: Eine Datei nach dem Pipen schließen\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: Mit await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPa1il61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Programación y eventos","summary":"SCHEDULE(), las funciones de eventos, todos los eventos integrados y los helpers de temporización.","markdown":"---\ntitle: \"Programación y eventos\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Programación y eventos\n\n> SCHEDULE(), las funciones de eventos, todos los eventos integrados y los helpers de temporización.\n\nEl programador `SCHEDULE()`, las funciones de eventos `ON()`, `ONCE()`, `OFF()`, `EMIT()` y `EMIT2()`, todos los eventos integrados del framework y los helpers de temporización `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` y `CLEANUP()`. La guía [Programación y eventos](../../guides/scheduling-and-events/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nRegistra un trabajo que se ejecuta a una hora, de forma repetida o según una expresión cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | Una expresión cron, una cadena de fecha u hora, una marca de tiempo o un Date. |\n| `repeat` | `String` | no |  | Un periodo de repetición como `'1 day'` o `'each hour'`. No se usa con una expresión cron. |\n| `fn` | `Function` | yes |  | El trabajo. No recibe argumentos. |\n\nReturns: `Object` El trabajo, con `id`, `remove()` y `exec()`.\n\nEl framework revisa los trabajos una vez por minuto, en su servicio, así que un trabajo se ejecuta en la primera revisión en su hora o después.\n\n- Una **cadena con un espacio** es una expresión cron con cinco campos (minuto, hora, día del mes, mes, día de la semana). El trabajo se ejecuta en cada minuto que coincide; no admite `repeat`.\n- Una **cadena sin espacio** se parsea como fecha u hora (por ejemplo `'03:00'`) en la zona horaria de la aplicación (`default_timezone`). Si ya ha pasado y `repeat` está definido, la primera ejecución avanza un `repeat`.\n- Un **número** es una marca de tiempo en milisegundos; un **Date** se usa tal cual.\n\n`repeat` es un periodo para `Date.add()`, como `'5 minutes'` o `'1 day'`; la palabra `each` se interpreta como `1` (`'each day'`). Sin `repeat`, un trabajo con fecha se ejecuta una vez y luego se elimina.\n\nLos campos cron aceptan `*`, un número, una lista (`1,15,30`) y un rango (`9-17`). Los días de la semana son `0`-`6` (el domingo es `0`) o nombres en inglés, de los que solo cuentan las dos primeras letras (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Cada día a las 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron: días laborables a las 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Una vez en una fecha concreta\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nEl identificador del trabajo.\n\nReturns: `String`\n\nUna cadena aleatoria corta que `SCHEDULE()` crea para cada trabajo.\n\n### schedule.remove()\n\nType: `method`\n\nDetiene el trabajo y lo elimina del programador.\n\nÚsalo para detener un trabajo repetido o cron. Un trabajo de una sola vez se elimina solo después de ejecutarse.\n\nExample: Detener tras la primera ejecución\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nEjecuta el trabajo ahora.\n\nLlama a la función del trabajo de inmediato. La hora planificada de la siguiente ejecución no cambia.\n\nExample: Ejecutar al inicio y luego cada hora\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAñade un listener a un evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | yes |  | El listener. |\n\n`fn` se llama con los argumentos de `EMIT()`, y `this` es el framework. Los listeners se ejecutan en el orden en que se añadieron.\n\nPara `init`, `load` y `ready`, si la aplicación ya se ha cargado, `fn` se llama de inmediato (y no se guarda).\n\nExample: Reaccionar al inicio\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAñade un listener que se elimina tras su primera llamada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | yes |  | El listener. |\n\nFunciona como `ON()`; el listener se elimina tras el primer `EMIT()` del evento.\n\nExample: Solo la primera petición\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nElimina listeners de eventos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre del evento. |\n| `fn` | `Function` | no |  | El listener que se elimina. |\n\n- `OFF(name, fn)` elimina ese listener concreto. Debe ser la misma función que pasaste a `ON()`.\n- `OFF(name)` elimina todos los listeners del evento, incluidos los del propio framework.\n- `OFF()` elimina todos los listeners de todos los eventos.\n\nExample: Eliminar un listener\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nLlama a todos los listeners de un evento en el proceso actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `a...g` | `Object` | no |  | Hasta siete argumentos para los listeners. |\n\nPasa hasta siete argumentos. Los listeners se ejecutan de forma síncrona, en el orden en que se añadieron. Los listeners añadidos con `ONCE()` se eliminan después. Un evento sin listeners no hace nada.\n\nExample: Tu propio evento\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nEnvía un evento a los otros procesos de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `a...e` | `Object` | no |  | Hasta cinco argumentos serializables. |\n\nEl evento va a los hilos (desde el proceso principal, que también llama a sus propios listeners), al clúster, o desde un hilo o worker de vuelta a su padre. Hasta cinco argumentos, enviados como mensajes IPC, así que usa valores simples serializables. En un único proceso sin hilos ni clúster no pasa nada; usa `EMIT()` en ese caso.\n\nExample: Limpiar una caché en cada proceso\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nEspera hasta que una condición sea verdadera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Devuelve `true` cuando termina la espera. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Espera máxima en milisegundos. |\n| `interval` | `Number` | no | `500` | Intervalo de comprobación en milisegundos. |\n\nSi `validator()` ya devuelve `true`, `callback(null, true)` se ejecuta de inmediato. Si no, `validator()` se comprueba cada `interval` ms. Cuando devuelve `true`, el callback recibe `(null, true)`; tras `timeout` ms recibe `(Error(\"Timeout\"), false)`.\n\nExample: Esperar a una conexión\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nUn timeout con nombre: cada llamada con el mismo nombre reinicia el temporizador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del temporizador. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Retraso en milisegundos. |\n| `limit` | `Number` | no |  | Número máximo de aplazamientos antes de que `fn` se ejecute en el momento. |\n| `param` | `Object` | no |  | Un argumento para `fn`. |\n\nReturns: `Timeout` El temporizador de Node.js, o nada cuando `fn` se ejecutó de inmediato.\n\nCancela el temporizador anterior con el mismo nombre e inicia uno nuevo, así que `fn` se ejecuta una vez, `timeout` ms después de la última llamada (un debounce). Con `limit`, tras `limit` aplazamientos `fn` se ejecuta de inmediato (sin `param`) y el contador se reinicia. `param` se pasa a `fn`.\n\nExample: Guardar una vez tras una ráfaga de cambios\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nCancela un temporizador creado con setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre usado en `setTimeout2()`. |\n\nReturns: `Boolean` `true` si se canceló un temporizador.\n\nDevuelve `true` si se canceló un temporizador pendiente con ese nombre.\n\nExample: Cancelar\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPausa el servidor: cada petición recibe 503 mientras haya un nombre en pausa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre para la pausa. |\n| `enable` | `Boolean` | no |  | `true` pausa, `false` reanuda. Si se omite, el estado se alterna. |\n\nReturns: `Boolean` `true` si `name` está ahora en pausa.\n\nCada `name` es un motivo de pausa. Mientras haya al menos un nombre en pausa, las peticiones HTTP se responden con `503` y se rechazan los upgrades a WebSocket. Con `enable` se define el estado; sin él, el estado de `name` se alterna. `F.wait()` es la misma función.\n\nExample: Pausar durante una migración\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinutos entre limpiezas de la caché de archivos temporales y de vistas.\n\nReturns: `Number`\n\nSe cuenta en ticks del servicio (uno por minuto). Cada limpieza emite `clear` con el tipo `'temporary'`.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinutos entre limpiezas de los recursos cargados.\n\nReturns: `Number`\n\nSe cuenta en ticks del servicio. Cada limpieza emite `clear` con el tipo `'resources'`.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinutos entre limpiezas de la caché DNS.\n\nReturns: `Number`\n\nSe cuenta en ticks del servicio. Cada limpieza emite `clear` con el tipo `'dns'`.\n\n### ON('init', function())\n\nType: `event`\n\nLa configuración está cargada; los archivos de la aplicación aún no.\n\nSe emite una vez al inicio, antes de que se carguen las definiciones, los modelos, los controladores y los demás archivos. Si llamas a `ON('init')` después de que la aplicación se haya cargado, la función se ejecuta de inmediato.\n\nExample: Escuchar\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nTodos los archivos de la aplicación están cargados.\n\nSe emite una vez, justo antes de `ready`. Si la aplicación ya se ha cargado, la función se ejecuta de inmediato.\n\nExample: Escuchar\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nLa aplicación está lista.\n\nSe emite una vez después de `load`, cuando todos los archivos están cargados. Es el lugar habitual para el código de arranque. Si la aplicación ya se ha cargado, la función se ejecuta de inmediato.\n\nExample: Escuchar\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nLo emite el servicio del framework cada minuto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | El número de ejecuciones del servicio. |\n\n`counter` es el número de ejecuciones desde que arrancó la aplicación (1, 2, 3...). Usa el resto de la división para ejecutar código cada pocos minutos. En un worker, añadir este listener inicia el temporizador.\n\nExample: Escuchar\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nLa aplicación se está deteniendo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | La señal; `15` (SIGTERM) cuando no se indicó ninguna. |\n\nSe emite una vez cuando el framework se detiene, después de enviar la señal a sus workers e hilos. Mantén el trabajo síncrono; el proceso termina poco después.\n\nExample: Escuchar\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nHa llegado una petición, antes del enrutamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `res` | `Response` | yes |  | La respuesta. |\n\nSe emite para cada petición HTTP después de comprobar los proxies y antes de las redirecciones y el enrutamiento.\n\nExample: Escuchar\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nLa petición está preparada para el enrutamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `res` | `Response` | yes |  | La respuesta. |\n\nSe emite después de parsear la petición (cabeceras, flag XHR), antes de buscar la ruta.\n\nExample: Escuchar\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nLa respuesta a una petición ha terminado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `res` | `Response` | yes |  | La respuesta. |\n\nSe emite cuando el framework ha terminado de enviar una respuesta.\n\nExample: Escuchar\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nLa acción de una ruta está a punto de ejecutarse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | El controlador de la petición. |\n| `name` | `String` | yes |  | El nombre del controlador. |\n| `options` | `Object` | yes |  | Las opciones personalizadas de la ruta. |\n\nSe emite antes de que se ejecute la acción de una ruta. Llama a `controller.cancel()` para detener la acción aquí. `name` es el nombre del archivo del controlador que declaró la ruta.\n\nExample: Escuchar\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nLa acción de una ruta de un controlador concreto está a punto de ejecutarse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | El controlador de la petición. |\n| `name` | `String` | yes |  | El nombre del controlador. |\n| `options` | `Object` | yes |  | Las opciones personalizadas de la ruta. |\n\nComo `controller`, pero solo para las rutas declaradas en el archivo de controlador `name`: `ON('@admin')` se ejecuta para las rutas de `controllers/admin.js`.\n\nExample: Escuchar\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nSe envía una respuesta de error, por ejemplo error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `res` | `Response` | yes |  | La respuesta. |\n| `exception` | `Error` | yes |  | El problema, si lo hay. |\n\nEl nombre es `error` más el estado HTTP: `error400`, `error401`, `error404`, `error500`... Se emite cuando el framework responde con ese estado.\n\nExample: Escuchar\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nEl framework ha registrado un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nLo emite el manejador por defecto `DEF.onError` por cada error que registra. Los últimos cinco errores también se guardan en `F.errors`.\n\nExample: Escuchar\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nSe ha registrado una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` o `file`. |\n| `route` | `Object` | yes |  | El objeto interno de la ruta. |\n\n`type` es `'web'` para rutas `ROUTE()`, `'websocket'` para rutas WebSocket y `'file'` para rutas de archivos.\n\nExample: Escuchar\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nSe ha instalado un archivo de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Por ejemplo `'controller'` o `'model'`. |\n| `name` | `String` | yes |  | El nombre del archivo. |\n| `module` | `Object` | yes |  | Los exports del archivo. |\n\nSe emite después de que el framework instale un controlador, modelo, definición, plugin, módulo, source y otros tipos. `module` es lo que exporta el archivo.\n\nExample: Escuchar\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nSe ha cargado la configuración.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | La configuración. |\n\nSe emite cada vez que se leen los archivos de configuración, al inicio y al recargar.\n\nExample: Escuchar\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() ha terminado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | Los errores, o `null`. |\n\nSe emite cuando se han ejecutado los scripts de actualización de `UPDATE()`, con los errores si los hay.\n\nExample: Escuchar\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nSe ha limpiado una caché interna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` o `dns`. |\n| `value` | `Object` | no |  | El almacenamiento temporal, solo para `temporary`. |\n\n`type` es `'temporary'` (con el almacenamiento temporal como `value`), `'resources'` o `'dns'`. El servicio las limpia según los ajustes `default_interval_clear_*`.\n\nExample: Escuchar\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nSe ha guardado un valor con CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `Object` | yes |  | El valor. |\n| `expire` | `Date` | yes |  | La expiración. |\n| `sync` | `Boolean` | yes |  | Un flag interno para cachés sincronizadas. |\n\nLo emite `CACHE.set()`.\n\nExample: Escuchar\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nHa expirado un valor de CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `Object` | yes |  | El valor expirado. |\n\nSe emite cuando la caché elimina un elemento expirado (se comprueba cada minuto) o encuentra uno al leerlo.\n\nExample: Escuchar\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nUna vista está a punto de imprimir sus meta tags.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | El controlador que renderiza la vista. |\n\nSe emite cuando una plantilla (layout) renderiza `@{meta}`, antes de construir las etiquetas. Cambia `controller.repository` aquí para ajustarlas.\n\nExample: Escuchar\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nHa llegado una petición de upgrade a WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La petición. |\n| `socket` | `Socket` | yes |  | El socket de red. |\n| `head` | `Buffer` | yes |  | El primer paquete del stream actualizado. |\n\nSe emite después de encontrar una ruta WebSocket que coincide, antes de aceptar la conexión.\n\nExample: Escuchar\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nSe ha conectado un cliente WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | El controlador WebSocket. |\n| `client` | `WebSocketClient` | yes |  | El cliente. |\n\nSe emite cuando un cliente se añade a su controlador WebSocket, antes de su evento `open`.\n\nExample: Escuchar\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nSe ha desconectado un cliente WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | El controlador WebSocket. |\n| `client` | `WebSocketClient` | yes |  | El cliente. |\n\nSe emite cuando un cliente se elimina de su controlador WebSocket.\n\nExample: Escuchar\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() está a punto de descargar componentes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` contiene `name` y `components` de la llamada a `COMPONENTATOR()`.\n\nExample: Escuchar\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nSe está enviando un mensaje de correo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | El mensaje. |\n\nSe emite para cada mensaje mientras el emisor SMTP lo escribe.\n\nExample: Escuchar\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nEl proceso ha recibido un mensaje IPC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje. |\n| `handle` | `Object` | yes |  | El handle enviado con el mensaje, si lo hay. |\n\nSe emite para cada mensaje que el proceso recibe de su padre (`process.on('message')`), después de que el framework haya gestionado los suyos.\n\nExample: Escuchar\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nEl watcher ha (re)iniciado la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | El proceso de la aplicación, o `null`. |\n\nSe emite en el proceso principal del modo `debug` o `release` con el watcher de archivos, cada vez que inicia el proceso de la aplicación.\n\nExample: Escuchar\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nLa aplicación ha arrancado en modo debug.\n\nSe emite en el proceso de la aplicación cuando arranca por primera vez en modo debug.\n\nExample: Escuchar\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nLa aplicación se ha reiniciado en modo debug.\n\nSe emite en lugar de `debug_start` cuando el watcher de depuración reinicia la aplicación tras un cambio.\n\nExample: Escuchar\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nDestruye un stream después de que haya terminado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un stream de lectura o de escritura. |\n| `callback` | `Function` | no |  | Se llama después de destruir el stream. |\n\nReturns: `Promise` Solo cuando no se define `callback`.\n\nEspera a que el stream termine o falle, lo destruye y llama a `callback`. Sin callback devuelve una Promise.\n\nExample: Cerrar un archivo después de hacer pipe\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: Con await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPa1il61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Planification et événements","summary":"SCHEDULE(), les fonctions d'événements, tous les événements intégrés et les helpers de temporisation.","markdown":"---\ntitle: \"Planification et événements\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Planification et événements\n\n> SCHEDULE(), les fonctions d'événements, tous les événements intégrés et les helpers de temporisation.\n\nLe planificateur `SCHEDULE()`, les fonctions d'événements `ON()`, `ONCE()`, `OFF()`, `EMIT()` et `EMIT2()`, tous les événements intégrés du framework, et les helpers de temporisation `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` et `CLEANUP()`. Le guide [Planification et événements](../../guides/scheduling-and-events/) explique comment les utiliser avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nEnregistre une tâche qui s'exécute à une heure donnée, de façon répétée, ou selon une expression cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | Une expression cron, une chaîne de date ou d'heure, un horodatage ou un Date. |\n| `repeat` | `String` | no |  | Une durée de répétition telle que `'1 day'` ou `'each hour'`. Non utilisée avec une expression cron. |\n| `fn` | `Function` | yes |  | La tâche. Elle ne reçoit aucun argument. |\n\nReturns: `Object` La tâche, avec `id`, `remove()` et `exec()`.\n\nLe framework vérifie les tâches une fois par minute, dans son service : une tâche s'exécute donc lors de la première vérification à son heure ou après.\n\n- Une **chaîne avec un espace** est une expression cron à cinq champs (minute, heure, jour du mois, mois, jour de la semaine). La tâche s'exécute à chaque minute qui correspond ; elle n'accepte pas de `repeat`.\n- Une **chaîne sans espace** est analysée comme une date ou une heure (par exemple `'03:00'`) dans le fuseau horaire de l'application (`default_timezone`). Si elle est déjà passée et que `repeat` est défini, la première exécution est décalée d'un `repeat`.\n- Un **nombre** est un horodatage en millisecondes ; un **Date** est utilisé tel quel.\n\n`repeat` est une durée pour `Date.add()`, telle que `'5 minutes'` ou `'1 day'` ; le mot `each` est lu comme `1` (`'each day'`). Sans `repeat`, une tâche à date s'exécute une fois puis est supprimée.\n\nLes champs cron acceptent `*`, un nombre, une liste (`1,15,30`) et un intervalle (`9-17`). Les jours de la semaine sont `0`-`6` (dimanche vaut `0`) ou des noms, dont seules les deux premières lettres comptent (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Chaque jour à 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron : jours ouvrés à 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Une fois à une date précise\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nL'identifiant de la tâche.\n\nReturns: `String`\n\nUne courte chaîne aléatoire que `SCHEDULE()` crée pour chaque tâche.\n\n### schedule.remove()\n\nType: `method`\n\nArrête la tâche et la retire du planificateur.\n\nUtilise-la pour arrêter une tâche répétée ou cron. Une tâche ponctuelle se supprime elle-même après son exécution.\n\nExample: Arrêter après la première exécution\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nExécute la tâche maintenant.\n\nAppelle immédiatement la fonction de la tâche. L'heure prévue de la prochaine exécution ne change pas.\n\nExample: Exécuter au démarrage puis chaque heure\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAjoute un écouteur à un événement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | yes |  | L'écouteur. |\n\n`fn` est appelée avec les arguments de `EMIT()`, et `this` est le framework. Les écouteurs s'exécutent dans l'ordre où ils ont été ajoutés.\n\nPour `init`, `load` et `ready`, si l'application est déjà chargée, `fn` est appelée immédiatement (et n'est pas conservée).\n\nExample: Réagir au démarrage\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAjoute un écouteur qui est supprimé après son premier appel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | yes |  | L'écouteur. |\n\nFonctionne comme `ON()` ; l'écouteur est supprimé après le premier `EMIT()` de l'événement.\n\nExample: Première requête uniquement\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nSupprime des écouteurs d'événements.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom de l'événement. |\n| `fn` | `Function` | no |  | L'écouteur à supprimer. |\n\n- `OFF(name, fn)` supprime cet écouteur précis. Ce doit être la même fonction que celle passée à `ON()`.\n- `OFF(name)` supprime tous les écouteurs de l'événement, y compris ceux du framework.\n- `OFF()` supprime tous les écouteurs de tous les événements.\n\nExample: Supprimer un écouteur\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nAppelle tous les écouteurs d'un événement dans le processus courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `a...g` | `Object` | no |  | Jusqu'à sept arguments pour les écouteurs. |\n\nPasse jusqu'à sept arguments. Les écouteurs s'exécutent de manière synchrone, dans l'ordre où ils ont été ajoutés. Les écouteurs ajoutés avec `ONCE()` sont ensuite supprimés. Un événement sans écouteur ne fait rien.\n\nExample: Ton propre événement\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nEnvoie un événement aux autres processus de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `a...e` | `Object` | no |  | Jusqu'à cinq arguments sérialisables. |\n\nL'événement part vers les threads (depuis le processus principal, qui appelle aussi ses propres écouteurs), vers le cluster, ou depuis un thread ou un worker vers son parent. Jusqu'à cinq arguments, envoyés sous forme de messages IPC : utilise donc des valeurs simples et sérialisables. Dans un processus unique sans threads ni cluster, rien ne se passe ; utilise `EMIT()` dans ce cas.\n\nExample: Vider un cache dans chaque processus\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nAttend qu'une condition soit vraie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Renvoie `true` quand l'attente est terminée. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Attente maximale en millisecondes. |\n| `interval` | `Number` | no | `500` | Intervalle de vérification en millisecondes. |\n\nSi `validator()` renvoie déjà `true`, `callback(null, true)` s'exécute immédiatement. Sinon, `validator()` est vérifié toutes les `interval` ms. Quand il renvoie `true`, le callback reçoit `(null, true)` ; après `timeout` ms, il reçoit `(Error(\"Timeout\"), false)`.\n\nExample: Attendre une connexion\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nUn timeout nommé : chaque appel avec le même nom relance le minuteur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du minuteur. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Délai en millisecondes. |\n| `limit` | `Number` | no |  | Nombre maximal de reports avant que `fn` ne s'exécute immédiatement. |\n| `param` | `Object` | no |  | Un argument pour `fn`. |\n\nReturns: `Timeout` Le minuteur Node.js, ou rien quand `fn` s'est exécutée immédiatement.\n\nAnnule le minuteur précédent du même nom et en démarre un nouveau : `fn` s'exécute donc une fois, `timeout` ms après le dernier appel (un debounce). Avec `limit`, après `limit` reports, `fn` s'exécute immédiatement (sans `param`) et le compteur est remis à zéro. `param` est passé à `fn`.\n\nExample: Enregistrer une fois après une rafale de modifications\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nAnnule un minuteur créé par setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom utilisé dans `setTimeout2()`. |\n\nReturns: `Boolean` `true` si un minuteur a été annulé.\n\nRenvoie `true` si un minuteur en attente portant ce nom a été annulé.\n\nExample: Annuler\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nMet le serveur en pause : chaque requête reçoit 503 tant qu'un nom est en pause.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom pour la pause. |\n| `enable` | `Boolean` | no |  | `true` met en pause, `false` reprend. S'il est omis, l'état est inversé. |\n\nReturns: `Boolean` `true` si `name` est maintenant en pause.\n\nChaque `name` est une raison de mettre en pause. Tant qu'au moins un nom est en pause, les requêtes HTTP reçoivent `503` et les upgrades WebSocket sont refusés. Avec `enable`, l'état est défini ; sans lui, l'état de `name` est inversé. `F.wait()` est la même fonction.\n\nExample: Mettre en pause pendant une migration\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinutes entre les nettoyages du cache des fichiers temporaires et des vues.\n\nReturns: `Number`\n\nCompté en ticks du service (un par minute). Chaque nettoyage émet `clear` avec le type `'temporary'`.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinutes entre les nettoyages des ressources chargées.\n\nReturns: `Number`\n\nCompté en ticks du service. Chaque nettoyage émet `clear` avec le type `'resources'`.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinutes entre les nettoyages du cache DNS.\n\nReturns: `Number`\n\nCompté en ticks du service. Chaque nettoyage émet `clear` avec le type `'dns'`.\n\n### ON('init', function())\n\nType: `event`\n\nLa configuration est chargée ; les fichiers de l'application ne le sont pas encore.\n\nÉmis une fois au démarrage, avant le chargement des définitions, des modèles, des contrôleurs et des autres fichiers. Si tu appelles `ON('init')` après le chargement de l'application, la fonction s'exécute immédiatement.\n\nExample: Écouter\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nTous les fichiers de l'application sont chargés.\n\nÉmis une fois, juste avant `ready`. Si l'application est déjà chargée, la fonction s'exécute immédiatement.\n\nExample: Écouter\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nL'application est prête.\n\nÉmis une fois après `load`, quand tous les fichiers sont chargés. L'endroit habituel pour le code de démarrage. Si l'application est déjà chargée, la fonction s'exécute immédiatement.\n\nExample: Écouter\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nÉmis chaque minute par le service du framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Le nombre d'exécutions du service. |\n\n`counter` est le nombre d'exécutions depuis le démarrage de l'application (1, 2, 3...). Utilise le reste de la division pour exécuter du code toutes les quelques minutes. Dans un worker, l'ajout de cet écouteur démarre le minuteur.\n\nExample: Écouter\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nL'application s'arrête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | Le signal ; `15` (SIGTERM) si aucun n'a été donné. |\n\nÉmis une fois quand le framework s'arrête, après avoir envoyé le signal à ses workers et à ses threads. Garde un traitement synchrone ; le processus se termine peu après.\n\nExample: Écouter\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nUne requête est arrivée, avant le routage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `res` | `Response` | yes |  | La réponse. |\n\nÉmis pour chaque requête HTTP après la vérification des proxys et avant les redirections et le routage.\n\nExample: Écouter\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nLa requête est préparée pour le routage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `res` | `Response` | yes |  | La réponse. |\n\nÉmis après l'analyse de la requête (en-têtes, flag XHR), avant la recherche de la route.\n\nExample: Écouter\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nLa réponse à une requête est terminée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `res` | `Response` | yes |  | La réponse. |\n\nÉmis quand le framework a fini d'envoyer une réponse.\n\nExample: Écouter\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nL'action d'une route va s'exécuter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Le contrôleur de la requête. |\n| `name` | `String` | yes |  | Le nom du contrôleur. |\n| `options` | `Object` | yes |  | Les options personnalisées de la route. |\n\nÉmis avant l'exécution de l'action d'une route. Appelle `controller.cancel()` pour arrêter l'action à ce stade. `name` est le nom du fichier de contrôleur qui a déclaré la route.\n\nExample: Écouter\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nL'action d'une route d'un contrôleur donné va s'exécuter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Le contrôleur de la requête. |\n| `name` | `String` | yes |  | Le nom du contrôleur. |\n| `options` | `Object` | yes |  | Les options personnalisées de la route. |\n\nComme `controller`, mais uniquement pour les routes déclarées dans le fichier de contrôleur `name` : `ON('@admin')` s'exécute pour les routes de `controllers/admin.js`.\n\nExample: Écouter\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nUne réponse d'erreur est envoyée, par exemple error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `res` | `Response` | yes |  | La réponse. |\n| `exception` | `Error` | yes |  | Le problème, le cas échéant. |\n\nLe nom est `error` suivi du statut HTTP : `error400`, `error401`, `error404`, `error500`... Émis quand le framework répond avec ce statut.\n\nExample: Écouter\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nLe framework a journalisé une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nÉmis par le gestionnaire par défaut `DEF.onError` pour chaque erreur qu'il enregistre. Les cinq dernières erreurs sont aussi conservées dans `F.errors`.\n\nExample: Écouter\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nUne route a été enregistrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` ou `file`. |\n| `route` | `Object` | yes |  | L'objet route interne. |\n\n`type` vaut `'web'` pour les routes `ROUTE()`, `'websocket'` pour les routes WebSocket et `'file'` pour les routes de fichiers.\n\nExample: Écouter\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nUn fichier de l'application a été installé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Par exemple `'controller'` ou `'model'`. |\n| `name` | `String` | yes |  | Le nom du fichier. |\n| `module` | `Object` | yes |  | Les exports du fichier. |\n\nÉmis après que le framework a installé un contrôleur, un modèle, une définition, un plugin, un module, une source et d'autres types. `module` est ce que le fichier exporte.\n\nExample: Écouter\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nLa configuration a été chargée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | La configuration. |\n\nÉmis à chaque lecture des fichiers de configuration, au démarrage et lors d'un rechargement.\n\nExample: Écouter\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() est terminé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | Les erreurs, ou `null`. |\n\nÉmis quand les scripts de mise à jour de `UPDATE()` se sont exécutés, avec les erreurs éventuelles.\n\nExample: Écouter\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nUn cache interne a été vidé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` ou `dns`. |\n| `value` | `Object` | no |  | Le stockage temporaire, uniquement pour `temporary`. |\n\n`type` vaut `'temporary'` (avec le stockage temporaire comme `value`), `'resources'` ou `'dns'`. Le service les vide selon les paramètres `default_interval_clear_*`.\n\nExample: Écouter\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nUne valeur a été stockée avec CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `Object` | yes |  | La valeur. |\n| `expire` | `Date` | yes |  | L'expiration. |\n| `sync` | `Boolean` | yes |  | Un flag interne pour les caches synchronisés. |\n\nÉmis par `CACHE.set()`.\n\nExample: Écouter\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nUne valeur CACHE a expiré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `Object` | yes |  | La valeur expirée. |\n\nÉmis quand le cache supprime un élément expiré (vérifié chaque minute) ou en trouve un lors de sa lecture.\n\nExample: Écouter\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nUne vue va afficher ses balises meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Le contrôleur qui rend la vue. |\n\nÉmis quand un layout rend `@{meta}`, avant la construction des balises. Modifie `controller.repository` ici pour les ajuster.\n\nExample: Écouter\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nUne requête d'upgrade WebSocket est arrivée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La requête. |\n| `socket` | `Socket` | yes |  | Le socket réseau. |\n| `head` | `Buffer` | yes |  | Le premier paquet du flux upgradé. |\n\nÉmis après qu'une route WebSocket correspondante a été trouvée, avant l'acceptation de la connexion.\n\nExample: Écouter\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nUn client WebSocket s'est connecté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Le contrôleur WebSocket. |\n| `client` | `WebSocketClient` | yes |  | Le client. |\n\nÉmis quand un client est ajouté à son contrôleur WebSocket, avant son événement `open`.\n\nExample: Écouter\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nUn client WebSocket s'est déconnecté.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Le contrôleur WebSocket. |\n| `client` | `WebSocketClient` | yes |  | Le client. |\n\nÉmis quand un client est retiré de son contrôleur WebSocket.\n\nExample: Écouter\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() va télécharger des composants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` contient `name` et `components` de l'appel à `COMPONENTATOR()`.\n\nExample: Écouter\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nUn e-mail est en cours d'envoi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Le message. |\n\nÉmis pour chaque message au moment où l'expéditeur SMTP l'écrit.\n\nExample: Écouter\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nLe processus a reçu un message IPC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message. |\n| `handle` | `Object` | yes |  | Le handle envoyé avec le message, le cas échéant. |\n\nÉmis pour chaque message que le processus reçoit de son parent (`process.on('message')`), après que le framework a traité les siens.\n\nExample: Écouter\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nLe watcher a (re)démarré l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | Le processus de l'application, ou `null`. |\n\nÉmis dans le processus principal du mode `debug` ou `release` avec le watcher de fichiers, chaque fois qu'il démarre le processus de l'application.\n\nExample: Écouter\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nL'application a démarré en mode debug.\n\nÉmis dans le processus de l'application lors de son premier démarrage en mode debug.\n\nExample: Écouter\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nL'application a redémarré en mode debug.\n\nÉmis à la place de `debug_start` quand le watcher de debug redémarre l'application après une modification.\n\nExample: Écouter\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nDétruit un flux une fois qu'il est terminé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un flux en lecture ou en écriture. |\n| `callback` | `Function` | no |  | Appelé après la destruction du flux. |\n\nReturns: `Promise` Uniquement quand `callback` n'est pas défini.\n\nAttend que le flux se termine ou échoue, le détruit et appelle `callback`. Sans callback, renvoie une Promise.\n\nExample: Fermer un fichier après un pipe\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: Avec await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPa1il61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Pianificazione ed eventi","summary":"SCHEDULE(), le funzioni per gli eventi, ogni evento integrato e gli helper di temporizzazione.","markdown":"---\ntitle: Pianificazione ed eventi\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Pianificazione ed eventi\n\n> SCHEDULE(), le funzioni per gli eventi, ogni evento integrato e gli helper di temporizzazione.\n\nLo scheduler `SCHEDULE()`, le funzioni per gli eventi `ON()`, `ONCE()`, `OFF()`, `EMIT()` ed `EMIT2()`, ogni evento integrato del framework e gli helper di temporizzazione `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` e `CLEANUP()`. La guida [Pianificazione ed eventi](../../guides/scheduling-and-events/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nRegistra un job che viene eseguito a un orario, ripetutamente o tramite un'espressione cron.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | Un'espressione cron, una stringa di data o orario, un timestamp o un Date. |\n| `repeat` | `String` | no |  | Un periodo di ripetizione come `'1 day'` o `'each hour'`. Non usato con un'espressione cron. |\n| `fn` | `Function` | yes |  | Il job. Non riceve argomenti. |\n\nReturns: `Object` Il job, con `id`, `remove()` ed `exec()`.\n\nIl framework controlla i job una volta al minuto, nel suo servizio, quindi un job viene eseguito al primo controllo pari o successivo al suo orario.\n\n- Una **stringa con uno spazio** è un'espressione cron con cinque campi (minuto, ora, giorno del mese, mese, giorno della settimana). Il job viene eseguito a ogni minuto che corrisponde; non accetta `repeat`.\n- Una **stringa senza spazi** viene interpretata come data o orario (ad esempio `'03:00'`) nel fuso orario dell'applicazione (`default_timezone`). Se è già passata ed è impostato `repeat`, la prima esecuzione viene spostata avanti di un `repeat`.\n- Un **numero** è un timestamp in millisecondi; un **Date** viene usato così com'è.\n\n`repeat` è un periodo per `Date.add()`, come `'5 minutes'` o `'1 day'`; la parola `each` viene letta come `1` (`'each day'`). Senza `repeat` un job a data viene eseguito una volta e poi rimosso.\n\nI campi cron accettano `*`, un numero, un elenco (`1,15,30`) e un intervallo (`9-17`). I giorni della settimana sono `0`-`6` (la domenica è `0`) oppure nomi, di cui contano solo le prime due lettere (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Ogni giorno alle 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron: giorni lavorativi alle 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Una volta a una data precisa\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nL'identificatore del job.\n\nReturns: `String`\n\nUna breve stringa casuale che `SCHEDULE()` crea per ogni job.\n\n### schedule.remove()\n\nType: `method`\n\nFerma il job e lo rimuove dallo scheduler.\n\nUsalo per fermare un job ripetuto o cron. Un job da eseguire una sola volta si rimuove da solo dopo l'esecuzione.\n\nExample: Fermare dopo la prima esecuzione\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nEsegue il job adesso.\n\nChiama subito la funzione del job. L'orario pianificato della prossima esecuzione non cambia.\n\nExample: Eseguire all'avvio e poi ogni ora\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nAggiunge un listener a un evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | yes |  | Il listener. |\n\n`fn` viene chiamata con gli argomenti di `EMIT()`, e `this` è il framework. I listener vengono eseguiti nell'ordine in cui sono stati aggiunti.\n\nPer `init`, `load` e `ready`, se l'applicazione è già stata caricata, `fn` viene chiamata immediatamente (e non viene memorizzata).\n\nExample: Reagire all'avvio\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nAggiunge un listener che viene rimosso dopo la prima chiamata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | yes |  | Il listener. |\n\nFunziona come `ON()`; il listener viene rimosso dopo il primo `EMIT()` dell'evento.\n\nExample: Solo la prima richiesta\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nRimuove i listener degli eventi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome dell'evento. |\n| `fn` | `Function` | no |  | Il listener da rimuovere. |\n\n- `OFF(name, fn)` rimuove quel singolo listener. Deve essere la stessa funzione che hai passato a `ON()`.\n- `OFF(name)` rimuove tutti i listener dell'evento, compresi quelli del framework.\n- `OFF()` rimuove tutti i listener di tutti gli eventi.\n\nExample: Rimuovere un listener\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nChiama tutti i listener di un evento nel processo corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `a...g` | `Object` | no |  | Fino a sette argomenti per i listener. |\n\nPassa fino a sette argomenti. I listener vengono eseguiti in modo sincrono, nell'ordine in cui sono stati aggiunti. I listener aggiunti con `ONCE()` vengono poi rimossi. Un evento senza listener non fa nulla.\n\nExample: Un tuo evento\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nInvia un evento agli altri processi dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `a...e` | `Object` | no |  | Fino a cinque argomenti serializzabili. |\n\nL'evento va ai thread (dal processo principale, che chiama anche i propri listener), al cluster, oppure da un thread o worker al suo processo padre. Fino a cinque argomenti, inviati come messaggi IPC, quindi usa semplici valori serializzabili. In un singolo processo senza thread né cluster non succede nulla; lì usa `EMIT()`.\n\nExample: Svuotare una cache in ogni processo\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nAttende finché una condizione è vera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Restituisce `true` quando l'attesa è finita. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Attesa massima in millisecondi. |\n| `interval` | `Number` | no | `500` | Intervallo di controllo in millisecondi. |\n\nSe `validator()` restituisce già `true`, `callback(null, true)` viene eseguita immediatamente. Altrimenti `validator()` viene controllato ogni `interval` ms. Quando restituisce `true` la callback riceve `(null, true)`; dopo `timeout` ms riceve `(Error(\"Timeout\"), false)`.\n\nExample: Attendere una connessione\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nUn timeout con nome: ogni chiamata con lo stesso nome riavvia il timer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del timer. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Ritardo in millisecondi. |\n| `limit` | `Number` | no |  | Numero massimo di rinvii prima che `fn` venga eseguita subito. |\n| `param` | `Object` | no |  | Un argomento per `fn`. |\n\nReturns: `Timeout` Il timer di Node.js, oppure nulla quando `fn` è stata eseguita immediatamente.\n\nAnnulla il timer precedente con lo stesso nome e ne avvia uno nuovo, quindi `fn` viene eseguita una volta, `timeout` ms dopo l'ultima chiamata (un debounce). Con `limit`, dopo `limit` rinvii `fn` viene eseguita immediatamente (senza `param`) e il contatore si azzera. `param` viene passato a `fn`.\n\nExample: Salvare una volta dopo una raffica di modifiche\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nAnnulla un timer creato da setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome usato in `setTimeout2()`. |\n\nReturns: `Boolean` `true` se è stato annullato un timer.\n\nRestituisce `true` se è stato annullato un timer in sospeso con quel nome.\n\nExample: Annullare\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nMette in pausa il server: ogni richiesta riceve 503 finché un nome è in pausa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome per la pausa. |\n| `enable` | `Boolean` | no |  | `true` mette in pausa, `false` riprende. Se omesso, lo stato viene invertito. |\n\nReturns: `Boolean` `true` se `name` è ora in pausa.\n\nOgni `name` è un motivo di pausa. Finché almeno un nome è in pausa, le richieste HTTP ricevono la risposta `503` e gli upgrade WebSocket vengono rifiutati. Con `enable` lo stato viene impostato; senza, lo stato di `name` viene invertito. `F.wait()` è la stessa funzione.\n\nExample: Pausa durante una migrazione\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinuti tra le pulizie della cache dei file temporanei e delle viste.\n\nReturns: `Number`\n\nContati in tick del servizio (uno al minuto). Ogni pulizia emette `clear` con il tipo `'temporary'`.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinuti tra le pulizie delle risorse caricate.\n\nReturns: `Number`\n\nContati in tick del servizio. Ogni pulizia emette `clear` con il tipo `'resources'`.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinuti tra le pulizie della cache DNS.\n\nReturns: `Number`\n\nContati in tick del servizio. Ogni pulizia emette `clear` con il tipo `'dns'`.\n\n### ON('init', function())\n\nType: `event`\n\nLa configurazione è caricata; i file dell'applicazione non sono ancora caricati.\n\nEmesso una volta all'avvio, prima che vengano caricati definizioni, modelli, controller e gli altri file. Se chiami `ON('init')` dopo che l'applicazione è stata caricata, la funzione viene eseguita immediatamente.\n\nExample: Ascoltare\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nTutti i file dell'applicazione sono caricati.\n\nEmesso una volta, subito prima di `ready`. Se l'applicazione è già stata caricata, la funzione viene eseguita immediatamente.\n\nExample: Ascoltare\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nL'applicazione è pronta.\n\nEmesso una volta dopo `load`, quando tutti i file sono caricati. Il posto abituale per il codice di avvio. Se l'applicazione è già stata caricata, la funzione viene eseguita immediatamente.\n\nExample: Ascoltare\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nEmesso ogni minuto dal servizio del framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Il numero di esecuzioni del servizio. |\n\n`counter` è il numero di esecuzioni dall'avvio dell'applicazione (1, 2, 3...). Usa il resto della divisione per eseguire codice ogni pochi minuti. In un worker, aggiungere questo listener avvia il timer.\n\nExample: Ascoltare\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nL'applicazione si sta fermando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | Il segnale; `15` (SIGTERM) quando non ne è stato indicato nessuno. |\n\nEmesso una volta quando il framework si ferma, dopo aver inviato il segnale ai suoi worker e thread. Mantieni il lavoro sincrono; il processo termina poco dopo.\n\nExample: Ascoltare\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nÈ arrivata una richiesta, prima del routing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `res` | `Response` | yes |  | La risposta. |\n\nEmesso per ogni richiesta HTTP dopo il controllo dei proxy e prima dei redirect e del routing.\n\nExample: Ascoltare\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nLa richiesta è pronta per il routing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `res` | `Response` | yes |  | La risposta. |\n\nEmesso dopo che la richiesta è stata analizzata (header, flag XHR), prima che venga cercata la route.\n\nExample: Ascoltare\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nLa risposta a una richiesta è terminata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `res` | `Response` | yes |  | La risposta. |\n\nEmesso quando il framework ha finito di inviare una risposta.\n\nExample: Ascoltare\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nL'azione di una route sta per essere eseguita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Il controller della richiesta. |\n| `name` | `String` | yes |  | Il nome del controller. |\n| `options` | `Object` | yes |  | Le opzioni personalizzate della route. |\n\nEmesso prima che venga eseguita l'azione di una route. Chiama `controller.cancel()` per fermare qui l'azione. `name` è il nome del file del controller che ha dichiarato la route.\n\nExample: Ascoltare\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nL'azione di una route di un controller sta per essere eseguita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Il controller della richiesta. |\n| `name` | `String` | yes |  | Il nome del controller. |\n| `options` | `Object` | yes |  | Le opzioni personalizzate della route. |\n\nCome `controller`, ma solo per le route dichiarate nel file del controller `name`: `ON('@admin')` viene eseguito per le route in `controllers/admin.js`.\n\nExample: Ascoltare\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nViene inviata una risposta di errore, ad esempio error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `res` | `Response` | yes |  | La risposta. |\n| `exception` | `Error` | yes |  | Il problema, se presente. |\n\nIl nome è `error` più lo stato HTTP: `error400`, `error401`, `error404`, `error500`... Emesso quando il framework risponde con quello stato.\n\nExample: Ascoltare\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nIl framework ha registrato un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nEmesso dall'handler predefinito `DEF.onError` per ogni errore che registra. Gli ultimi cinque errori vengono conservati anche in `F.errors`.\n\nExample: Ascoltare\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nÈ stata registrata una route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` o `file`. |\n| `route` | `Object` | yes |  | L'oggetto interno della route. |\n\n`type` è `'web'` per le route `ROUTE()`, `'websocket'` per le route WebSocket e `'file'` per le route di file.\n\nExample: Ascoltare\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nÈ stato installato un file dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Ad esempio `'controller'` o `'model'`. |\n| `name` | `String` | yes |  | Il nome del file. |\n| `module` | `Object` | yes |  | Gli export del file. |\n\nEmesso dopo che il framework installa un controller, un modello, una definizione, un plugin, un modulo, un sorgente e altri tipi. `module` è ciò che il file esporta.\n\nExample: Ascoltare\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nLa configurazione è stata caricata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | La configurazione. |\n\nEmesso ogni volta che vengono letti i file di configurazione, all'avvio e al ricaricamento.\n\nExample: Ascoltare\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() è terminato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | Gli errori, oppure `null`. |\n\nEmesso quando gli script di aggiornamento di `UPDATE()` sono stati eseguiti, con gli eventuali errori.\n\nExample: Ascoltare\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nÈ stata svuotata una cache interna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` o `dns`. |\n| `value` | `Object` | no |  | Lo storage temporaneo, solo per `temporary`. |\n\n`type` è `'temporary'` (con lo storage temporaneo come `value`), `'resources'` o `'dns'`. Il servizio le svuota secondo le impostazioni `default_interval_clear_*`.\n\nExample: Ascoltare\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nÈ stato memorizzato un valore con CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `Object` | yes |  | Il valore. |\n| `expire` | `Date` | yes |  | La scadenza. |\n| `sync` | `Boolean` | yes |  | Un flag interno per le cache sincronizzate. |\n\nEmesso da `CACHE.set()`.\n\nExample: Ascoltare\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nUn valore di CACHE è scaduto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `Object` | yes |  | Il valore scaduto. |\n\nEmesso quando la cache rimuove un elemento scaduto (controllato ogni minuto) o ne trova uno durante la lettura.\n\nExample: Ascoltare\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nUna vista sta per stampare i suoi meta tag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Il controller che esegue il rendering della vista. |\n\nEmesso quando un layout esegue il rendering di `@{meta}`, prima che vengano costruiti i tag. Modifica qui `controller.repository` per adattarli.\n\nExample: Ascoltare\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nÈ arrivata una richiesta di upgrade WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | La richiesta. |\n| `socket` | `Socket` | yes |  | Il socket di rete. |\n| `head` | `Buffer` | yes |  | Il primo pacchetto dello stream dopo l'upgrade. |\n\nEmesso dopo che è stata trovata una route WebSocket corrispondente, prima che la connessione venga accettata.\n\nExample: Ascoltare\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nUn client WebSocket si è connesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Il controller WebSocket. |\n| `client` | `WebSocketClient` | yes |  | Il client. |\n\nEmesso quando un client viene aggiunto al suo controller WebSocket, prima del suo evento `open`.\n\nExample: Ascoltare\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nUn client WebSocket si è disconnesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | Il controller WebSocket. |\n| `client` | `WebSocketClient` | yes |  | Il client. |\n\nEmesso quando un client viene rimosso dal suo controller WebSocket.\n\nExample: Ascoltare\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() sta per scaricare i componenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` contiene `name` e `components` della chiamata `COMPONENTATOR()`.\n\nExample: Ascoltare\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nViene inviato un messaggio email.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Il messaggio. |\n\nEmesso per ogni messaggio mentre il mittente SMTP lo scrive.\n\nExample: Ascoltare\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nIl processo ha ricevuto un messaggio IPC.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio. |\n| `handle` | `Object` | yes |  | L'handle inviato con il messaggio, se presente. |\n\nEmesso per ogni messaggio che il processo riceve dal suo processo padre (`process.on('message')`), dopo che il framework ha gestito i propri.\n\nExample: Ascoltare\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nIl watcher ha (ri)avviato l'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | Il processo dell'applicazione, oppure `null`. |\n\nEmesso nel processo principale della modalità `debug` o `release` con il watcher dei file, ogni volta che avvia il processo dell'applicazione.\n\nExample: Ascoltare\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nL'applicazione è stata avviata in modalità debug.\n\nEmesso nel processo dell'applicazione quando si avvia per la prima volta in modalità debug.\n\nExample: Ascoltare\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nL'applicazione è stata riavviata in modalità debug.\n\nEmesso al posto di `debug_start` quando il watcher di debug riavvia l'applicazione dopo una modifica.\n\nExample: Ascoltare\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nDistrugge uno stream dopo che ha finito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Uno stream leggibile o scrivibile. |\n| `callback` | `Function` | no |  | Chiamata dopo che lo stream è stato distrutto. |\n\nReturns: `Promise` Solo quando `callback` non è impostata.\n\nAttende che lo stream finisca o fallisca, lo distrugge e chiama `callback`. Senza callback restituisce una Promise.\n\nExample: Chiudere un file dopo il pipe\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: Con await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabnPa1il61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/scheduling-and-events/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Plánovanie a udalosti","summary":"SCHEDULE(), funkcie udalostí, všetky vstavané udalosti a pomocné funkcie pre časovanie.","markdown":"---\ntitle: \"Plánovanie a udalosti\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/scheduling-and-events/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Plánovanie a udalosti\n\n> SCHEDULE(), funkcie udalostí, všetky vstavané udalosti a pomocné funkcie pre časovanie.\n\nPlánovač `SCHEDULE()`, funkcie udalostí `ON()`, `ONCE()`, `OFF()`, `EMIT()` a `EMIT2()`, všetky vstavané udalosti frameworku a pomocné funkcie pre časovanie `WAIT()`, `setTimeout2()`, `clearTimeout2()`, `PAUSESERVER()` a `CLEANUP()`. Návod [Plánovanie a udalosti](../../guides/scheduling-and-events/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### SCHEDULE(date, [repeat], fn)\n\nType: `method`\n\nZaregistruje úlohu, ktorá sa spustí v určitý čas, opakovane alebo podľa cron výrazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String|Number|Date` | yes |  | Cron výraz, reťazec s dátumom alebo časom, časová pečiatka alebo Date. |\n| `repeat` | `String` | no |  | Obdobie opakovania, napríklad `'1 day'` alebo `'each hour'`. Nepoužíva sa s cron výrazom. |\n| `fn` | `Function` | yes |  | Úloha. Nedostáva žiadne argumenty. |\n\nReturns: `Object` Úloha s `id`, `remove()` a `exec()`.\n\nFramework kontroluje úlohy raz za minútu vo svojej službe, takže úloha sa spustí pri prvej kontrole v jej čase alebo po ňom.\n\n- **Reťazec s medzerou** je cron výraz s piatimi poľami (minúta, hodina, deň v mesiaci, mesiac, deň v týždni). Úloha sa spúšťa v každej minúte, ktorá mu zodpovedá; neberie `repeat`.\n- **Reťazec bez medzery** sa spracuje ako dátum alebo čas (napríklad `'03:00'`) v časovom pásme aplikácie (`default_timezone`). Ak už uplynul a `repeat` je nastavený, prvé spustenie sa posunie dopredu o jedno `repeat`.\n- **Číslo** je časová pečiatka v milisekundách; **Date** sa použije tak, ako je.\n\n`repeat` je obdobie pre `Date.add()`, napríklad `'5 minutes'` alebo `'1 day'`; slovo `each` sa číta ako `1` (`'each day'`). Bez `repeat` sa úloha s dátumom spustí raz a potom sa odstráni.\n\nPolia cronu prijímajú `*`, číslo, zoznam (`1,15,30`) a rozsah (`9-17`). Dni v týždni sú `0`-`6` (nedeľa je `0`) alebo názvy, z ktorých sa rátajú iba prvé dve písmená (`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`).\n\nExample: Každý deň o 03:00\n```js\nSCHEDULE('03:00', '1 day', function() {\n\tconsole.log('Nightly cleanup');\n});\n```\n\nExample: Cron: pracovné dni o 08:00\n```js\nSCHEDULE('0 8 * * mo-fr', function() {\n\tconsole.log('Good morning');\n});\n```\n\nExample: Raz v konkrétny dátum\n```js\nSCHEDULE(new Date(2026, 11, 24, 8, 0), function() {\n\tconsole.log('Christmas Eve');\n});\n```\n\n### schedule.id\n\nType: `property`\n\nIdentifikátor úlohy.\n\nReturns: `String`\n\nKrátky náhodný reťazec, ktorý `SCHEDULE()` vytvorí pre každú úlohu.\n\n### schedule.remove()\n\nType: `method`\n\nZastaví úlohu a odstráni ju z plánovača.\n\nPouži ju na zastavenie opakovanej alebo cron úlohy. Jednorazová úloha sa po spustení odstráni sama.\n\nExample: Zastavenie po prvom spustení\n```js\nvar job = SCHEDULE('0,30 * * * *', function() {\n\tconsole.log('Run');\n\tjob.remove();\n});\n```\n\n### schedule.exec()\n\nType: `method`\n\nSpustí úlohu teraz.\n\nOkamžite zavolá funkciu úlohy. Plánovaný čas ďalšieho spustenia sa nezmení.\n\nExample: Spustenie pri štarte a potom každú hodinu\n```js\nvar job = SCHEDULE('0 * * * *', refresh);\n\nON('ready', function() {\n\tjob.exec();\n});\n```\n\n### ON(name, fn)\n\nType: `method`\n\nPridá listener k udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | yes |  | Listener. |\n\n`fn` sa volá s argumentmi z `EMIT()` a `this` je framework. Listenery sa spúšťajú v poradí, v akom boli pridané.\n\nPri `init`, `load` a `ready` sa `fn` zavolá okamžite (a neuloží sa), ak je aplikácia už načítaná.\n\nExample: Reakcia na štart\n```js\nON('ready', function() {\n\tconsole.log('Listening on port', F.port);\n});\n```\n\n### ONCE(name, fn)\n\nType: `method`\n\nPridá listener, ktorý sa po prvom volaní odstráni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | yes |  | Listener. |\n\nFunguje ako `ON()`; listener sa odstráni po prvom `EMIT()` udalosti.\n\nExample: Iba prvá požiadavka\n```js\nONCE('request', function(req) {\n\tconsole.log('First request from', req.ip);\n});\n```\n\n### OFF([name], [fn])\n\nType: `method`\n\nOdstráni listenery udalostí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov udalosti. |\n| `fn` | `Function` | no |  | Listener na odstránenie. |\n\n- `OFF(name, fn)` odstráni tento jeden listener. Musí to byť tá istá funkcia, ktorú si odovzdal do `ON()`.\n- `OFF(name)` odstráni všetky listenery udalosti, vrátane vlastných listenerov frameworku.\n- `OFF()` odstráni všetky listenery všetkých udalostí.\n\nExample: Odstránenie jedného listenera\n```js\nfunction log(req, res) {\n\tconsole.log(req.url);\n}\n\nON('request', log);\nOFF('request', log);\n```\n\n### EMIT(name, [a], [b], [c], [d], [e], [f], [g])\n\nType: `method`\n\nZavolá všetky listenery udalosti v aktuálnom procese.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `a...g` | `Object` | no |  | Najviac sedem argumentov pre listenery. |\n\nOdovzdá najviac sedem argumentov. Listenery sa spúšťajú synchrónne, v poradí, v akom boli pridané. Listenery pridané pomocou `ONCE()` sa potom odstránia. Udalosť bez listenerov nerobí nič.\n\nExample: Vlastná udalosť\n```js\nON('order_created', function(order) {\n\tconsole.log('New order', order.id);\n});\n\nEMIT('order_created', { id: 'A100' });\n```\n\n### EMIT2(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nPošle udalosť ostatným procesom aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `a...e` | `Object` | no |  | Najviac päť serializovateľných argumentov. |\n\nUdalosť ide do vlákien (z hlavného procesu, ktorý zavolá aj svoje vlastné listenery), do klastra alebo z vlákna či workera späť k jeho rodičovi. Najviac päť argumentov, odoslaných ako IPC správy, takže používaj jednoduché serializovateľné hodnoty. V jednom procese bez vlákien alebo klastra sa nič nestane; tam použi `EMIT()`.\n\nExample: Vyčistenie cache v každom procese\n```js\nON('products_changed', function() {\n\tCACHE.remove('products');\n});\n\nEMIT2('products_changed');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nČaká, kým nie je podmienka splnená.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Vráti `true`, keď čakanie skončilo. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximálne čakanie v milisekundách. |\n| `interval` | `Number` | no | `500` | Interval kontroly v milisekundách. |\n\nAk `validator()` už vracia `true`, `callback(null, true)` sa spustí okamžite. Inak sa `validator()` kontroluje každých `interval` ms. Keď vráti `true`, callback dostane `(null, true)`; po `timeout` ms dostane `(Error(\"Timeout\"), false)`.\n\nExample: Čakanie na spojenie\n```js\nWAIT(() => MAIN.client != null, function(err) {\n\tif (err)\n\t\tconsole.log('Not connected');\n\telse\n\t\tMAIN.client.send('hello');\n}, 10000);\n```\n\n### setTimeout2(name, fn, timeout, [limit], [param])\n\nType: `method`\n\nPomenovaný timeout: každé volanie s rovnakým názvom reštartuje časovač.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov časovača. |\n| `fn` | `Function` | yes |  | `function(param)`. |\n| `timeout` | `Number` | yes |  | Oneskorenie v milisekundách. |\n| `limit` | `Number` | no |  | Maximálny počet odložení, po ktorom sa `fn` spustí okamžite. |\n| `param` | `Object` | no |  | Argument pre `fn`. |\n\nReturns: `Timeout` Časovač Node.js alebo nič, keď sa `fn` spustila okamžite.\n\nZruší predchádzajúci časovač s rovnakým názvom a spustí nový, takže `fn` sa spustí raz, `timeout` ms po poslednom volaní (debounce). S `limit` sa `fn` po `limit` odloženiach spustí okamžite (bez `param`) a počítadlo sa vynuluje. `param` sa odovzdá do `fn`.\n\nExample: Uloženie raz po sérii zmien\n```js\nfunction changed() {\n\tsetTimeout2('save', save, 2000);\n}\n\nfunction save() {\n\tF.Fs.writeFile(PATH.databases('state.json'), JSON.stringify(MAIN.state), NOOP);\n}\n```\n\n### clearTimeout2(name)\n\nType: `method`\n\nZruší časovač vytvorený pomocou setTimeout2().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov použitý v `setTimeout2()`. |\n\nReturns: `Boolean` `true`, ak bol časovač zrušený.\n\nVráti `true`, ak bol zrušený čakajúci časovač s týmto názvom.\n\nExample: Zrušenie\n```js\nsetTimeout2('save', save, 5000);\nclearTimeout2('save');\n```\n\n### PAUSESERVER(name, [enable])\n\nType: `method`\n\nPozastaví server: každá požiadavka dostane 503, kým je nejaký názov pozastavený.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pozastavenia. |\n| `enable` | `Boolean` | no |  | `true` pozastaví, `false` obnoví. Keď sa vynechá, stav sa prepne. |\n\nReturns: `Boolean` `true`, ak je `name` teraz pozastavený.\n\nKaždý `name` je jeden dôvod na pozastavenie. Kým je pozastavený aspoň jeden názov, na HTTP požiadavky sa odpovedá `503` a upgrady na WebSocket sa odmietajú. S `enable` sa stav nastaví; bez neho sa stav `name` prepne. `F.wait()` je tá istá funkcia.\n\nExample: Pozastavenie počas migrácie\n```js\nPAUSESERVER('migration', true);\nmigrate(function() {\n\tPAUSESERVER('migration', false);\n});\n```\n\n### default_interval_clear_cache : 10\n\nType: `config`\n\nMinúty medzi čisteniami dočasných súborov a cache view.\n\nReturns: `Number`\n\nPočíta sa v tickoch služby (jeden za minútu). Každé čistenie vyvolá `clear` s typom `'temporary'`.\n\n### default_interval_clear_resources : 20\n\nType: `config`\n\nMinúty medzi čisteniami načítaných zdrojov.\n\nReturns: `Number`\n\nPočíta sa v tickoch služby. Každé čistenie vyvolá `clear` s typom `'resources'`.\n\n### default_interval_clear_dnscache : 30\n\nType: `config`\n\nMinúty medzi čisteniami DNS cache.\n\nReturns: `Number`\n\nPočíta sa v tickoch služby. Každé čistenie vyvolá `clear` s typom `'dns'`.\n\n### ON('init', function())\n\nType: `event`\n\nKonfigurácia je načítaná; súbory aplikácie ešte nie sú načítané.\n\nVyvolá sa raz pri štarte, pred načítaním definícií, modelov, kontrolérov a ostatných súborov. Ak zavoláš `ON('init')` po načítaní aplikácie, funkcia sa spustí okamžite.\n\nExample: Počúvanie\n```js\nON('init', function() {\n\tconsole.log('Config ready, port', CONF.port);\n});\n```\n\n### ON('load', function())\n\nType: `event`\n\nVšetky súbory aplikácie sú načítané.\n\nVyvolá sa raz, tesne pred `ready`. Ak je aplikácia už načítaná, funkcia sa spustí okamžite.\n\nExample: Počúvanie\n```js\nON('load', function() {\n\tconsole.log('Loaded');\n});\n```\n\n### ON('ready', function())\n\nType: `event`\n\nAplikácia je pripravená.\n\nVyvolá sa raz po `load`, keď sú načítané všetky súbory. Obvyklé miesto pre kód pri štarte. Ak je aplikácia už načítaná, funkcia sa spustí okamžite.\n\nExample: Počúvanie\n```js\nON('ready', function() {\n\tMAIN.started = NOW;\n});\n```\n\n### ON('service', function(counter))\n\nType: `event`\n\nVyvoláva ju služba frameworku každú minútu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `counter` | `Number` | yes |  | Počet spustení služby. |\n\n`counter` je počet spustení od štartu aplikácie (1, 2, 3...). Pomocou zvyšku po delení spúšťaj kód každých pár minút. Vo workeri pridanie tohto listenera spustí časovač.\n\nExample: Počúvanie\n```js\nON('service', function(counter) {\n\tif (counter % 10 === 0)\n\t\tconsole.log('Ten more minutes');\n});\n```\n\n### ON('exit', function(signal))\n\nType: `event`\n\nAplikácia sa zastavuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `signal` | `Number|String` | yes |  | Signál; `15` (SIGTERM), keď žiadny nebol zadaný. |\n\nVyvolá sa raz, keď sa framework zastavuje, potom ako poslal signál svojim workerom a vláknam. Prácu drž synchrónnu; proces sa čoskoro ukončí.\n\nExample: Počúvanie\n```js\nON('exit', function(signal) {\n\tconsole.log('Stopping with signal', signal);\n});\n```\n\n### ON('request', function(req, res))\n\nType: `event`\n\nPrišla požiadavka, pred routovaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `res` | `Response` | yes |  | Odpoveď. |\n\nVyvolá sa pre každú HTTP požiadavku po kontrole proxy a pred presmerovaniami a routovaním.\n\nExample: Počúvanie\n```js\nON('request', function(req, res) {\n\tconsole.log(req.method, req.url);\n});\n```\n\n### ON('request_begin', function(req, res))\n\nType: `event`\n\nPožiadavka je pripravená na routovanie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `res` | `Response` | yes |  | Odpoveď. |\n\nVyvolá sa po spracovaní požiadavky (hlavičky, flag XHR), pred vyhľadaním routy.\n\nExample: Počúvanie\n```js\nON('request_begin', function(req) {\n\treq.started = Date.now();\n});\n```\n\n### ON('request_end', function(req, res))\n\nType: `event`\n\nOdpoveď na požiadavku sa dokončila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `res` | `Response` | yes |  | Odpoveď. |\n\nVyvolá sa, keď framework dokončí odosielanie odpovede.\n\nExample: Počúvanie\n```js\nON('request_end', function(req, res) {\n\tconsole.log(req.url, Date.now() - req.started, 'ms');\n});\n```\n\n### ON('controller', function(controller, name, options))\n\nType: `event`\n\nAkcia routy sa má spustiť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Kontrolér požiadavky. |\n| `name` | `String` | yes |  | Názov kontroléra. |\n| `options` | `Object` | yes |  | Vlastné voľby routy. |\n\nVyvolá sa pred spustením akcie routy. Zavolaj `controller.cancel()`, aby si akciu tu zastavil. `name` je názov súboru kontroléra, ktorý routu deklaroval.\n\nExample: Počúvanie\n```js\nON('controller', function(controller, name) {\n\tcontroller.repository.section = name;\n});\n```\n\n### ON('@name', function(controller, name, options))\n\nType: `event`\n\nAkcia routy jedného kontroléra sa má spustiť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Kontrolér požiadavky. |\n| `name` | `String` | yes |  | Názov kontroléra. |\n| `options` | `Object` | yes |  | Vlastné voľby routy. |\n\nAko `controller`, ale iba pre routy deklarované v súbore kontroléra `name`: `ON('@admin')` sa spustí pre routy v `controllers/admin.js`.\n\nExample: Počúvanie\n```js\nON('@admin', function(controller) {\n\tcontroller.layout('layout_admin');\n});\n```\n\n### ON('errornnn', function(req, res, exception))\n\nType: `event`\n\nOdosiela sa chybová odpoveď, napríklad error404.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `res` | `Response` | yes |  | Odpoveď. |\n| `exception` | `Error` | yes |  | Problém, ak nejaký je. |\n\nNázov je `error` plus HTTP stav: `error400`, `error401`, `error404`, `error500`... Vyvolá sa, keď framework odpovedá daným stavom.\n\nExample: Počúvanie\n```js\nON('error404', function(req) {\n\tconsole.log('Not found:', req.url);\n});\n```\n\n### ON('error', function(obj))\n\nType: `event`\n\nFramework zalogoval chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | `{ error, name, url, date }`. |\n\nVyvoláva ju predvolený handler `DEF.onError` pre každú chybu, ktorú zaznamená. Posledných päť chýb sa uchováva aj v `F.errors`.\n\nExample: Počúvanie\n```js\nON('error', function(obj) {\n\tconsole.log(obj.name, obj.error);\n});\n```\n\n### ON('route', function(type, route))\n\nType: `event`\n\nBola zaregistrovaná routa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `web`, `websocket` alebo `file`. |\n| `route` | `Object` | yes |  | Interný objekt routy. |\n\n`type` je `'web'` pre routy `ROUTE()`, `'websocket'` pre WebSocket routy a `'file'` pre súborové routy.\n\nExample: Počúvanie\n```js\nON('route', function(type) {\n\tconsole.log('A new route of type', type);\n});\n```\n\n### ON('install', function(type, name, module))\n\nType: `event`\n\nBol nainštalovaný súbor aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Napríklad `'controller'` alebo `'model'`. |\n| `name` | `String` | yes |  | Názov súboru. |\n| `module` | `Object` | yes |  | Exporty súboru. |\n\nVyvolá sa potom, ako framework nainštaluje kontrolér, model, definíciu, plugin, modul, zdrojový súbor a ďalšie typy. `module` je to, čo súbor exportuje.\n\nExample: Počúvanie\n```js\nON('install', function(type, name) {\n\tconsole.log('Installed', type, name);\n});\n```\n\n### ON('configure', function(CONF))\n\nType: `event`\n\nKonfigurácia bola načítaná.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `CONF` | `Object` | yes |  | Konfigurácia. |\n\nVyvolá sa vždy, keď sa čítajú konfiguračné súbory, pri štarte aj pri opätovnom načítaní.\n\nExample: Počúvanie\n```js\nON('configure', function(conf) {\n\tconsole.log('Name:', conf.name);\n});\n```\n\n### ON('update', function(err))\n\nType: `event`\n\nUPDATE() sa dokončil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `ErrorBuilder` | yes |  | Chyby alebo `null`. |\n\nVyvolá sa po spustení aktualizačných skriptov `UPDATE()`, s chybami, ak nejaké sú.\n\nExample: Počúvanie\n```js\nON('update', function(err) {\n\terr && console.log('Update failed', err);\n});\n```\n\n### ON('clear', function(type, [value]))\n\nType: `event`\n\nInterná cache bola vyčistená.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | `temporary`, `resources` alebo `dns`. |\n| `value` | `Object` | no |  | Dočasné úložisko, iba pre `temporary`. |\n\n`type` je `'temporary'` (s dočasným úložiskom ako `value`), `'resources'` alebo `'dns'`. Služba ich čistí podľa nastavení `default_interval_clear_*`.\n\nExample: Počúvanie\n```js\nON('clear', function(type) {\n\tconsole.log('Cleared', type);\n});\n```\n\n### ON('cache_set', function(key, value, expire, sync))\n\nType: `event`\n\nHodnota bola uložená pomocou CACHE.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `Object` | yes |  | Hodnota. |\n| `expire` | `Date` | yes |  | Expirácia. |\n| `sync` | `Boolean` | yes |  | Interný flag pre synchronizované cache. |\n\nVyvoláva ju `CACHE.set()`.\n\nExample: Počúvanie\n```js\nON('cache_set', function(key) {\n\tconsole.log('Cached', key);\n});\n```\n\n### ON('cache_expired', function(key, value))\n\nType: `event`\n\nHodnota CACHE expirovala.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `Object` | yes |  | Expirovaná hodnota. |\n\nVyvolá sa, keď cache odstráni expirovanú položku (kontroluje sa každú minútu) alebo ju nájde pri čítaní.\n\nExample: Počúvanie\n```js\nON('cache_expired', function(key) {\n\tconsole.log('Expired', key);\n});\n```\n\n### ON('controller_render_meta', function(controller))\n\nType: `event`\n\nView sa chystá vypísať svoje meta tagy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `Controller` | yes |  | Kontrolér, ktorý vykresľuje view. |\n\nVyvolá sa, keď layout vykresľuje `@{meta}`, pred zostavením tagov. Na ich úpravu tu zmeň `controller.repository`.\n\nExample: Počúvanie\n```js\nON('controller_render_meta', function(controller) {\n\tif (!controller.repository.title)\n\t\tcontroller.repository.title = CONF.name;\n});\n```\n\n### ON('websocket', function(req, socket, head))\n\nType: `event`\n\nPrišla požiadavka na upgrade na WebSocket.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `req` | `Request` | yes |  | Požiadavka. |\n| `socket` | `Socket` | yes |  | Sieťový socket. |\n| `head` | `Buffer` | yes |  | Prvý paket upgradovaného streamu. |\n\nVyvolá sa po nájdení zodpovedajúcej WebSocket routy, pred prijatím spojenia.\n\nExample: Počúvanie\n```js\nON('websocket', function(req) {\n\tconsole.log('WebSocket from', req.ip);\n});\n```\n\n### ON('websocket_begin', function(controller, client))\n\nType: `event`\n\nWebSocket klient sa pripojil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | WebSocket kontrolér. |\n| `client` | `WebSocketClient` | yes |  | Klient. |\n\nVyvolá sa, keď sa klient pridá k svojmu WebSocket kontroléru, pred jeho udalosťou `open`.\n\nExample: Počúvanie\n```js\nON('websocket_begin', function(controller, client) {\n\tconsole.log('Online:', controller.online);\n});\n```\n\n### ON('websocket_end', function(controller, client))\n\nType: `event`\n\nWebSocket klient sa odpojil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `controller` | `WebSocket` | yes |  | WebSocket kontrolér. |\n| `client` | `WebSocketClient` | yes |  | Klient. |\n\nVyvolá sa, keď sa klient odstráni zo svojho WebSocket kontroléra.\n\nExample: Počúvanie\n```js\nON('websocket_end', function(controller, client) {\n\tconsole.log('Left:', client.id);\n});\n```\n\n### ON('componentator', function(meta))\n\nType: `event`\n\nCOMPONENTATOR() sa chystá stiahnuť komponenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | `{ name, components }`. |\n\n`meta` obsahuje `name` a `components` z volania `COMPONENTATOR()`.\n\nExample: Počúvanie\n```js\nON('componentator', function(meta) {\n\tconsole.log('Components', meta.name);\n});\n```\n\n### ON('mail', function(message))\n\nType: `event`\n\nOdosiela sa e-mailová správa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `MailMessage` | yes |  | Správa. |\n\nVyvolá sa pre každú správu, keď ju odosielateľ SMTP zapisuje.\n\nExample: Počúvanie\n```js\nON('mail', function(message) {\n\tconsole.log('Mail:', message.subject);\n});\n```\n\n### ON('message', function(msg, handle))\n\nType: `event`\n\nProces dostal IPC správu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa. |\n| `handle` | `Object` | yes |  | Handle odoslaný so správou, ak nejaký je. |\n\nVyvolá sa pre každú správu, ktorú proces dostane od svojho rodiča (`process.on('message')`), potom ako framework spracoval svoje vlastné.\n\nExample: Počúvanie\n```js\nON('message', function(msg) {\n\tif (msg.type === 'reload')\n\t\tconsole.log('Reload requested');\n});\n```\n\n### ON('watcher', function(app))\n\nType: `event`\n\nWatcher (znova) spustil aplikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `app` | `ChildProcess` | yes |  | Proces aplikácie alebo `null`. |\n\nVyvoláva sa v hlavnom procese režimu `debug` alebo `release` so sledovaním súborov, vždy keď spustí proces aplikácie.\n\nExample: Počúvanie\n```js\nON('watcher', function(app) {\n\tapp && console.log('App PID', app.pid);\n});\n```\n\n### ON('debug_start', function())\n\nType: `event`\n\nAplikácia sa spustila v režime debug.\n\nVyvolá sa v procese aplikácie, keď sa prvýkrát spustí v režime debug.\n\nExample: Počúvanie\n```js\nON('debug_start', function() {\n\tconsole.log('Debug start');\n});\n```\n\n### ON('debug_restart', function())\n\nType: `event`\n\nAplikácia sa reštartovala v režime debug.\n\nVyvolá sa namiesto `debug_start`, keď debug watcher po zmene reštartuje aplikáciu.\n\nExample: Počúvanie\n```js\nON('debug_restart', function() {\n\tconsole.log('Restarted after a change');\n});\n```\n\n### CLEANUP(stream, [callback])\n\nType: `method` · Since: `0.0.96`\n\nZničí stream po tom, čo skončil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Stream na čítanie alebo zápis. |\n| `callback` | `Function` | no |  | Zavolá sa po zničení streamu. |\n\nReturns: `Promise` Len keď nie je nastavený `callback`.\n\nPočká, kým stream skončí alebo zlyhá, zničí ho a zavolá `callback`. Bez callbacku vráti Promise.\n\nExample: Zatvorenie súboru po pipe\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('export.csv'));\nstream.pipe(F.Fs.createWriteStream(PATH.temp('export.csv')));\n\nCLEANUP(stream, function() {\n\tconsole.log('Done');\n});\n```\n\nExample: S await\n```js\nasync function copy(stream) {\n\tawait CLEANUP(stream);\n\tconsole.log('Closed');\n}\n```\n","entries":[{"type":"method","name":"SCHEDULE()","signature":"SCHEDULE(date, [repeat], fn)","since":"","deprecated":false},{"type":"property","name":"schedule.id","signature":"schedule.id","since":"","deprecated":false},{"type":"method","name":"schedule.remove()","signature":"schedule.remove()","since":"","deprecated":false},{"type":"method","name":"schedule.exec()","signature":"schedule.exec()","since":"","deprecated":false},{"type":"method","name":"ON()","signature":"ON(name, fn)","since":"","deprecated":false},{"type":"method","name":"ONCE()","signature":"ONCE(name, fn)","since":"","deprecated":false},{"type":"method","name":"OFF()","signature":"OFF([name], [fn])","since":"","deprecated":false},{"type":"method","name":"EMIT()","signature":"EMIT(name, [a], [b], [c], [d], [e], [f], [g])","since":"","deprecated":false},{"type":"method","name":"EMIT2()","signature":"EMIT2(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"setTimeout2()","signature":"setTimeout2(name, fn, timeout, [limit], [param])","since":"","deprecated":false},{"type":"method","name":"clearTimeout2()","signature":"clearTimeout2(name)","since":"","deprecated":false},{"type":"method","name":"PAUSESERVER()","signature":"PAUSESERVER(name, [enable])","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_cache","signature":"default_interval_clear_cache : 10","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_resources","signature":"default_interval_clear_resources : 20","since":"","deprecated":false},{"type":"config","name":"default_interval_clear_dnscache","signature":"default_interval_clear_dnscache : 30","since":"","deprecated":false},{"type":"event","name":"ON('init')","signature":"ON('init', function())","since":"","deprecated":false},{"type":"event","name":"ON('load')","signature":"ON('load', function())","since":"","deprecated":false},{"type":"event","name":"ON('ready')","signature":"ON('ready', function())","since":"","deprecated":false},{"type":"event","name":"ON('service')","signature":"ON('service', function(counter))","since":"","deprecated":false},{"type":"event","name":"ON('exit')","signature":"ON('exit', function(signal))","since":"","deprecated":false},{"type":"event","name":"ON('request')","signature":"ON('request', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_begin')","signature":"ON('request_begin', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('request_end')","signature":"ON('request_end', function(req, res))","since":"","deprecated":false},{"type":"event","name":"ON('controller')","signature":"ON('controller', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('@name')","signature":"ON('@name', function(controller, name, options))","since":"","deprecated":false},{"type":"event","name":"ON('errornnn')","signature":"ON('errornnn', function(req, res, exception))","since":"","deprecated":false},{"type":"event","name":"ON('error')","signature":"ON('error', function(obj))","since":"","deprecated":false},{"type":"event","name":"ON('route')","signature":"ON('route', function(type, route))","since":"","deprecated":false},{"type":"event","name":"ON('install')","signature":"ON('install', function(type, name, module))","since":"","deprecated":false},{"type":"event","name":"ON('configure')","signature":"ON('configure', function(CONF))","since":"","deprecated":false},{"type":"event","name":"ON('update')","signature":"ON('update', function(err))","since":"","deprecated":false},{"type":"event","name":"ON('clear')","signature":"ON('clear', function(type, [value]))","since":"","deprecated":false},{"type":"event","name":"ON('cache_set')","signature":"ON('cache_set', function(key, value, expire, sync))","since":"","deprecated":false},{"type":"event","name":"ON('cache_expired')","signature":"ON('cache_expired', function(key, value))","since":"","deprecated":false},{"type":"event","name":"ON('controller_render_meta')","signature":"ON('controller_render_meta', function(controller))","since":"","deprecated":false},{"type":"event","name":"ON('websocket')","signature":"ON('websocket', function(req, socket, head))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_begin')","signature":"ON('websocket_begin', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('websocket_end')","signature":"ON('websocket_end', function(controller, client))","since":"","deprecated":false},{"type":"event","name":"ON('componentator')","signature":"ON('componentator', function(meta))","since":"","deprecated":false},{"type":"event","name":"ON('mail')","signature":"ON('mail', function(message))","since":"","deprecated":false},{"type":"event","name":"ON('message')","signature":"ON('message', function(msg, handle))","since":"","deprecated":false},{"type":"event","name":"ON('watcher')","signature":"ON('watcher', function(app))","since":"","deprecated":false},{"type":"event","name":"ON('debug_start')","signature":"ON('debug_start', function())","since":"","deprecated":false},{"type":"event","name":"ON('debug_restart')","signature":"ON('debug_restart', function())","since":"","deprecated":false},{"type":"method","name":"CLEANUP()","signature":"CLEANUP(stream, [callback])","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZEF44S61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"File storage","summary":"FILESTORAGE(), its methods, the meta object and the controller methods that serve stored files.","markdown":"---\ntitle: File storage\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# File storage\n\n> FILESTORAGE(), its methods, the meta object and the controller methods that serve stored files.\n\n`FILESTORAGE(name)` returns a storage of binary files in `databases/fs-{name}/`. In this reference `fs` is a storage returned by `FILESTORAGE()` and `meta` the metadata of a file. The guide [File storage](../../guides/file-storage/) explains how to save, read and serve files with examples.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nReturns a file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the storage. |\n\nReturns: `FileStorage` The storage.\n\nReturns the storage `name`, stored in `databases/fs-{name}/`. The object is created on the first call and reused later. The folder is created when the first file is saved.\n\nExample: Get a storage\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nReturns the folder of a file storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the storage. |\n\nReturns: `String` The absolute path of the folder.\n\nReturns the path `databases/fs-{name}/` inside the folder set by `directory_databases`.\n\nExample: Folder\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nThe name of the storage.\n\nReturns: `String`\n\nThe name given to `FILESTORAGE()`.\n\nExample: Name\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nThe folder of the storage.\n\nReturns: `String`\n\nThe absolute path of the folder with the files. Change it with `fs.storage()`.\n\nExample: Folder\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nThe number of files.\n\nReturns: `Number`\n\nA counter kept in memory. It starts at `0`; `fs.count()` and `fs.rebuild()` set it, and every saved file adds one.\n\nExample: Load the counters\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nThe total size of the files in bytes.\n\nReturns: `Number`\n\nA counter kept in memory. It starts at `0`; `fs.count()` and `fs.rebuild()` set it, and every saved file adds its size.\n\nExample: Size in MB\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nSaves a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `name` | `String` | yes |  | The file name with its extension. |\n| `data` | `String|Buffer|Stream` | yes |  | A path, a buffer, a readable stream or a URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, runs when the file is saved. |\n| `custom` | `Object` | no |  | Any data kept with the file as `meta.custom`. |\n| `expire` | `String` | no |  | A period such as `'1 day'`; after it the file cannot be read. |\n| `headers` | `Object` | no |  | Headers for the request when `data` is a URL. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nStores `data` under `id`. The extension of `name` sets the content type; a path in `name` is reduced to the file name. `data` is a path to a file, a `Buffer`, a readable stream or an `http://`/`https://` URL, which is downloaded first. For GIF, PNG, JPEG and SVG images the metadata also gets `width` and `height`. An existing file with the same ID is overwritten. Without a callback the method returns a promise. Alias: `fs.insert()`.\n\nExample: Save a buffer\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Download from a URL\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias of fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `name` | `String` | yes |  | The file name with its extension. |\n| `data` | `String|Buffer|Stream` | yes |  | A path, a buffer, a readable stream or a URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Any data kept with the file. |\n| `expire` | `String` | no |  | An expiration period. |\n| `headers` | `Object` | no |  | Headers for a URL request. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nThe same method as `fs.save()`.\n\nExample: Insert\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nSaves an object as JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `value` | `Object` | yes |  | The value to store. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Any data kept with the file. |\n| `expire` | `String` | no |  | An expiration period. |\n\nReturns: `FileStorage|Promise` The storage, or a promise without a callback.\n\nSerializes `value` with `JSON.stringify()` and saves it as `{id}.json`.\n\nExample: Save settings\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nReads a file as a stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | Do not open a stream of the content. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nGives the meta object with `meta.stream`, a readable stream of the content. With `nostream` set to `true` the meta object comes without the stream. Errors: `File not found`, `Invalid file`, `File is expired` or an error of the file system. Without a callback the method returns a promise.\n\nExample: Pipe to a file\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nReads only the metadata of a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Keep the file descriptor `fd` open; you must close it. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nReads the header of the file. Dates come as `Date` objects. The callback also gets the path of the file on the disk. Unlike `fs.read()`, it does not check the expiration. Without a callback the method returns a promise.\n\nExample: Metadata\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nReads the content of a file into a Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the buffer.\n\nReads the whole file into memory. Use `fs.read()` for big files. Without a callback the method returns a promise. The promise gives only the buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nReads the content of a file as Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the string.\n\nReads the whole file and encodes it as a Base64 string. Without a callback the method returns a promise. The promise gives only the string.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nReads a JSON file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` The storage.\n\nReads a file saved by `fs.savejson()` and parses it. The callback is required.\n\nExample: Read settings\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nReads a stored picture as an Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the image.\n\nGives an `Image` object that reads the content of the file, so you can resize or convert it and save the result. Image processing needs GraphicsMagick or ImageMagick. Without a callback the method returns a promise. The promise gives only the image.\n\nExample: Thumbnail\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nSends a file to an HTTP response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | The response object. |\n| `options` | `Object` | yes |  | The options, see above. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; return `false` to answer with `404`. |\n\nReturns: `undefined`\n\nThe method behind `controller.filefs()` and `controller.imagefs()`. `options`: `id` (the file), `download` (`true` for the stored name, a string, or `function(name, type)` that returns the name), `headers`, `done` (a callback), `nocompress`, and for images `image: true`, `make` (`function(image, res)`) and `cache` (default `true`). It supports `If-Modified-Since` (`304`) and `Range` requests (`206`). A missing or expired file, or `checkmeta(meta)` that returns `false`, gives `404`.\n\nExample: In a route with req and res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nCopies the content of a file to the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `path` | `String` | yes |  | A target file, or a folder. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nWrites the content of the file (without the header) to `path`. A path with a dot is used as the file name; any other path is a folder and the file keeps its stored name. The folder must exist. Expired files give the error `File is expired`. Without a callback the method returns a promise.\n\nExample: Export to a folder\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: Export to a file\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nCopies a file inside the storage under a new ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `newid` | `String` | no | `UID()` | The ID of the copy. |\n| `callback` | `Function` | no |  | `function(err, meta)`; `meta.id` is the new ID. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nCreates a copy of the file with the same metadata under `newid` and adds it to `files.log`. When the second argument is the callback, a new ID is generated with `UID()`. Expired files give the error `File is expired`. Without a callback the method returns a promise. In the promise form pass `newid`.\n\nExample: Clone\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Clone as a promise\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nChanges the ID of a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `newid` | `String` | yes |  | The new ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise.\n\nMoves the file to the name and folder of `newid`. `files.log` is not changed; call `fs.rebuild()` when you list files with `fs.browse()`. Without a callback the method returns a promise.\n\nExample: Move\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nChanges the stored name of a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `newname` | `String` | yes |  | The new file name (at most 250 characters). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nWrites the new name into the header and into `files.log`. The content type stays the same. Without a callback the method returns a promise.\n\nExample: Rename\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nRemoves a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise.\n\nDeletes the file from the disk and from `files.log`. Without a callback the method returns a promise.\n\nExample: Remove\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nLists files from files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nReturns a NoSQL query builder over `files.log`, the database with the metadata of all files. Add conditions, sorting and paging, then `callback()`.\n\nExample: Latest images\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nLists files from the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the array.\n\nReads the header of every file on the disk and returns their meta objects. Slower than `fs.browse()`, but it does not depend on `files.log`. Without a callback the method returns a promise.\n\nExample: All files\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nGoes through all files on the disk one by one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | Runs when all files are processed. |\n| `workers` | `Number` | no |  | How many files are processed at the same time. |\n\nReturns: `FileStorage` The storage.\n\nCalls `onfile(meta, next)` for every file; call `next()` to continue. `meta.index` is the order of the file. `callback` runs at the end.\n\nExample: Find big files\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nCounts files and their size from files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` The storage.\n\nGives an object with `count` (the number of files) and `size` (the total size in bytes), and updates `fs.total` and `fs.size`.\n\nExample: Count\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nCounts files on the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the number.\n\nCounts the files in the subfolders of the storage, without `files.log`. Without a callback the method returns a promise.\n\nExample: Count on disk\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nCreates files.log again from the files on the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Runs when the log is written. |\n\nReturns: `FileStorage|Promise` The storage, or a promise.\n\nReads all files with `fs.browse2()`, writes a new `files.log` and sets `fs.total` and `fs.size`. Use it after `fs.move()` or when `files.log` was lost. Without a callback the method returns a promise.\n\nExample: Rebuild\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nRemoves expired files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` is the number of removed files. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the number.\n\nFinds files whose `expire` date has passed in `files.log` and deletes them. Without a callback the method returns a promise.\n\nExample: Clean every day\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nRemoves all files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` is the number of removed files. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the number.\n\nDeletes all files, their subfolders and `files.log`. While it runs, other reads and saves wait. Without a callback the method returns a promise. Alias: `fs.drop()`.\n\nExample: Clear\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias of fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the number.\n\nThe same method as `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nWrites all files into one backup file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The target file or a writable stream. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` has `filename`, `files` and `size`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the response.\n\nEach file is compressed with GZIP and written as Base64. `filename` is a path or a writable stream. Without a callback the method returns a promise.\n\nExample: Backup\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestores the storage from a backup file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The backup file. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise.\n\nRemoves all current files first (like `fs.clear()`), then unpacks the backup made by `fs.backup()`. Reads and saves wait until it ends. Without a callback the method returns a promise.\n\nExample: Restore\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nChanges the folder of the storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | The absolute path of the folder. |\n\nReturns: `FileStorage` The storage.\n\nSets `fs.directory` and the path of `files.log` to another folder.\n\nExample: Another disk\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nReturns the path of a file on the disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the file. |\n\nReturns: `String` The absolute path.\n\nReturns the path of the `.file` for `id`. The file starts with a header of 2000 bytes, so it is not a copy of the original file; use `fs.copy()` for that.\n\nExample: Path\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nAnswers with a file from a storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the storage. |\n| `id` | `String` | yes |  | The ID of the file. |\n| `download` | `Boolean|String|Function` | no |  | `true`, a file name, or `function(name, type)` that returns the name. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs when the file is sent. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; return `false` to answer with `404`. |\n\nReturns: `Controller` The controller.\n\nSends the file `id` of `FILESTORAGE(name)` with its stored content type. `download` set to `true` uses the stored name, a string sets another name. `checkmeta(meta)` that returns `false` gives `404`. `Range` and `If-Modified-Since` requests are supported. The response object has the same method, `res.filefs()`.\n\nExample: Download\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nAnswers with a processed image from a storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the storage. |\n| `id` | `String` | yes |  | The ID of the file. |\n| `make` | `Function` | yes |  | `function(image, res)` that changes the image. |\n| `headers` | `Object` | no |  | Extra response headers. |\n| `callback` | `Function` | no |  | Runs when the image is sent. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; return `false` to answer with `404`. |\n\nReturns: `Controller` The controller.\n\nReads the picture `id` of `FILESTORAGE(name)`, calls `make(image, res)` to process it and sends the result. The processed image is cached in the temporary folder per URL. Needs GraphicsMagick or ImageMagick. The response object has the same method, `res.imagefs()`.\n\nExample: Thumbnail\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nSaves an uploaded file into a storage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | The name of the storage. |\n| `id` | `String` | yes |  | The ID of the file. |\n| `custom` | `Object` | no |  | Any data kept with the file. |\n| `expire` | `String` | no |  | An expiration period. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` The storage, or a promise with the meta object.\n\nA method of every file in `controller.files`. It calls `FILESTORAGE(storage).save()` with the original file name and the temporary file of the upload. Without a callback it returns a promise.\n\nExample: Upload\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZEF44S61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Dateispeicher","summary":"FILESTORAGE(), seine Methoden, das Meta-Objekt und die Controller-Methoden, die gespeicherte Dateien ausliefern.","markdown":"---\ntitle: Dateispeicher\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Dateispeicher\n\n> FILESTORAGE(), seine Methoden, das Meta-Objekt und die Controller-Methoden, die gespeicherte Dateien ausliefern.\n\n`FILESTORAGE(name)` gibt einen Speicher für Binärdateien in `databases/fs-{name}/` zurück. In dieser Referenz ist `fs` ein von `FILESTORAGE()` zurückgegebener Speicher und `meta` die Metadaten einer Datei. Der Leitfaden [Dateispeicher](../../guides/file-storage/) erklärt mit Beispielen, wie du Dateien speicherst, liest und auslieferst.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nGibt einen Dateispeicher zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Speichers. |\n\nReturns: `FileStorage` Der Speicher.\n\nGibt den Speicher `name` zurück, abgelegt in `databases/fs-{name}/`. Das Objekt wird beim ersten Aufruf erstellt und danach wiederverwendet. Der Ordner wird erstellt, wenn die erste Datei gespeichert wird.\n\nExample: Einen Speicher holen\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nGibt den Ordner eines Dateispeichers zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Speichers. |\n\nReturns: `String` Der absolute Pfad des Ordners.\n\nGibt den Pfad `databases/fs-{name}/` innerhalb des Ordners zurück, den `directory_databases` festlegt.\n\nExample: Ordner\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nDer Name des Speichers.\n\nReturns: `String`\n\nDer an `FILESTORAGE()` übergebene Name.\n\nExample: Name\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nDer Ordner des Speichers.\n\nReturns: `String`\n\nDer absolute Pfad des Ordners mit den Dateien. Ändere ihn mit `fs.storage()`.\n\nExample: Ordner\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nDie Anzahl der Dateien.\n\nReturns: `Number`\n\nEin Zähler im Speicher. Er beginnt bei `0`; `fs.count()` und `fs.rebuild()` setzen ihn, und jede gespeicherte Datei erhöht ihn um eins.\n\nExample: Die Zähler laden\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nDie Gesamtgröße der Dateien in Bytes.\n\nReturns: `Number`\n\nEin Zähler im Speicher. Er beginnt bei `0`; `fs.count()` und `fs.rebuild()` setzen ihn, und jede gespeicherte Datei erhöht ihn um ihre Größe.\n\nExample: Größe in MB\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nSpeichert eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `name` | `String` | yes |  | Der Dateiname mit Endung. |\n| `data` | `String|Buffer|Stream` | yes |  | Ein Pfad, ein Buffer, ein lesbarer Stream oder eine URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, läuft, wenn die Datei gespeichert ist. |\n| `custom` | `Object` | no |  | Beliebige Daten, die mit der Datei als `meta.custom` aufbewahrt werden. |\n| `expire` | `String` | no |  | Ein Zeitraum wie `'1 day'`; danach kann die Datei nicht mehr gelesen werden. |\n| `headers` | `Object` | no |  | Header für die Anfrage, wenn `data` eine URL ist. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nSpeichert `data` unter `id`. Die Endung von `name` bestimmt den Content-Type; ein Pfad in `name` wird auf den Dateinamen gekürzt. `data` ist ein Pfad zu einer Datei, ein `Buffer`, ein lesbarer Stream oder eine `http://`/`https://`-URL, die zuerst heruntergeladen wird. Bei GIF-, PNG-, JPEG- und SVG-Bildern erhalten die Metadaten zusätzlich `width` und `height`. Eine vorhandene Datei mit derselben ID wird überschrieben. Ohne Callback gibt die Methode ein Promise zurück. Alias: `fs.insert()`.\n\nExample: Einen Buffer speichern\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Von einer URL herunterladen\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias von fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `name` | `String` | yes |  | Der Dateiname mit Endung. |\n| `data` | `String|Buffer|Stream` | yes |  | Ein Pfad, ein Buffer, ein lesbarer Stream oder eine URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Beliebige Daten, die mit der Datei aufbewahrt werden. |\n| `expire` | `String` | no |  | Ein Ablaufzeitraum. |\n| `headers` | `Object` | no |  | Header für eine URL-Anfrage. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nDieselbe Methode wie `fs.save()`.\n\nExample: Einfügen\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nSpeichert ein Objekt als JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `value` | `Object` | yes |  | Der zu speichernde Wert. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Beliebige Daten, die mit der Datei aufbewahrt werden. |\n| `expire` | `String` | no |  | Ein Ablaufzeitraum. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ohne Callback ein Promise.\n\nSerialisiert `value` mit `JSON.stringify()` und speichert es als `{id}.json`.\n\nExample: Einstellungen speichern\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nLiest eine Datei als Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | Keinen Stream für den Inhalt öffnen. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nLiefert das Meta-Objekt mit `meta.stream`, einem lesbaren Stream des Inhalts. Ist `nostream` auf `true` gesetzt, kommt das Meta-Objekt ohne Stream. Fehler: `File not found`, `Invalid file`, `File is expired` oder ein Fehler des Dateisystems. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: In eine Datei pipen\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nLiest nur die Metadaten einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Den Dateideskriptor `fd` offen halten; du musst ihn selbst schließen. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nLiest den Header der Datei. Datumswerte kommen als `Date`-Objekte. Der Callback erhält außerdem den Pfad der Datei auf der Festplatte. Anders als `fs.read()` prüft die Methode das Ablaufdatum nicht. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Metadaten\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLiest den Inhalt einer Datei in einen Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Buffer.\n\nLiest die ganze Datei in den Arbeitsspeicher. Nutze `fs.read()` für große Dateien. Ohne Callback gibt die Methode ein Promise zurück. Das Promise liefert nur den Buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLiest den Inhalt einer Datei als Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem String.\n\nLiest die ganze Datei und kodiert sie als Base64-String. Ohne Callback gibt die Methode ein Promise zurück. Das Promise liefert nur den String.\n\nExample: Data-URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nLiest eine JSON-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` Der Speicher.\n\nLiest eine mit `fs.savejson()` gespeicherte Datei und parst sie. Der Callback ist Pflicht.\n\nExample: Einstellungen lesen\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLiest ein gespeichertes Bild als Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Bild.\n\nLiefert ein `Image`-Objekt, das den Inhalt der Datei liest, sodass du es skalieren oder konvertieren und das Ergebnis speichern kannst. Die Bildverarbeitung braucht GraphicsMagick oder ImageMagick. Ohne Callback gibt die Methode ein Promise zurück. Das Promise liefert nur das Bild.\n\nExample: Vorschaubild\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nSendet eine Datei an eine HTTP-Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | Das Response-Objekt. |\n| `options` | `Object` | yes |  | Die Optionen, siehe oben. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; gib `false` zurück, um mit `404` zu antworten. |\n\nReturns: `undefined`\n\nDie Methode hinter `controller.filefs()` und `controller.imagefs()`. `options`: `id` (die Datei), `download` (`true` für den gespeicherten Namen, ein String oder `function(name, type)`, die den Namen zurückgibt), `headers`, `done` (ein Callback), `nocompress` und für Bilder `image: true`, `make` (`function(image, res)`) und `cache` (Standard `true`). Sie unterstützt `If-Modified-Since`- (`304`) und `Range`-Anfragen (`206`). Eine fehlende oder abgelaufene Datei oder ein `checkmeta(meta)`, das `false` zurückgibt, ergibt `404`.\n\nExample: In einer Route mit req und res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nKopiert den Inhalt einer Datei auf die Festplatte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `path` | `String` | yes |  | Eine Zieldatei oder ein Ordner. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nSchreibt den Inhalt der Datei (ohne den Header) nach `path`. Ein Pfad mit einem Punkt wird als Dateiname verwendet; jeder andere Pfad ist ein Ordner, und die Datei behält ihren gespeicherten Namen. Der Ordner muss existieren. Abgelaufene Dateien ergeben den Fehler `File is expired`. Ohne Callback gibt die Methode eine Promise zurück.\n\nExample: In einen Ordner exportieren\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: In eine Datei exportieren\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nKopiert eine Datei innerhalb des Speichers unter eine neue ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `newid` | `String` | no | `UID()` | Die ID der Kopie. |\n| `callback` | `Function` | no |  | `function(err, meta)`; `meta.id` ist die neue ID. |\n\nReturns: `FileStorage|Promise` Den Speicher oder eine Promise mit dem Meta-Objekt.\n\nErstellt eine Kopie der Datei mit denselben Metadaten unter `newid` und fügt sie zu `files.log` hinzu. Ist das zweite Argument der Callback, wird mit `UID()` eine neue ID erzeugt. Abgelaufene Dateien ergeben den Fehler `File is expired`. Ohne Callback gibt die Methode eine Promise zurück. In der Promise-Form übergibst du `newid`.\n\nExample: Klonen\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Als Promise klonen\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nÄndert die ID einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `newid` | `String` | yes |  | Die neue ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise.\n\nVerschiebt die Datei zum Namen und Ordner von `newid`. `files.log` wird nicht geändert; rufe `fs.rebuild()` auf, wenn du Dateien mit `fs.browse()` auflistest. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Verschieben\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nÄndert den gespeicherten Namen einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `newname` | `String` | yes |  | Der neue Dateiname (höchstens 250 Zeichen). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nSchreibt den neuen Namen in den Header und in `files.log`. Der Content-Type bleibt gleich. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Umbenennen\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nEntfernt eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise.\n\nLöscht die Datei von der Festplatte und aus `files.log`. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Entfernen\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nListet Dateien aus files.log auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nGibt einen NoSQL-Query-Builder über `files.log` zurück, die Datenbank mit den Metadaten aller Dateien. Füge Bedingungen, Sortierung und Paginierung hinzu und rufe dann `callback()` auf.\n\nExample: Neueste Bilder\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nListet Dateien von der Festplatte auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Array.\n\nLiest den Header jeder Datei auf der Festplatte und gibt ihre Meta-Objekte zurück. Langsamer als `fs.browse()`, aber unabhängig von `files.log`. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Alle Dateien\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nGeht alle Dateien auf der Festplatte nacheinander durch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | Läuft, wenn alle Dateien verarbeitet sind. |\n| `workers` | `Number` | no |  | Wie viele Dateien gleichzeitig verarbeitet werden. |\n\nReturns: `FileStorage` Der Speicher.\n\nRuft `onfile(meta, next)` für jede Datei auf; rufe `next()` auf, um fortzufahren. `meta.index` ist die Position der Datei. `callback` läuft am Ende.\n\nExample: Große Dateien finden\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nZählt Dateien und ihre Größe aus files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` Der Speicher.\n\nLiefert ein Objekt mit `count` (der Anzahl der Dateien) und `size` (der Gesamtgröße in Bytes) und aktualisiert `fs.total` und `fs.size`.\n\nExample: Zählen\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nZählt die Dateien auf der Festplatte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit der Anzahl.\n\nZählt die Dateien in den Unterordnern des Speichers, ohne `files.log`. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Auf der Festplatte zählen\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nErstellt files.log neu aus den Dateien auf der Festplatte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Läuft, wenn das Log geschrieben ist. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise.\n\nLiest alle Dateien mit `fs.browse2()`, schreibt eine neue `files.log` und setzt `fs.total` und `fs.size`. Nutze die Methode nach `fs.move()` oder wenn `files.log` verloren gegangen ist. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Neu aufbauen\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nEntfernt abgelaufene Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` ist die Anzahl der entfernten Dateien. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit der Anzahl.\n\nSucht in `files.log` Dateien, deren `expire`-Datum vorbei ist, und löscht sie. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Jeden Tag aufräumen\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nEntfernt alle Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` ist die Anzahl der entfernten Dateien. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit der Anzahl.\n\nLöscht alle Dateien, ihre Unterordner und `files.log`. Während die Methode läuft, warten andere Lese- und Speichervorgänge. Ohne Callback gibt die Methode ein Promise zurück. Alias: `fs.drop()`.\n\nExample: Leeren\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias von fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit der Anzahl.\n\nDieselbe Methode wie `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nSchreibt alle Dateien in eine Sicherungsdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Die Zieldatei oder ein beschreibbarer Stream. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` enthält `filename`, `files` und `size`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit der Antwort.\n\nJede Datei wird mit GZIP komprimiert und als Base64 geschrieben. `filename` ist ein Pfad oder ein beschreibbarer Stream. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Sicherung\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nStellt den Speicher aus einer Sicherungsdatei wieder her.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die Sicherungsdatei. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise.\n\nEntfernt zuerst alle aktuellen Dateien (wie `fs.clear()`) und entpackt dann die mit `fs.backup()` erstellte Sicherung. Lese- und Speichervorgänge warten, bis die Methode fertig ist. Ohne Callback gibt die Methode ein Promise zurück.\n\nExample: Wiederherstellen\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nÄndert den Ordner des Speichers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | Der absolute Pfad des Ordners. |\n\nReturns: `FileStorage` Der Speicher.\n\nSetzt `fs.directory` und den Pfad von `files.log` auf einen anderen Ordner.\n\nExample: Eine andere Festplatte\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nGibt den Pfad einer Datei auf der Festplatte zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID der Datei. |\n\nReturns: `String` Der absolute Pfad.\n\nGibt den Pfad der `.file` für `id` zurück. Die Datei beginnt mit einem Header von 2000 Bytes, ist also keine Kopie der Originaldatei; nutze dafür `fs.copy()`.\n\nExample: Pfad\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nAntwortet mit einer Datei aus einem Speicher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Speichers. |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `download` | `Boolean|String|Function` | no |  | `true`, ein Dateiname oder `function(name, type)`, die den Namen zurückgibt. |\n| `headers` | `Object` | no |  | Zusätzliche Response-Header. |\n| `callback` | `Function` | no |  | Läuft, wenn die Datei gesendet ist. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; gib `false` zurück, um mit `404` zu antworten. |\n\nReturns: `Controller` Der Controller.\n\nSendet die Datei `id` aus `FILESTORAGE(name)` mit ihrem gespeicherten Content-Type. Ist `download` auf `true` gesetzt, wird der gespeicherte Name verwendet; ein String setzt einen anderen Namen. Ein `checkmeta(meta)`, das `false` zurückgibt, ergibt `404`. `Range`- und `If-Modified-Since`-Anfragen werden unterstützt. Das Response-Objekt hat dieselbe Methode, `res.filefs()`.\n\nExample: Download\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nAntwortet mit einem verarbeiteten Bild aus einem Speicher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Speichers. |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `make` | `Function` | yes |  | `function(image, res)`, die das Bild verändert. |\n| `headers` | `Object` | no |  | Zusätzliche Response-Header. |\n| `callback` | `Function` | no |  | Läuft, wenn das Bild gesendet ist. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; gib `false` zurück, um mit `404` zu antworten. |\n\nReturns: `Controller` Der Controller.\n\nLiest das Bild `id` aus `FILESTORAGE(name)`, ruft `make(image, res)` zur Verarbeitung auf und sendet das Ergebnis. Das verarbeitete Bild wird pro URL im temporären Ordner zwischengespeichert. Braucht GraphicsMagick oder ImageMagick. Das Response-Objekt hat dieselbe Methode, `res.imagefs()`.\n\nExample: Vorschaubild\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nSpeichert eine hochgeladene Datei in einem Speicher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Der Name des Speichers. |\n| `id` | `String` | yes |  | Die ID der Datei. |\n| `custom` | `Object` | no |  | Beliebige Daten, die mit der Datei aufbewahrt werden. |\n| `expire` | `String` | no |  | Ein Ablaufzeitraum. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Der Speicher oder ein Promise mit dem Meta-Objekt.\n\nEine Methode jeder Datei in `controller.files`. Sie ruft `FILESTORAGE(storage).save()` mit dem ursprünglichen Dateinamen und der temporären Datei des Uploads auf. Ohne Callback gibt sie ein Promise zurück.\n\nExample: Upload\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZEF44S61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Almacenamiento de archivos","summary":"FILESTORAGE(), sus métodos, el objeto meta y los métodos del controlador que sirven archivos guardados.","markdown":"---\ntitle: Almacenamiento de archivos\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Almacenamiento de archivos\n\n> FILESTORAGE(), sus métodos, el objeto meta y los métodos del controlador que sirven archivos guardados.\n\n`FILESTORAGE(name)` devuelve un almacenamiento de archivos binarios en `databases/fs-{name}/`. En esta referencia, `fs` es un almacenamiento devuelto por `FILESTORAGE()` y `meta` son los metadatos de un archivo. La guía [Almacenamiento de archivos](../../guides/file-storage/) explica con ejemplos cómo guardar, leer y servir archivos.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nDevuelve un almacenamiento de archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento. |\n\nReturns: `FileStorage` El almacenamiento.\n\nDevuelve el almacenamiento `name`, guardado en `databases/fs-{name}/`. El objeto se crea en la primera llamada y se reutiliza después. La carpeta se crea al guardar el primer archivo.\n\nExample: Obtener un almacenamiento\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nDevuelve la carpeta de un almacenamiento de archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento. |\n\nReturns: `String` La ruta absoluta de la carpeta.\n\nDevuelve la ruta `databases/fs-{name}/` dentro de la carpeta definida por `directory_databases`.\n\nExample: Carpeta\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nEl nombre del almacenamiento.\n\nReturns: `String`\n\nEl nombre pasado a `FILESTORAGE()`.\n\nExample: Nombre\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nLa carpeta del almacenamiento.\n\nReturns: `String`\n\nLa ruta absoluta de la carpeta con los archivos. Cámbiala con `fs.storage()`.\n\nExample: Carpeta\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nEl número de archivos.\n\nReturns: `Number`\n\nUn contador guardado en memoria. Empieza en `0`; `fs.count()` y `fs.rebuild()` lo establecen, y cada archivo guardado suma uno.\n\nExample: Cargar los contadores\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nEl tamaño total de los archivos en bytes.\n\nReturns: `Number`\n\nUn contador guardado en memoria. Empieza en `0`; `fs.count()` y `fs.rebuild()` lo establecen, y cada archivo guardado suma su tamaño.\n\nExample: Tamaño en MB\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nGuarda un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `name` | `String` | yes |  | El nombre del archivo con su extensión. |\n| `data` | `String|Buffer|Stream` | yes |  | Una ruta, un buffer, un stream de lectura o una URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, se ejecuta cuando el archivo está guardado. |\n| `custom` | `Object` | no |  | Cualquier dato guardado con el archivo como `meta.custom`. |\n| `expire` | `String` | no |  | Un periodo como `'1 day'`; pasado ese tiempo, el archivo no se puede leer. |\n| `headers` | `Object` | no |  | Cabeceras para la petición cuando `data` es una URL. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nGuarda `data` bajo `id`. La extensión de `name` define el tipo de contenido; una ruta en `name` se reduce al nombre del archivo. `data` es una ruta a un archivo, un `Buffer`, un stream de lectura o una URL `http://`/`https://`, que primero se descarga. Para imágenes GIF, PNG, JPEG y SVG, los metadatos también reciben `width` y `height`. Un archivo existente con el mismo ID se sobrescribe. Sin callback, el método devuelve una promesa. Alias: `fs.insert()`.\n\nExample: Guardar un buffer\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Descargar desde una URL\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias de fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `name` | `String` | yes |  | El nombre del archivo con su extensión. |\n| `data` | `String|Buffer|Stream` | yes |  | Una ruta, un buffer, un stream de lectura o una URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Cualquier dato guardado con el archivo. |\n| `expire` | `String` | no |  | Un periodo de expiración. |\n| `headers` | `Object` | no |  | Cabeceras para una petición a una URL. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nEl mismo método que `fs.save()`.\n\nExample: Insertar\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nGuarda un objeto como JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `value` | `Object` | yes |  | El valor que se guarda. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Cualquier dato guardado con el archivo. |\n| `expire` | `String` | no |  | Un periodo de expiración. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa si no hay callback.\n\nSerializa `value` con `JSON.stringify()` y lo guarda como `{id}.json`.\n\nExample: Guardar ajustes\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nLee un archivo como stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | No abrir un stream del contenido. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nDa el objeto meta con `meta.stream`, un stream de lectura del contenido. Con `nostream` en `true`, el objeto meta llega sin el stream. Errores: `File not found`, `Invalid file`, `File is expired` o un error del sistema de archivos. Sin callback, el método devuelve una promesa.\n\nExample: Volcar a un archivo\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nLee solo los metadatos de un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Mantener abierto el descriptor de archivo `fd`; tienes que cerrarlo tú. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nLee la cabecera del archivo. Las fechas llegan como objetos `Date`. El callback también recibe la ruta del archivo en el disco. A diferencia de `fs.read()`, no comprueba la expiración. Sin callback, el método devuelve una promesa.\n\nExample: Metadatos\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLee el contenido de un archivo en un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el buffer.\n\nLee el archivo entero en memoria. Usa `fs.read()` para archivos grandes. Sin callback, el método devuelve una promesa. La promesa da solo el buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLee el contenido de un archivo como Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con la cadena.\n\nLee el archivo entero y lo codifica como cadena Base64. Sin callback, el método devuelve una promesa. La promesa da solo la cadena.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nLee un archivo JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` El almacenamiento.\n\nLee un archivo guardado con `fs.savejson()` y lo parsea. El callback es obligatorio.\n\nExample: Leer ajustes\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLee una imagen guardada como Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con la imagen.\n\nDa un objeto `Image` que lee el contenido del archivo, para que puedas redimensionarlo o convertirlo y guardar el resultado. El procesamiento de imágenes necesita GraphicsMagick o ImageMagick. Sin callback, el método devuelve una promesa. La promesa da solo la imagen.\n\nExample: Miniatura\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nEnvía un archivo a una respuesta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | El objeto de respuesta. |\n| `options` | `Object` | yes |  | Las opciones, ver arriba. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; devuelve `false` para responder con `404`. |\n\nReturns: `undefined`\n\nEl método que hay detrás de `controller.filefs()` y `controller.imagefs()`. `options`: `id` (el archivo), `download` (`true` para el nombre guardado, una cadena, o `function(name, type)` que devuelve el nombre), `headers`, `done` (un callback), `nocompress` y, para imágenes, `image: true`, `make` (`function(image, res)`) y `cache` (por defecto `true`). Admite peticiones `If-Modified-Since` (`304`) y `Range` (`206`). Un archivo que falta o ha expirado, o un `checkmeta(meta)` que devuelve `false`, da `404`.\n\nExample: En una ruta con req y res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nCopia el contenido de un archivo al disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `path` | `String` | yes |  | Un archivo de destino o una carpeta. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nEscribe el contenido del archivo (sin la cabecera) en `path`. Una ruta con un punto se usa como nombre de archivo; cualquier otra ruta es una carpeta y el archivo conserva su nombre almacenado. La carpeta debe existir. Los archivos expirados dan el error `File is expired`. Sin callback, el método devuelve una promesa.\n\nExample: Exportar a una carpeta\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: Exportar a un archivo\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nCopia un archivo dentro del almacenamiento bajo un nuevo ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `newid` | `String` | no | `UID()` | El ID de la copia. |\n| `callback` | `Function` | no |  | `function(err, meta)`; `meta.id` es el nuevo ID. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nCrea una copia del archivo con los mismos metadatos bajo `newid` y la añade a `files.log`. Cuando el segundo argumento es el callback, se genera un nuevo ID con `UID()`. Los archivos expirados dan el error `File is expired`. Sin callback, el método devuelve una promesa. En la forma de promesa, pasa `newid`.\n\nExample: Clonar\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Clonar como promesa\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nCambia el ID de un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `newid` | `String` | yes |  | El nuevo ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa.\n\nMueve el archivo al nombre y la carpeta de `newid`. `files.log` no cambia; llama a `fs.rebuild()` cuando listes archivos con `fs.browse()`. Sin callback, el método devuelve una promesa.\n\nExample: Mover\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nCambia el nombre guardado de un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `newname` | `String` | yes |  | El nuevo nombre del archivo (como máximo 250 caracteres). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nEscribe el nuevo nombre en la cabecera y en `files.log`. El tipo de contenido no cambia. Sin callback, el método devuelve una promesa.\n\nExample: Renombrar\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nElimina un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa.\n\nBorra el archivo del disco y de `files.log`. Sin callback, el método devuelve una promesa.\n\nExample: Eliminar\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nLista archivos desde files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` El constructor de consultas.\n\nDevuelve un constructor de consultas NoSQL sobre `files.log`, la base de datos con los metadatos de todos los archivos. Añade condiciones, orden y paginación, y luego `callback()`.\n\nExample: Últimas imágenes\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nLista archivos desde el disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el array.\n\nLee la cabecera de cada archivo del disco y devuelve sus objetos meta. Es más lento que `fs.browse()`, pero no depende de `files.log`. Sin callback, el método devuelve una promesa.\n\nExample: Todos los archivos\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nRecorre uno a uno todos los archivos del disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | Se ejecuta cuando todos los archivos están procesados. |\n| `workers` | `Number` | no |  | Cuántos archivos se procesan a la vez. |\n\nReturns: `FileStorage` El almacenamiento.\n\nLlama a `onfile(meta, next)` para cada archivo; llama a `next()` para continuar. `meta.index` es el orden del archivo. `callback` se ejecuta al final.\n\nExample: Buscar archivos grandes\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nCuenta los archivos y su tamaño desde files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` El almacenamiento.\n\nDa un objeto con `count` (el número de archivos) y `size` (el tamaño total en bytes), y actualiza `fs.total` y `fs.size`.\n\nExample: Contar\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nCuenta los archivos del disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el número.\n\nCuenta los archivos de las subcarpetas del almacenamiento, sin `files.log`. Sin callback, el método devuelve una promesa.\n\nExample: Contar en el disco\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nVuelve a crear files.log a partir de los archivos del disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Se ejecuta cuando el log está escrito. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa.\n\nLee todos los archivos con `fs.browse2()`, escribe un nuevo `files.log` y establece `fs.total` y `fs.size`. Úsalo después de `fs.move()` o cuando se haya perdido `files.log`. Sin callback, el método devuelve una promesa.\n\nExample: Reconstruir\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nElimina los archivos expirados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` es el número de archivos eliminados. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el número.\n\nBusca en `files.log` los archivos cuya fecha `expire` ya ha pasado y los borra. Sin callback, el método devuelve una promesa.\n\nExample: Limpiar cada día\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nElimina todos los archivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` es el número de archivos eliminados. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el número.\n\nBorra todos los archivos, sus subcarpetas y `files.log`. Mientras se ejecuta, las demás lecturas y escrituras esperan. Sin callback, el método devuelve una promesa. Alias: `fs.drop()`.\n\nExample: Vaciar\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias de fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el número.\n\nEl mismo método que `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nEscribe todos los archivos en un único archivo de copia de seguridad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | El archivo de destino o un stream de escritura. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` tiene `filename`, `files` y `size`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con la respuesta.\n\nCada archivo se comprime con GZIP y se escribe en Base64. `filename` es una ruta o un stream de escritura. Sin callback, el método devuelve una promesa.\n\nExample: Copia de seguridad\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestaura el almacenamiento desde un archivo de copia de seguridad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo de copia de seguridad. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa.\n\nPrimero elimina todos los archivos actuales (como `fs.clear()`) y luego desempaqueta la copia de seguridad creada con `fs.backup()`. Las lecturas y escrituras esperan hasta que termina. Sin callback, el método devuelve una promesa.\n\nExample: Restaurar\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nCambia la carpeta del almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | La ruta absoluta de la carpeta. |\n\nReturns: `FileStorage` El almacenamiento.\n\nEstablece `fs.directory` y la ruta de `files.log` en otra carpeta.\n\nExample: Otro disco\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nDevuelve la ruta de un archivo en el disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del archivo. |\n\nReturns: `String` La ruta absoluta.\n\nDevuelve la ruta del `.file` de `id`. El archivo empieza con una cabecera de 2000 bytes, así que no es una copia del archivo original; para eso usa `fs.copy()`.\n\nExample: Ruta\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nResponde con un archivo de un almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento. |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `download` | `Boolean|String|Function` | no |  | `true`, un nombre de archivo, o `function(name, type)` que devuelve el nombre. |\n| `headers` | `Object` | no |  | Cabeceras de respuesta adicionales. |\n| `callback` | `Function` | no |  | Se ejecuta cuando el archivo se ha enviado. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; devuelve `false` para responder con `404`. |\n\nReturns: `Controller` El controlador.\n\nEnvía el archivo `id` de `FILESTORAGE(name)` con su tipo de contenido guardado. `download` en `true` usa el nombre guardado; una cadena define otro nombre. Un `checkmeta(meta)` que devuelve `false` da `404`. Se admiten peticiones `Range` e `If-Modified-Since`. El objeto de respuesta tiene el mismo método, `res.filefs()`.\n\nExample: Descarga\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nResponde con una imagen procesada de un almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del almacenamiento. |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `make` | `Function` | yes |  | `function(image, res)` que modifica la imagen. |\n| `headers` | `Object` | no |  | Cabeceras de respuesta adicionales. |\n| `callback` | `Function` | no |  | Se ejecuta cuando la imagen se ha enviado. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; devuelve `false` para responder con `404`. |\n\nReturns: `Controller` El controlador.\n\nLee la imagen `id` de `FILESTORAGE(name)`, llama a `make(image, res)` para procesarla y envía el resultado. La imagen procesada se guarda en caché en la carpeta temporal por URL. Necesita GraphicsMagick o ImageMagick. El objeto de respuesta tiene el mismo método, `res.imagefs()`.\n\nExample: Miniatura\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nGuarda un archivo subido en un almacenamiento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | El nombre del almacenamiento. |\n| `id` | `String` | yes |  | El ID del archivo. |\n| `custom` | `Object` | no |  | Cualquier dato guardado con el archivo. |\n| `expire` | `String` | no |  | Un periodo de expiración. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` El almacenamiento, o una promesa con el objeto meta.\n\nUn método de cada archivo de `controller.files`. Llama a `FILESTORAGE(storage).save()` con el nombre de archivo original y el archivo temporal de la subida. Sin callback, devuelve una promesa.\n\nExample: Subida\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZEF44S61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Stockage de fichiers","summary":"FILESTORAGE(), ses méthodes, l'objet meta et les méthodes de contrôleur qui servent les fichiers stockés.","markdown":"---\ntitle: Stockage de fichiers\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Stockage de fichiers\n\n> FILESTORAGE(), ses méthodes, l'objet meta et les méthodes de contrôleur qui servent les fichiers stockés.\n\n`FILESTORAGE(name)` renvoie un stockage de fichiers binaires dans `databases/fs-{name}/`. Dans cette référence, `fs` est un stockage renvoyé par `FILESTORAGE()` et `meta` les métadonnées d'un fichier. Le guide [Stockage de fichiers](../../guides/file-storage/) explique, avec des exemples, comment enregistrer, lire et servir des fichiers.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nRenvoie un stockage de fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage. |\n\nReturns: `FileStorage` Le stockage.\n\nRenvoie le stockage `name`, situé dans `databases/fs-{name}/`. L'objet est créé au premier appel puis réutilisé. Le dossier est créé lors de l'enregistrement du premier fichier.\n\nExample: Obtenir un stockage\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nRenvoie le dossier d'un stockage de fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage. |\n\nReturns: `String` Le chemin absolu du dossier.\n\nRenvoie le chemin `databases/fs-{name}/` dans le dossier défini par `directory_databases`.\n\nExample: Dossier\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nLe nom du stockage.\n\nReturns: `String`\n\nLe nom passé à `FILESTORAGE()`.\n\nExample: Nom\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nLe dossier du stockage.\n\nReturns: `String`\n\nLe chemin absolu du dossier contenant les fichiers. Modifie-le avec `fs.storage()`.\n\nExample: Dossier\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nLe nombre de fichiers.\n\nReturns: `Number`\n\nUn compteur conservé en mémoire. Il commence à `0` ; `fs.count()` et `fs.rebuild()` le définissent, et chaque fichier enregistré ajoute un.\n\nExample: Charger les compteurs\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nLa taille totale des fichiers en octets.\n\nReturns: `Number`\n\nUn compteur conservé en mémoire. Il commence à `0` ; `fs.count()` et `fs.rebuild()` le définissent, et chaque fichier enregistré ajoute sa taille.\n\nExample: Taille en Mo\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nEnregistre un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `name` | `String` | yes |  | Le nom du fichier avec son extension. |\n| `data` | `String|Buffer|Stream` | yes |  | Un chemin, un buffer, un flux lisible ou une URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, s'exécute quand le fichier est enregistré. |\n| `custom` | `Object` | no |  | N'importe quelles données conservées avec le fichier dans `meta.custom`. |\n| `expire` | `String` | no |  | Une durée telle que `'1 day'` ; passé ce délai, le fichier ne peut plus être lu. |\n| `headers` | `Object` | no |  | Les en-têtes de la requête quand `data` est une URL. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nStocke `data` sous `id`. L'extension de `name` détermine le type de contenu ; un chemin dans `name` est réduit au nom du fichier. `data` est un chemin vers un fichier, un `Buffer`, un flux lisible ou une URL `http://`/`https://`, qui est d'abord téléchargée. Pour les images GIF, PNG, JPEG et SVG, les métadonnées reçoivent aussi `width` et `height`. Un fichier existant avec le même ID est écrasé. Sans callback, la méthode renvoie une promesse. Alias : `fs.insert()`.\n\nExample: Enregistrer un buffer\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Télécharger depuis une URL\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias de fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `name` | `String` | yes |  | Le nom du fichier avec son extension. |\n| `data` | `String|Buffer|Stream` | yes |  | Un chemin, un buffer, un flux lisible ou une URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | N'importe quelles données conservées avec le fichier. |\n| `expire` | `String` | no |  | Une durée d'expiration. |\n| `headers` | `Object` | no |  | Les en-têtes d'une requête vers une URL. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nLa même méthode que `fs.save()`.\n\nExample: Insérer\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nEnregistre un objet en JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `value` | `Object` | yes |  | La valeur à stocker. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | N'importe quelles données conservées avec le fichier. |\n| `expire` | `String` | no |  | Une durée d'expiration. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse sans callback.\n\nSérialise `value` avec `JSON.stringify()` et l'enregistre sous `{id}.json`.\n\nExample: Enregistrer des paramètres\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nLit un fichier sous forme de flux.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | Ne pas ouvrir de flux du contenu. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nFournit l'objet meta avec `meta.stream`, un flux lisible du contenu. Avec `nostream` à `true`, l'objet meta arrive sans le flux. Erreurs : `File not found`, `Invalid file`, `File is expired` ou une erreur du système de fichiers. Sans callback, la méthode renvoie une promesse.\n\nExample: Rediriger vers un fichier\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nLit uniquement les métadonnées d'un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Garder le descripteur de fichier `fd` ouvert ; tu dois le fermer. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nLit l'en-tête du fichier. Les dates arrivent sous forme d'objets `Date`. Le callback reçoit aussi le chemin du fichier sur le disque. Contrairement à `fs.read()`, elle ne vérifie pas l'expiration. Sans callback, la méthode renvoie une promesse.\n\nExample: Métadonnées\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLit le contenu d'un fichier dans un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le buffer.\n\nLit tout le fichier en mémoire. Utilise `fs.read()` pour les gros fichiers. Sans callback, la méthode renvoie une promesse. La promesse ne fournit que le buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLit le contenu d'un fichier en Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec la chaîne.\n\nLit tout le fichier et l'encode en chaîne Base64. Sans callback, la méthode renvoie une promesse. La promesse ne fournit que la chaîne.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nLit un fichier JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` Le stockage.\n\nLit un fichier enregistré par `fs.savejson()` et l'analyse. Le callback est obligatoire.\n\nExample: Lire des paramètres\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLit une image stockée sous forme d'Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'image.\n\nFournit un objet `Image` qui lit le contenu du fichier, pour le redimensionner ou le convertir et enregistrer le résultat. Le traitement d'images nécessite GraphicsMagick ou ImageMagick. Sans callback, la méthode renvoie une promesse. La promesse ne fournit que l'image.\n\nExample: Miniature\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nEnvoie un fichier dans une réponse HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | L'objet réponse. |\n| `options` | `Object` | yes |  | Les options, voir ci-dessus. |\n| `checkmeta` | `Function` | no |  | `function(meta)` ; renvoie `false` pour répondre avec `404`. |\n\nReturns: `undefined`\n\nLa méthode derrière `controller.filefs()` et `controller.imagefs()`. `options` : `id` (le fichier), `download` (`true` pour le nom stocké, une chaîne, ou `function(name, type)` qui renvoie le nom), `headers`, `done` (un callback), `nocompress`, et pour les images `image: true`, `make` (`function(image, res)`) et `cache` (par défaut `true`). Elle prend en charge `If-Modified-Since` (`304`) et les requêtes `Range` (`206`). Un fichier manquant ou expiré, ou un `checkmeta(meta)` qui renvoie `false`, donne `404`.\n\nExample: Dans une route avec req et res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nCopie le contenu d'un fichier sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `path` | `String` | yes |  | Un fichier cible, ou un dossier. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nÉcrit le contenu du fichier (sans l'en-tête) dans `path`. Un chemin contenant un point est utilisé comme nom de fichier ; tout autre chemin est un dossier, et le fichier conserve son nom stocké. Le dossier doit exister. Les fichiers expirés donnent l'erreur `File is expired`. Sans callback, la méthode renvoie une promesse.\n\nExample: Exporter vers un dossier\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: Exporter vers un fichier\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nCopie un fichier à l'intérieur du stockage sous un nouvel ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `newid` | `String` | no | `UID()` | L'ID de la copie. |\n| `callback` | `Function` | no |  | `function(err, meta)` ; `meta.id` est le nouvel ID. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nCrée une copie du fichier avec les mêmes métadonnées sous `newid` et l'ajoute à `files.log`. Quand le deuxième argument est le callback, un nouvel ID est généré avec `UID()`. Les fichiers expirés donnent l'erreur `File is expired`. Sans callback, la méthode renvoie une promesse. Dans la forme avec promesse, passe `newid`.\n\nExample: Cloner\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Cloner avec une promesse\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nModifie l'ID d'un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `newid` | `String` | yes |  | Le nouvel ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse.\n\nDéplace le fichier vers le nom et le dossier de `newid`. `files.log` n'est pas modifié ; appelle `fs.rebuild()` si tu listes les fichiers avec `fs.browse()`. Sans callback, la méthode renvoie une promesse.\n\nExample: Déplacer\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nModifie le nom stocké d'un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `newname` | `String` | yes |  | Le nouveau nom de fichier (250 caractères au maximum). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nÉcrit le nouveau nom dans l'en-tête et dans `files.log`. Le type de contenu reste le même. Sans callback, la méthode renvoie une promesse.\n\nExample: Renommer\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nSupprime un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse.\n\nSupprime le fichier du disque et de `files.log`. Sans callback, la méthode renvoie une promesse.\n\nExample: Supprimer\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nListe les fichiers à partir de files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` Le constructeur de requêtes.\n\nRenvoie un constructeur de requêtes NoSQL sur `files.log`, la base de données des métadonnées de tous les fichiers. Ajoute des conditions, un tri et une pagination, puis `callback()`.\n\nExample: Dernières images\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nListe les fichiers à partir du disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le tableau.\n\nLit l'en-tête de chaque fichier sur le disque et renvoie leurs objets meta. Plus lent que `fs.browse()`, mais ne dépend pas de `files.log`. Sans callback, la méthode renvoie une promesse.\n\nExample: Tous les fichiers\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nParcourt tous les fichiers du disque un par un.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | S'exécute quand tous les fichiers sont traités. |\n| `workers` | `Number` | no |  | Le nombre de fichiers traités en même temps. |\n\nReturns: `FileStorage` Le stockage.\n\nAppelle `onfile(meta, next)` pour chaque fichier ; appelle `next()` pour continuer. `meta.index` est le rang du fichier. `callback` s'exécute à la fin.\n\nExample: Trouver les gros fichiers\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nCompte les fichiers et leur taille à partir de files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` Le stockage.\n\nFournit un objet avec `count` (le nombre de fichiers) et `size` (la taille totale en octets), et met à jour `fs.total` et `fs.size`.\n\nExample: Compter\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nCompte les fichiers sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le nombre.\n\nCompte les fichiers dans les sous-dossiers du stockage, sans `files.log`. Sans callback, la méthode renvoie une promesse.\n\nExample: Compter sur le disque\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nRecrée files.log à partir des fichiers sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | S'exécute quand le journal est écrit. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse.\n\nLit tous les fichiers avec `fs.browse2()`, écrit un nouveau `files.log` et définit `fs.total` et `fs.size`. Utilise-la après `fs.move()` ou quand `files.log` a été perdu. Sans callback, la méthode renvoie une promesse.\n\nExample: Reconstruire\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nSupprime les fichiers expirés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)` ; `count` est le nombre de fichiers supprimés. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le nombre.\n\nRecherche dans `files.log` les fichiers dont la date `expire` est dépassée et les supprime. Sans callback, la méthode renvoie une promesse.\n\nExample: Nettoyer chaque jour\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nSupprime tous les fichiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)` ; `count` est le nombre de fichiers supprimés. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le nombre.\n\nSupprime tous les fichiers, leurs sous-dossiers et `files.log`. Pendant l'exécution, les autres lectures et enregistrements attendent. Sans callback, la méthode renvoie une promesse. Alias : `fs.drop()`.\n\nExample: Vider\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias de fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec le nombre.\n\nLa même méthode que `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nÉcrit tous les fichiers dans un seul fichier de sauvegarde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Le fichier cible ou un flux inscriptible. |\n| `callback` | `Function` | no |  | `function(err, response)` ; `response` contient `filename`, `files` et `size`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec la réponse.\n\nChaque fichier est compressé avec GZIP et écrit en Base64. `filename` est un chemin ou un flux inscriptible. Sans callback, la méthode renvoie une promesse.\n\nExample: Sauvegarde\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRestaure le stockage à partir d'un fichier de sauvegarde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier de sauvegarde. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse.\n\nSupprime d'abord tous les fichiers actuels (comme `fs.clear()`), puis décompresse la sauvegarde créée par `fs.backup()`. Les lectures et enregistrements attendent jusqu'à la fin. Sans callback, la méthode renvoie une promesse.\n\nExample: Restaurer\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nModifie le dossier du stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | Le chemin absolu du dossier. |\n\nReturns: `FileStorage` Le stockage.\n\nFait pointer `fs.directory` et le chemin de `files.log` vers un autre dossier.\n\nExample: Un autre disque\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nRenvoie le chemin d'un fichier sur le disque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du fichier. |\n\nReturns: `String` Le chemin absolu.\n\nRenvoie le chemin du `.file` correspondant à `id`. Le fichier commence par un en-tête de 2000 octets : ce n'est donc pas une copie du fichier d'origine ; utilise `fs.copy()` pour cela.\n\nExample: Chemin\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nRépond avec un fichier d'un stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage. |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `download` | `Boolean|String|Function` | no |  | `true`, un nom de fichier, ou `function(name, type)` qui renvoie le nom. |\n| `headers` | `Object` | no |  | Des en-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute quand le fichier est envoyé. |\n| `checkmeta` | `Function` | no |  | `function(meta)` ; renvoie `false` pour répondre avec `404`. |\n\nReturns: `Controller` Le contrôleur.\n\nEnvoie le fichier `id` de `FILESTORAGE(name)` avec son type de contenu stocké. `download` à `true` utilise le nom stocké, une chaîne définit un autre nom. Un `checkmeta(meta)` qui renvoie `false` donne `404`. Les requêtes `Range` et `If-Modified-Since` sont prises en charge. L'objet réponse possède la même méthode, `res.filefs()`.\n\nExample: Téléchargement\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nRépond avec une image traitée d'un stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du stockage. |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `make` | `Function` | yes |  | `function(image, res)` qui modifie l'image. |\n| `headers` | `Object` | no |  | Des en-têtes de réponse supplémentaires. |\n| `callback` | `Function` | no |  | S'exécute quand l'image est envoyée. |\n| `checkmeta` | `Function` | no |  | `function(meta)` ; renvoie `false` pour répondre avec `404`. |\n\nReturns: `Controller` Le contrôleur.\n\nLit l'image `id` de `FILESTORAGE(name)`, appelle `make(image, res)` pour la traiter et envoie le résultat. L'image traitée est mise en cache dans le dossier temporaire, par URL. Nécessite GraphicsMagick ou ImageMagick. L'objet réponse possède la même méthode, `res.imagefs()`.\n\nExample: Miniature\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nEnregistre un fichier envoyé dans un stockage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Le nom du stockage. |\n| `id` | `String` | yes |  | L'ID du fichier. |\n| `custom` | `Object` | no |  | N'importe quelles données conservées avec le fichier. |\n| `expire` | `String` | no |  | Une durée d'expiration. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Le stockage, ou une promesse avec l'objet meta.\n\nUne méthode de chaque fichier de `controller.files`. Elle appelle `FILESTORAGE(storage).save()` avec le nom de fichier d'origine et le fichier temporaire de l'envoi. Sans callback, elle renvoie une promesse.\n\nExample: Envoi\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZEF44S61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Archivio di file","summary":"FILESTORAGE(), i suoi metodi, l'oggetto meta e i metodi del controller che servono i file memorizzati.","markdown":"---\ntitle: Archivio di file\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Archivio di file\n\n> FILESTORAGE(), i suoi metodi, l'oggetto meta e i metodi del controller che servono i file memorizzati.\n\n`FILESTORAGE(name)` restituisce un archivio di file binari in `databases/fs-{name}/`. In questa reference `fs` è un archivio restituito da `FILESTORAGE()` e `meta` i metadati di un file. La guida [Archivio di file](../../guides/file-storage/) spiega con esempi come salvare, leggere e servire file.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nRestituisce un archivio di file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'archivio. |\n\nReturns: `FileStorage` L'archivio.\n\nRestituisce l'archivio `name`, memorizzato in `databases/fs-{name}/`. L'oggetto viene creato alla prima chiamata e poi riutilizzato. La cartella viene creata quando si salva il primo file.\n\nExample: Ottenere un archivio\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nRestituisce la cartella di un archivio di file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'archivio. |\n\nReturns: `String` Il percorso assoluto della cartella.\n\nRestituisce il percorso `databases/fs-{name}/` dentro la cartella impostata da `directory_databases`.\n\nExample: Cartella\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nIl nome dell'archivio.\n\nReturns: `String`\n\nIl nome passato a `FILESTORAGE()`.\n\nExample: Nome\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nLa cartella dell'archivio.\n\nReturns: `String`\n\nIl percorso assoluto della cartella con i file. Modificalo con `fs.storage()`.\n\nExample: Cartella\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nIl numero di file.\n\nReturns: `Number`\n\nUn contatore tenuto in memoria. Parte da `0`; `fs.count()` e `fs.rebuild()` lo impostano, e ogni file salvato aggiunge uno.\n\nExample: Caricare i contatori\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nLa dimensione totale dei file in byte.\n\nReturns: `Number`\n\nUn contatore tenuto in memoria. Parte da `0`; `fs.count()` e `fs.rebuild()` lo impostano, e ogni file salvato aggiunge la sua dimensione.\n\nExample: Dimensione in MB\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nSalva un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `name` | `String` | yes |  | Il nome del file con la sua estensione. |\n| `data` | `String|Buffer|Stream` | yes |  | Un percorso, un buffer, uno stream leggibile o un URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, viene eseguita quando il file è salvato. |\n| `custom` | `Object` | no |  | Qualsiasi dato conservato con il file come `meta.custom`. |\n| `expire` | `String` | no |  | Un periodo come `'1 day'`; trascorso questo il file non può essere letto. |\n| `headers` | `Object` | no |  | Header per la richiesta quando `data` è un URL. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nMemorizza `data` sotto `id`. L'estensione di `name` determina il content type; un percorso in `name` viene ridotto al nome del file. `data` è un percorso di un file, un `Buffer`, uno stream leggibile o un URL `http://`/`https://`, che viene prima scaricato. Per le immagini GIF, PNG, JPEG e SVG i metadati ricevono anche `width` e `height`. Un file esistente con lo stesso ID viene sovrascritto. Senza callback il metodo restituisce una promise. Alias: `fs.insert()`.\n\nExample: Salvare un buffer\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Scaricare da un URL\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias di fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `name` | `String` | yes |  | Il nome del file con la sua estensione. |\n| `data` | `String|Buffer|Stream` | yes |  | Un percorso, un buffer, uno stream leggibile o un URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Qualsiasi dato conservato con il file. |\n| `expire` | `String` | no |  | Un periodo di scadenza. |\n| `headers` | `Object` | no |  | Header per una richiesta a un URL. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nLo stesso metodo di `fs.save()`.\n\nExample: Inserire\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nSalva un oggetto come JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `value` | `Object` | yes |  | Il valore da memorizzare. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Qualsiasi dato conservato con il file. |\n| `expire` | `String` | no |  | Un periodo di scadenza. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise senza callback.\n\nSerializza `value` con `JSON.stringify()` e lo salva come `{id}.json`.\n\nExample: Salvare le impostazioni\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nLegge un file come stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | Non aprire uno stream del contenuto. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nRestituisce l'oggetto meta con `meta.stream`, uno stream leggibile del contenuto. Con `nostream` impostato a `true` l'oggetto meta arriva senza lo stream. Errori: `File not found`, `Invalid file`, `File is expired` o un errore del file system. Senza callback il metodo restituisce una promise.\n\nExample: Inoltrare in un file\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nLegge solo i metadati di un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Tiene aperto il file descriptor `fd`; devi chiuderlo tu. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nLegge l'header del file. Le date arrivano come oggetti `Date`. La callback riceve anche il percorso del file sul disco. A differenza di `fs.read()`, non controlla la scadenza. Senza callback il metodo restituisce una promise.\n\nExample: Metadati\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nLegge il contenuto di un file in un Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con il buffer.\n\nLegge l'intero file in memoria. Usa `fs.read()` per i file grandi. Senza callback il metodo restituisce una promise. La promise restituisce solo il buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nLegge il contenuto di un file come Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con la stringa.\n\nLegge l'intero file e lo codifica come stringa Base64. Senza callback il metodo restituisce una promise. La promise restituisce solo la stringa.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nLegge un file JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` L'archivio.\n\nLegge un file salvato da `fs.savejson()` e lo analizza. La callback è obbligatoria.\n\nExample: Leggere le impostazioni\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nLegge un'immagine memorizzata come Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'immagine.\n\nRestituisce un oggetto `Image` che legge il contenuto del file, così puoi ridimensionarlo o convertirlo e salvare il risultato. L'elaborazione delle immagini richiede GraphicsMagick o ImageMagick. Senza callback il metodo restituisce una promise. La promise restituisce solo l'immagine.\n\nExample: Miniatura\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nInvia un file a una risposta HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | L'oggetto risposta. |\n| `options` | `Object` | yes |  | Le opzioni, vedi sopra. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; restituisci `false` per rispondere con `404`. |\n\nReturns: `undefined`\n\nIl metodo dietro `controller.filefs()` e `controller.imagefs()`. `options`: `id` (il file), `download` (`true` per il nome memorizzato, una stringa, oppure `function(name, type)` che restituisce il nome), `headers`, `done` (una callback), `nocompress`, e per le immagini `image: true`, `make` (`function(image, res)`) e `cache` (predefinito `true`). Supporta le richieste `If-Modified-Since` (`304`) e `Range` (`206`). Un file mancante o scaduto, oppure `checkmeta(meta)` che restituisce `false`, produce `404`.\n\nExample: In una route con req e res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nCopia il contenuto di un file sul disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `path` | `String` | yes |  | Un file di destinazione, o una cartella. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nScrive il contenuto del file (senza l'intestazione) in `path`. Un percorso con un punto viene usato come nome del file; qualsiasi altro percorso è una cartella e il file mantiene il nome con cui è stato salvato. La cartella deve esistere. I file scaduti danno l'errore `File is expired`. Senza callback il metodo restituisce una promise.\n\nExample: Esportare in una cartella\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: Esportare in un file\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nCopia un file all'interno dell'archiviazione con un nuovo ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `newid` | `String` | no | `UID()` | L'ID della copia. |\n| `callback` | `Function` | no |  | `function(err, meta)`; `meta.id` è il nuovo ID. |\n\nReturns: `FileStorage|Promise` L'archiviazione, o una promise con l'oggetto meta.\n\nCrea una copia del file con gli stessi metadati sotto `newid` e la aggiunge a `files.log`. Quando il secondo argomento è la callback, viene generato un nuovo ID con `UID()`. I file scaduti danno l'errore `File is expired`. Senza callback il metodo restituisce una promise. Nella forma con promise passa `newid`.\n\nExample: Clonare\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Clonare con una promise\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nCambia l'ID di un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `newid` | `String` | yes |  | Il nuovo ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise.\n\nSposta il file nel nome e nella cartella di `newid`. `files.log` non viene modificato; chiama `fs.rebuild()` quando elenchi i file con `fs.browse()`. Senza callback il metodo restituisce una promise.\n\nExample: Spostare\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nCambia il nome memorizzato di un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `newname` | `String` | yes |  | Il nuovo nome del file (al massimo 250 caratteri). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nScrive il nuovo nome nell'header e in `files.log`. Il content type resta lo stesso. Senza callback il metodo restituisce una promise.\n\nExample: Rinominare\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nRimuove un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise.\n\nElimina il file dal disco e da `files.log`. Senza callback il metodo restituisce una promise.\n\nExample: Rimuovere\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nElenca i file da files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nRestituisce un query builder NoSQL su `files.log`, il database con i metadati di tutti i file. Aggiungi condizioni, ordinamento e paginazione, poi `callback()`.\n\nExample: Immagini più recenti\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nElenca i file dal disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'array.\n\nLegge l'header di ogni file sul disco e restituisce i loro oggetti meta. Più lento di `fs.browse()`, ma non dipende da `files.log`. Senza callback il metodo restituisce una promise.\n\nExample: Tutti i file\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nScorre tutti i file sul disco uno per uno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | Viene eseguita quando tutti i file sono stati elaborati. |\n| `workers` | `Number` | no |  | Quanti file vengono elaborati contemporaneamente. |\n\nReturns: `FileStorage` L'archivio.\n\nChiama `onfile(meta, next)` per ogni file; chiama `next()` per continuare. `meta.index` è la posizione del file. `callback` viene eseguita alla fine.\n\nExample: Trovare i file grandi\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nConta i file e la loro dimensione da files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` L'archivio.\n\nRestituisce un oggetto con `count` (il numero di file) e `size` (la dimensione totale in byte), e aggiorna `fs.total` e `fs.size`.\n\nExample: Contare\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nConta i file sul disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con il numero.\n\nConta i file nelle sottocartelle dell'archivio, senza `files.log`. Senza callback il metodo restituisce una promise.\n\nExample: Contare sul disco\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nRicrea files.log a partire dai file sul disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Viene eseguita quando il log è stato scritto. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise.\n\nLegge tutti i file con `fs.browse2()`, scrive un nuovo `files.log` e imposta `fs.total` e `fs.size`. Usalo dopo `fs.move()` o quando `files.log` è andato perso. Senza callback il metodo restituisce una promise.\n\nExample: Ricostruire\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nRimuove i file scaduti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` è il numero di file rimossi. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con il numero.\n\nTrova in `files.log` i file la cui data `expire` è passata e li elimina. Senza callback il metodo restituisce una promise.\n\nExample: Pulire ogni giorno\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nRimuove tutti i file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` è il numero di file rimossi. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con il numero.\n\nElimina tutti i file, le loro sottocartelle e `files.log`. Durante l'esecuzione, le altre letture e i salvataggi restano in attesa. Senza callback il metodo restituisce una promise. Alias: `fs.drop()`.\n\nExample: Svuotare\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias di fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con il numero.\n\nLo stesso metodo di `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nScrive tutti i file in un unico file di backup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Il file di destinazione o uno stream scrivibile. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` ha `filename`, `files` e `size`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con la risposta.\n\nOgni file viene compresso con GZIP e scritto in Base64. `filename` è un percorso o uno stream scrivibile. Senza callback il metodo restituisce una promise.\n\nExample: Backup\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nRipristina l'archivio da un file di backup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file di backup. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise.\n\nPrima rimuove tutti i file attuali (come `fs.clear()`), poi estrae il backup creato da `fs.backup()`. Letture e salvataggi restano in attesa finché non termina. Senza callback il metodo restituisce una promise.\n\nExample: Ripristinare\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nCambia la cartella dell'archivio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | Il percorso assoluto della cartella. |\n\nReturns: `FileStorage` L'archivio.\n\nImposta `fs.directory` e il percorso di `files.log` su un'altra cartella.\n\nExample: Un altro disco\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nRestituisce il percorso di un file sul disco.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID del file. |\n\nReturns: `String` Il percorso assoluto.\n\nRestituisce il percorso del `.file` per `id`. Il file inizia con un header di 2000 byte, quindi non è una copia del file originale; per quello usa `fs.copy()`.\n\nExample: Percorso\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nRisponde con un file da un archivio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'archivio. |\n| `id` | `String` | yes |  | L'ID del file. |\n| `download` | `Boolean|String|Function` | no |  | `true`, un nome di file, oppure `function(name, type)` che restituisce il nome. |\n| `headers` | `Object` | no |  | Header di risposta aggiuntivi. |\n| `callback` | `Function` | no |  | Viene eseguita quando il file è stato inviato. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; restituisci `false` per rispondere con `404`. |\n\nReturns: `Controller` Il controller.\n\nInvia il file `id` di `FILESTORAGE(name)` con il suo content type memorizzato. `download` impostato a `true` usa il nome memorizzato, una stringa imposta un altro nome. `checkmeta(meta)` che restituisce `false` produce `404`. Sono supportate le richieste `Range` e `If-Modified-Since`. L'oggetto risposta ha lo stesso metodo, `res.filefs()`.\n\nExample: Download\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nRisponde con un'immagine elaborata da un archivio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'archivio. |\n| `id` | `String` | yes |  | L'ID del file. |\n| `make` | `Function` | yes |  | `function(image, res)` che modifica l'immagine. |\n| `headers` | `Object` | no |  | Header di risposta aggiuntivi. |\n| `callback` | `Function` | no |  | Viene eseguita quando l'immagine è stata inviata. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; restituisci `false` per rispondere con `404`. |\n\nReturns: `Controller` Il controller.\n\nLegge l'immagine `id` di `FILESTORAGE(name)`, chiama `make(image, res)` per elaborarla e invia il risultato. L'immagine elaborata viene messa in cache nella cartella temporanea per ogni URL. Richiede GraphicsMagick o ImageMagick. L'oggetto risposta ha lo stesso metodo, `res.imagefs()`.\n\nExample: Miniatura\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nSalva un file caricato in un archivio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Il nome dell'archivio. |\n| `id` | `String` | yes |  | L'ID del file. |\n| `custom` | `Object` | no |  | Qualsiasi dato conservato con il file. |\n| `expire` | `String` | no |  | Un periodo di scadenza. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` L'archivio, oppure una promise con l'oggetto meta.\n\nUn metodo di ogni file in `controller.files`. Chiama `FILESTORAGE(storage).save()` con il nome originale del file e il file temporaneo dell'upload. Senza callback restituisce una promise.\n\nExample: Upload\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZEF44S61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/file-storage/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Úložisko súborov","summary":"FILESTORAGE(), jeho metódy, objekt meta a metódy kontroléra, ktoré poskytujú uložené súbory.","markdown":"---\ntitle: \"Úložisko súborov\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/file-storage/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Úložisko súborov\n\n> FILESTORAGE(), jeho metódy, objekt meta a metódy kontroléra, ktoré poskytujú uložené súbory.\n\n`FILESTORAGE(name)` vracia úložisko binárnych súborov v `databases/fs-{name}/`. V tejto referencii je `fs` úložisko vrátené z `FILESTORAGE()` a `meta` metadáta súboru. Návod [Úložisko súborov](../../guides/file-storage/) vysvetľuje na príkladoch, ako súbory ukladať, čítať a poskytovať.\n\n## API\n\n### FILESTORAGE(name)\n\nType: `method`\n\nVráti úložisko súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska. |\n\nReturns: `FileStorage` Úložisko.\n\nVráti úložisko `name`, uložené v `databases/fs-{name}/`. Objekt sa vytvorí pri prvom volaní a potom sa opätovne používa. Priečinok sa vytvorí, keď sa uloží prvý súbor.\n\nExample: Získanie úložiska\n```js\nvar fs = FILESTORAGE('photos');\nfs.save(UID(), 'logo.png', PATH.public('img/logo.png'));\n```\n\n### PATH.filestorage(name)\n\nType: `method`\n\nVráti priečinok úložiska súborov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska. |\n\nReturns: `String` Absolútna cesta k priečinku.\n\nVráti cestu `databases/fs-{name}/` v priečinku nastavenom cez `directory_databases`.\n\nExample: Priečinok\n```js\nconsole.log(PATH.filestorage('photos'));\n// /www/app/databases/fs-photos/\n```\n\n### fs.name\n\nType: `property`\n\nNázov úložiska.\n\nReturns: `String`\n\nNázov odovzdaný do `FILESTORAGE()`.\n\nExample: Názov\n```js\nconsole.log(FILESTORAGE('photos').name); // photos\n```\n\n### fs.directory\n\nType: `property`\n\nPriečinok úložiska.\n\nReturns: `String`\n\nAbsolútna cesta k priečinku so súbormi. Zmeníš ju pomocou `fs.storage()`.\n\nExample: Priečinok\n```js\nconsole.log(FILESTORAGE('photos').directory);\n```\n\n### fs.total\n\nType: `property`\n\nPočet súborov.\n\nReturns: `Number`\n\nPočítadlo uchovávané v pamäti. Začína na `0`; nastavujú ho `fs.count()` a `fs.rebuild()` a každý uložený súbor pridá jednotku.\n\nExample: Načítanie počítadiel\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log(fs.total, fs.size);\n});\n```\n\n### fs.size\n\nType: `property`\n\nCelková veľkosť súborov v bajtoch.\n\nReturns: `Number`\n\nPočítadlo uchovávané v pamäti. Začína na `0`; nastavujú ho `fs.count()` a `fs.rebuild()` a každý uložený súbor pridá svoju veľkosť.\n\nExample: Veľkosť v MB\n```js\nvar fs = FILESTORAGE('photos');\nfs.count(function() {\n\tconsole.log((fs.size / 1024 / 1024).floor(2) + ' MB');\n});\n```\n\n### fs.save(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nUloží súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `name` | `String` | yes |  | Názov súboru s príponou. |\n| `data` | `String|Buffer|Stream` | yes |  | Cesta, buffer, čitateľný stream alebo URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`, spustí sa po uložení súboru. |\n| `custom` | `Object` | no |  | Akékoľvek dáta uchované so súborom ako `meta.custom`. |\n| `expire` | `String` | no |  | Obdobie ako `'1 day'`; po ňom sa súbor nedá prečítať. |\n| `headers` | `Object` | no |  | Hlavičky pre požiadavku, keď je `data` URL. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nUloží `data` pod `id`. Prípona `name` určuje typ obsahu; cesta v `name` sa skráti na názov súboru. `data` je cesta k súboru, `Buffer`, čitateľný stream alebo URL `http://`/`https://`, ktorá sa najprv stiahne. Pri obrázkoch GIF, PNG, JPEG a SVG metadáta dostanú aj `width` a `height`. Existujúci súbor s rovnakým ID sa prepíše. Bez callbacku metóda vracia promise. Alias: `fs.insert()`.\n\nExample: Uloženie bufferu\n```js\nFILESTORAGE('documents').save(UID(), 'note.txt', Buffer.from('Hello'), function(err, meta) {\n\tconsole.log(meta.id, meta.size);\n});\n```\n\nExample: Stiahnutie z URL\n```js\nvar meta = await FILESTORAGE('photos').save(UID(), 'photo.jpg', 'https://example.com/photo.jpg', null, { source: 'web' }, '30 days');\n```\n\n### fs.insert(id, name, data, [callback], [custom], [expire], [headers])\n\nType: `method`\n\nAlias fs.save().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `name` | `String` | yes |  | Názov súboru s príponou. |\n| `data` | `String|Buffer|Stream` | yes |  | Cesta, buffer, čitateľný stream alebo URL. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Akékoľvek dáta uchované so súborom. |\n| `expire` | `String` | no |  | Obdobie expirácie. |\n| `headers` | `Object` | no |  | Hlavičky pre požiadavku na URL. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nRovnaká metóda ako `fs.save()`.\n\nExample: Vloženie\n```js\nFILESTORAGE('documents').insert(UID(), 'a.txt', Buffer.from('A'));\n```\n\n### fs.savejson(id, value, [callback], [custom], [expire])\n\nType: `method`\n\nUloží objekt ako JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `value` | `Object` | yes |  | Hodnota na uloženie. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `custom` | `Object` | no |  | Akékoľvek dáta uchované so súborom. |\n| `expire` | `String` | no |  | Obdobie expirácie. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise bez callbacku.\n\nSerializuje `value` pomocou `JSON.stringify()` a uloží ho ako `{id}.json`.\n\nExample: Uloženie nastavení\n```js\nFILESTORAGE('data').savejson('settings', { theme: 'dark' });\n```\n\n### fs.read(id, [callback], [nostream])\n\nType: `method`\n\nPrečíta súbor ako stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n| `nostream` | `Boolean` | no | `false` | Neotvárať stream obsahu. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nVráti objekt meta s `meta.stream`, čitateľným streamom obsahu. Keď je `nostream` nastavené na `true`, objekt meta príde bez streamu. Chyby: `File not found`, `Invalid file`, `File is expired` alebo chyba súborového systému. Bez callbacku metóda vracia promise.\n\nExample: Presmerovanie do súboru\n```js\nFILESTORAGE('documents').read(id, function(err, meta) {\n\tif (!err)\n\t\tmeta.stream.pipe(F.Fs.createWriteStream(PATH.temp(meta.name)));\n});\n```\n\n### fs.readmeta(id, [callback], [keepfd])\n\nType: `method`\n\nPrečíta iba metadáta súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err, meta, filename, fd)`. |\n| `keepfd` | `Boolean` | no | `false` | Ponechať deskriptor súboru `fd` otvorený; musíš ho zatvoriť. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nPrečíta hlavičku súboru. Dátumy prídu ako objekty `Date`. Callback dostane aj cestu k súboru na disku. Na rozdiel od `fs.read()` nekontroluje expiráciu. Bez callbacku metóda vracia promise.\n\nExample: Metadáta\n```js\nFILESTORAGE('documents').readmeta(id, function(err, meta) {\n\tconsole.log(meta.name, meta.type, meta.size);\n});\n```\n\n### fs.readbuffer(id, [callback])\n\nType: `method`\n\nPrečíta obsah súboru do Buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err, buffer, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s bufferom.\n\nNačíta celý súbor do pamäte. Pre veľké súbory používaj `fs.read()`. Bez callbacku metóda vracia promise. Promise vráti iba buffer.\n\nExample: Buffer\n```js\nvar buffer = await FILESTORAGE('documents').readbuffer(id);\n```\n\n### fs.readbase64(id, [callback])\n\nType: `method`\n\nPrečíta obsah súboru ako Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err, base64, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s reťazcom.\n\nPrečíta celý súbor a zakóduje ho ako reťazec Base64. Bez callbacku metóda vracia promise. Promise vráti iba reťazec.\n\nExample: Data URI\n```js\nFILESTORAGE('photos').readbase64(id, function(err, base64, meta) {\n\tvar uri = 'data:' + meta.type + ';base64,' + base64;\n});\n```\n\n### fs.readjson(id, callback)\n\nType: `method`\n\nPrečíta súbor JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | yes |  | `function(err, value, meta)`. |\n\nReturns: `FileStorage` Úložisko.\n\nPrečíta súbor uložený pomocou `fs.savejson()` a spracuje ho. Callback je povinný.\n\nExample: Načítanie nastavení\n```js\nFILESTORAGE('data').readjson('settings', function(err, value) {\n\tconsole.log(value.theme);\n});\n```\n\n### fs.image(id, [callback])\n\nType: `method`\n\nPrečíta uložený obrázok ako Image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err, image, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s obrázkom.\n\nVráti objekt `Image`, ktorý číta obsah súboru, takže môžeš zmeniť jeho veľkosť alebo ho skonvertovať a výsledok uložiť. Spracovanie obrázkov potrebuje GraphicsMagick alebo ImageMagick. Bez callbacku metóda vracia promise. Promise vráti iba obrázok.\n\nExample: Náhľad\n```js\nFILESTORAGE('photos').image(id, function(err, image, meta) {\n\tif (err)\n\t\treturn;\n\timage.resize(200, 200);\n\timage.save(PATH.temp('thumb_' + meta.name));\n});\n```\n\n### fs.res(res, options, [checkmeta])\n\nType: `method`\n\nOdošle súbor do HTTP odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `res` | `Response` | yes |  | Objekt odpovede. |\n| `options` | `Object` | yes |  | Voľby, pozri vyššie. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; vráť `false`, aby sa odpovedalo `404`. |\n\nReturns: `undefined`\n\nMetóda, na ktorej stoja `controller.filefs()` a `controller.imagefs()`. `options`: `id` (súbor), `download` (`true` pre uložený názov, reťazec alebo `function(name, type)`, ktorá vráti názov), `headers`, `done` (callback), `nocompress` a pri obrázkoch `image: true`, `make` (`function(image, res)`) a `cache` (predvolene `true`). Podporuje požiadavky `If-Modified-Since` (`304`) a `Range` (`206`). Chýbajúci alebo expirovaný súbor, prípadne `checkmeta(meta)`, ktorá vráti `false`, vráti `404`.\n\nExample: V route s req a res\n```js\nROUTE('GET /files/{id}/', function(id) {\n\tFILESTORAGE('documents').res(this.res, { id: id, download: true });\n});\n```\n\n### fs.copy(id, path, [callback])\n\nType: `method` · Since: `0.0.97`\n\nSkopíruje obsah súboru na disk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `path` | `String` | yes |  | Cieľový súbor alebo priečinok. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nZapíše obsah súboru (bez hlavičky) do `path`. Cesta s bodkou sa použije ako názov súboru; akákoľvek iná cesta je priečinok a súbor si ponechá uložený názov. Priečinok musí existovať. Súbory s vypršanou platnosťou vrátia chybu `File is expired`. Bez callbacku metóda vráti promise.\n\nExample: Export do priečinka\n```js\nFILESTORAGE('documents').copy(id, PATH.temp(), function(err, meta) {\n\tconsole.log(PATH.temp(meta.name));\n});\n```\n\nExample: Export do súboru\n```js\nawait FILESTORAGE('documents').copy(id, PATH.temp('invoice.pdf'));\n```\n\n### fs.clone(id, [newid], [callback])\n\nType: `method` · Since: `0.0.99`\n\nSkopíruje súbor v rámci úložiska pod nové ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `newid` | `String` | no | `UID()` | ID kópie. |\n| `callback` | `Function` | no |  | `function(err, meta)`; `meta.id` je nové ID. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s meta objektom.\n\nVytvorí kópiu súboru s rovnakými metadátami pod `newid` a pridá ju do `files.log`. Keď je druhým argumentom callback, nové ID sa vygeneruje cez `UID()`. Súbory s vypršanou platnosťou vrátia chybu `File is expired`. Bez callbacku metóda vráti promise. Pri použití promise odovzdaj `newid`.\n\nExample: Klonovanie\n```js\nFILESTORAGE('documents').clone(id, function(err, meta) {\n\tconsole.log('Copy:', meta.id);\n});\n```\n\nExample: Klonovanie ako promise\n```js\nvar meta = await FILESTORAGE('documents').clone(id, UID());\n```\n\n### fs.move(id, newid, [callback])\n\nType: `method`\n\nZmení ID súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `newid` | `String` | yes |  | Nové ID. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise.\n\nPresunie súbor na názov a do priečinka podľa `newid`. `files.log` sa nemení; zavolaj `fs.rebuild()`, keď súbory vypisuješ pomocou `fs.browse()`. Bez callbacku metóda vracia promise.\n\nExample: Presun\n```js\nFILESTORAGE('documents').move('draft', 'final', function(err) {\n\tconsole.log(err ? 'Error' : 'Moved');\n});\n```\n\n### fs.rename(id, newname, [callback])\n\nType: `method`\n\nZmení uložený názov súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `newname` | `String` | yes |  | Nový názov súboru (najviac 250 znakov). |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nZapíše nový názov do hlavičky a do `files.log`. Typ obsahu zostane rovnaký. Bez callbacku metóda vracia promise.\n\nExample: Premenovanie\n```js\nFILESTORAGE('documents').rename(id, 'contract-2024.pdf');\n```\n\n### fs.remove(id, [callback])\n\nType: `method`\n\nOdstráni súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise.\n\nVymaže súbor z disku a z `files.log`. Bez callbacku metóda vracia promise.\n\nExample: Odstránenie\n```js\nFILESTORAGE('documents').remove(id, function(err) {\n\tconsole.log(err ? 'Not found' : 'Removed');\n});\n```\n\n### fs.browse([callback])\n\nType: `method`\n\nVypíše súbory z files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nVráti NoSQL query builder nad `files.log`, databázou s metadátami všetkých súborov. Pridaj podmienky, triedenie a stránkovanie a potom `callback()`.\n\nExample: Najnovšie obrázky\n```js\nFILESTORAGE('photos').browse().where('ext', 'jpg').sort('date_desc').take(10).callback(function(err, files) {\n\tconsole.log(files);\n});\n```\n\n### fs.browse2([callback])\n\nType: `method`\n\nVypíše súbory z disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, files)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s poľom.\n\nPrečíta hlavičku každého súboru na disku a vráti ich objekty meta. Je pomalšie ako `fs.browse()`, ale nezávisí od `files.log`. Bez callbacku metóda vracia promise.\n\nExample: Všetky súbory\n```js\nvar files = await FILESTORAGE('photos').browse2();\nconsole.log(files.length);\n```\n\n### fs.stream(onfile, [callback], [workers])\n\nType: `method`\n\nPrejde všetky súbory na disku jeden po druhom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onfile` | `Function` | yes |  | `function(meta, next)`. |\n| `callback` | `Function` | no |  | Spustí sa po spracovaní všetkých súborov. |\n| `workers` | `Number` | no |  | Koľko súborov sa spracúva súčasne. |\n\nReturns: `FileStorage` Úložisko.\n\nZavolá `onfile(meta, next)` pre každý súbor; zavolaj `next()`, aby sa pokračovalo. `meta.index` je poradie súboru. `callback` sa spustí na konci.\n\nExample: Nájdenie veľkých súborov\n```js\nFILESTORAGE('documents').stream(function(meta, next) {\n\tif (meta.size > 1024 * 1024 * 10)\n\t\tconsole.log(meta.id, meta.name);\n\tnext();\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### fs.count([callback])\n\nType: `method`\n\nSpočíta súbory a ich veľkosť z files.log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\nReturns: `FileStorage` Úložisko.\n\nVráti objekt s `count` (počet súborov) a `size` (celková veľkosť v bajtoch) a aktualizuje `fs.total` a `fs.size`.\n\nExample: Počet\n```js\nFILESTORAGE('photos').count(function(err, response) {\n\tconsole.log(response.count, response.size);\n});\n```\n\n### fs.count2([callback])\n\nType: `method`\n\nSpočíta súbory na disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s číslom.\n\nSpočíta súbory v podpriečinkoch úložiska, bez `files.log`. Bez callbacku metóda vracia promise.\n\nExample: Počet na disku\n```js\nvar count = await FILESTORAGE('photos').count2();\n```\n\n### fs.rebuild([callback])\n\nType: `method`\n\nZnova vytvorí files.log zo súborov na disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | Spustí sa po zapísaní logu. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise.\n\nPrečíta všetky súbory pomocou `fs.browse2()`, zapíše nový `files.log` a nastaví `fs.total` a `fs.size`. Použi ho po `fs.move()` alebo keď sa `files.log` stratil. Bez callbacku metóda vracia promise.\n\nExample: Obnova logu\n```js\nFILESTORAGE('photos').rebuild(function() {\n\tconsole.log('files.log is ready');\n});\n```\n\n### fs.clean([callback])\n\nType: `method`\n\nOdstráni expirované súbory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` je počet odstránených súborov. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s číslom.\n\nNájde v `files.log` súbory, ktorých dátum `expire` uplynul, a vymaže ich. Bez callbacku metóda vracia promise.\n\nExample: Čistenie každý deň\n```js\nON('service', function(counter) {\n\tif (counter % 1440 === 0)\n\t\tFILESTORAGE('temporary').clean();\n});\n```\n\n### fs.clear([callback])\n\nType: `method`\n\nOdstráni všetky súbory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`; `count` je počet odstránených súborov. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s číslom.\n\nVymaže všetky súbory, ich podpriečinky a `files.log`. Kým beží, ostatné čítania a ukladania čakajú. Bez callbacku metóda vracia promise. Alias: `fs.drop()`.\n\nExample: Vymazanie\n```js\nvar count = await FILESTORAGE('temporary').clear();\n```\n\n### fs.drop([callback])\n\nType: `method`\n\nAlias fs.clear().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s číslom.\n\nRovnaká metóda ako `fs.clear()`.\n\nExample: Drop\n```js\nFILESTORAGE('temporary').drop();\n```\n\n### fs.backup(filename, [callback])\n\nType: `method`\n\nZapíše všetky súbory do jedného záložného súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Cieľový súbor alebo zapisovateľný stream. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` obsahuje `filename`, `files` a `size`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s odpoveďou.\n\nKaždý súbor sa skomprimuje pomocou GZIP a zapíše ako Base64. `filename` je cesta alebo zapisovateľný stream. Bez callbacku metóda vracia promise.\n\nExample: Záloha\n```js\nFILESTORAGE('photos').backup(PATH.temp('photos.backup'), function(err, response) {\n\tconsole.log(response.files, response.size);\n});\n```\n\n### fs.restore(filename, [callback])\n\nType: `method`\n\nObnoví úložisko zo záložného súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Záložný súbor. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise.\n\nNajprv odstráni všetky aktuálne súbory (ako `fs.clear()`), potom rozbalí zálohu vytvorenú pomocou `fs.backup()`. Čítania a ukladania čakajú, kým neskončí. Bez callbacku metóda vracia promise.\n\nExample: Obnovenie\n```js\nFILESTORAGE('photos').restore(PATH.temp('photos.backup'), function(err) {\n\tFILESTORAGE('photos').rebuild();\n});\n```\n\n### fs.storage(directory)\n\nType: `method`\n\nZmení priečinok úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | yes |  | Absolútna cesta k priečinku. |\n\nReturns: `FileStorage` Úložisko.\n\nNastaví `fs.directory` a cestu k `files.log` na iný priečinok.\n\nExample: Iný disk\n```js\nFILESTORAGE('archive').storage('/mnt/archive/files/');\n```\n\n### fs.readfilename(id)\n\nType: `method`\n\nVráti cestu k súboru na disku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID súboru. |\n\nReturns: `String` Absolútna cesta.\n\nVráti cestu k `.file` pre `id`. Súbor začína hlavičkou s veľkosťou 2000 bajtov, takže nie je kópiou pôvodného súboru; na to použi `fs.copy()`.\n\nExample: Cesta\n```js\nconsole.log(FILESTORAGE('photos').readfilename(id));\n```\n\n### controller.filefs(name, id, [download], [headers], [callback], [checkmeta])\n\nType: `method`\n\nOdpovie súborom z úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska. |\n| `id` | `String` | yes |  | ID súboru. |\n| `download` | `Boolean|String|Function` | no |  | `true`, názov súboru alebo `function(name, type)`, ktorá vráti názov. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa po odoslaní súboru. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; vráť `false`, aby sa odpovedalo `404`. |\n\nReturns: `Controller` Kontrolér.\n\nOdošle súbor `id` z `FILESTORAGE(name)` s jeho uloženým typom obsahu. `download` nastavené na `true` použije uložený názov, reťazec nastaví iný názov. `checkmeta(meta)`, ktorá vráti `false`, vráti `404`. Požiadavky `Range` a `If-Modified-Since` sú podporované. Objekt odpovede má rovnakú metódu, `res.filefs()`.\n\nExample: Stiahnutie\n```js\nexports.install = function() {\n\tROUTE('GET /download/{id}/', download);\n};\n\nfunction download(id) {\n\tthis.filefs('documents', id, true);\n}\n```\n\n### controller.imagefs(name, id, make, [headers], [callback], [checkmeta])\n\nType: `method`\n\nOdpovie spracovaným obrázkom z úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úložiska. |\n| `id` | `String` | yes |  | ID súboru. |\n| `make` | `Function` | yes |  | `function(image, res)`, ktorá zmení obrázok. |\n| `headers` | `Object` | no |  | Ďalšie hlavičky odpovede. |\n| `callback` | `Function` | no |  | Spustí sa po odoslaní obrázka. |\n| `checkmeta` | `Function` | no |  | `function(meta)`; vráť `false`, aby sa odpovedalo `404`. |\n\nReturns: `Controller` Kontrolér.\n\nPrečíta obrázok `id` z `FILESTORAGE(name)`, zavolá `make(image, res)` na jeho spracovanie a odošle výsledok. Spracovaný obrázok sa uloží do cache v dočasnom priečinku pre každú URL. Potrebuje GraphicsMagick alebo ImageMagick. Objekt odpovede má rovnakú metódu, `res.imagefs()`.\n\nExample: Náhľad\n```js\nexports.install = function() {\n\tROUTE('GET /thumbnails/{id}/', thumbnail);\n};\n\nfunction thumbnail(id) {\n\tthis.imagefs('photos', id, function(image) {\n\t\timage.resizeCenter(200, 200);\n\t\timage.quality(80);\n\t});\n}\n```\n\n### file.fs(storage, id, [custom], [expire], [callback])\n\nType: `method`\n\nUloží nahraný súbor do úložiska.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `storage` | `String` | yes |  | Názov úložiska. |\n| `id` | `String` | yes |  | ID súboru. |\n| `custom` | `Object` | no |  | Akékoľvek dáta uchované so súborom. |\n| `expire` | `String` | no |  | Obdobie expirácie. |\n| `callback` | `Function` | no |  | `function(err, meta)`. |\n\nReturns: `FileStorage|Promise` Úložisko alebo promise s objektom meta.\n\nMetóda každého súboru v `controller.files`. Zavolá `FILESTORAGE(storage).save()` s pôvodným názvom súboru a dočasným súborom nahrávania. Bez callbacku vracia promise.\n\nExample: Nahrávanie\n```js\nexports.install = function() {\n\tROUTE('POST /api/upload/', upload, ['upload'], 1024 * 5);\n};\n\nasync function upload() {\n\tvar file = this.files[0];\n\tvar meta = await file.fs('documents', UID(), { user: this.user.id });\n\tthis.json({ id: meta.id, name: meta.name });\n}\n```\n","entries":[{"type":"method","name":"FILESTORAGE()","signature":"FILESTORAGE(name)","since":"","deprecated":false},{"type":"method","name":"PATH.filestorage()","signature":"PATH.filestorage(name)","since":"","deprecated":false},{"type":"property","name":"fs.name","signature":"fs.name","since":"","deprecated":false},{"type":"property","name":"fs.directory","signature":"fs.directory","since":"","deprecated":false},{"type":"property","name":"fs.total","signature":"fs.total","since":"","deprecated":false},{"type":"property","name":"fs.size","signature":"fs.size","since":"","deprecated":false},{"type":"method","name":"fs.save()","signature":"fs.save(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.insert()","signature":"fs.insert(id, name, data, [callback], [custom], [expire], [headers])","since":"","deprecated":false},{"type":"method","name":"fs.savejson()","signature":"fs.savejson(id, value, [callback], [custom], [expire])","since":"","deprecated":false},{"type":"method","name":"fs.read()","signature":"fs.read(id, [callback], [nostream])","since":"","deprecated":false},{"type":"method","name":"fs.readmeta()","signature":"fs.readmeta(id, [callback], [keepfd])","since":"","deprecated":false},{"type":"method","name":"fs.readbuffer()","signature":"fs.readbuffer(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readbase64()","signature":"fs.readbase64(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.readjson()","signature":"fs.readjson(id, callback)","since":"","deprecated":false},{"type":"method","name":"fs.image()","signature":"fs.image(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.res()","signature":"fs.res(res, options, [checkmeta])","since":"","deprecated":false},{"type":"method","name":"fs.copy()","signature":"fs.copy(id, path, [callback])","since":"0.0.97","deprecated":false},{"type":"method","name":"fs.clone()","signature":"fs.clone(id, [newid], [callback])","since":"0.0.99","deprecated":false},{"type":"method","name":"fs.move()","signature":"fs.move(id, newid, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.rename()","signature":"fs.rename(id, newname, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.remove()","signature":"fs.remove(id, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse()","signature":"fs.browse([callback])","since":"","deprecated":false},{"type":"method","name":"fs.browse2()","signature":"fs.browse2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.stream()","signature":"fs.stream(onfile, [callback], [workers])","since":"","deprecated":false},{"type":"method","name":"fs.count()","signature":"fs.count([callback])","since":"","deprecated":false},{"type":"method","name":"fs.count2()","signature":"fs.count2([callback])","since":"","deprecated":false},{"type":"method","name":"fs.rebuild()","signature":"fs.rebuild([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clean()","signature":"fs.clean([callback])","since":"","deprecated":false},{"type":"method","name":"fs.clear()","signature":"fs.clear([callback])","since":"","deprecated":false},{"type":"method","name":"fs.drop()","signature":"fs.drop([callback])","since":"","deprecated":false},{"type":"method","name":"fs.backup()","signature":"fs.backup(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.restore()","signature":"fs.restore(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"fs.storage()","signature":"fs.storage(directory)","since":"","deprecated":false},{"type":"method","name":"fs.readfilename()","signature":"fs.readfilename(id)","since":"","deprecated":false},{"type":"method","name":"controller.filefs()","signature":"controller.filefs(name, id, [download], [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"controller.imagefs()","signature":"controller.imagefs(name, id, make, [headers], [callback], [checkmeta])","since":"","deprecated":false},{"type":"method","name":"file.fs()","signature":"file.fs(storage, id, [custom], [expire], [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabZRH4aj61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Operations and tasks","summary":"Global functions and the $ object of operations and tasks, plus commands, extensions and PROMISIFY().","markdown":"---\ntitle: Operations and tasks\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operations and tasks\n\n> Global functions and the $ object of operations and tasks, plus commands, extensions and PROMISIFY().\n\nOperations (`NEWOPERATION()`, `OPERATION()`, `RUN()`) and tasks (`NEWTASK()`, `TASK()`) hold business logic outside of routes. Both receive a `$` object; this page lists its properties and methods, and also commands, extensions and `PROMISIFY()`. The guide [Operations and tasks](../../guides/operations-and-tasks/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nRegisters an operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the operation. |\n| `fn` | `Function($, value)` | yes |  | The operation. `null` removes it. |\n| `repeat` | `Number` | no |  | How many times to run the operation again when it ends with an error. |\n| `stop` | `Boolean` | no | `true` | Stops a `RUN()` chain when this operation fails. |\n| `binderror` | `Boolean` | no | `false` | In a `RUN()` chain, stores the error output as the response of this operation. |\n| `filter` | `String` | no |  | Schema for the query string, used by `$.filter`. |\n\nThe function receives `$` and the value. It must end with `$.callback()`, `$.success()`, `$.invalid()` or another method that calls the callback. A boolean in place of `repeat` is read as `stop`, and a string in any optional position is read as `filter`. Calling `NEWOPERATION(name, null)` removes the operation. Put operations in the `/operations/` directory.\n\nExample: An operation\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Repeat after an error\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nRuns one operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the operation, or a URL of a remote operation. |\n| `value` | `Object` | no | `{}` | Value for `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Called when the operation ends. |\n| `options` | `Object` | no |  | Custom options, available as `$.options`. |\n| `controller` | `Controller` | no |  | Controller of the current request, or a `$` object. |\n\nThe callback receives `err` (an `ErrorBuilder` or `null`), the response and `options`. When `value` is a function, it is the callback and the value is an empty object. A controller or a `$` object passed as `options` is used as the controller. A missing operation ends with the error `Operation \"name\" not found.`\n\nThe name can also be a URL with an optional expiration, for example `'https://example.com/op.js <5 minutes>'` (`once` and `asap` are accepted too). The file is downloaded, compiled and cached until it expires. It can contain a `NEWOPERATION()` declaration or a module with `exports.install`, `exports.make` or `exports.exec`.\n\nExample: Call an operation\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: From a route\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nRuns several operations one after another.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Operation names, separated by commas. |\n| `value` | `Object` | no | `{}` | Shared value for `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Called when the chain ends. |\n| `options` | `Object` | no |  | Custom options, available as `$.options`. |\n| `controller` | `Controller` | no |  | Controller of the current request. |\n| `response_name` | `String` | no |  | Name of the operation whose response is returned alone. |\n\n`names` is a comma-separated string or an array. All operations share one `$` and one `$.value`. The callback receives `err`, the response and the `$` object. The response has one key per operation; with `response_name` it is only the response of that operation. When an operation fails and its `stop` option is `true` (the default), the chain stops. Names that do not exist are skipped. A string in place of `options` or `controller` is read as `response_name`.\n\nExample: Chain two operations\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Return one response\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nCalls a function for each registered operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Called with the name of each operation. |\n\nThe function receives the name of each operation.\n\nExample: List operations\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nThe value passed to the operation.\n\nReturns: `Object`\n\n`$.model` is the same value. In a `RUN()` chain, every operation shares this object, so changes are visible to the next operations.\n\nExample: Read the value\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nThe options passed to `OPERATION()` or `RUN()`.\n\nReturns: `Object`\n\nAn empty object when no options were passed. `OPERATION()` passes it again as the third argument of the callback.\n\nExample: Use options\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nName of the running operation.\n\nReturns: `String`\n\nIn a `RUN()` chain it changes with each operation.\n\nExample: Log the name\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\nThe `ErrorBuilder` of the operation.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` pushes errors here. In a `RUN()` chain, each operation gets a new `ErrorBuilder`.\n\nExample: Push several errors\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nThe controller passed to the operation, or `undefined`.\n\nReturns: `Controller`\n\n`$.client` is the same value. Request properties of `$` read from this controller.\n\nExample: Check for a controller\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nThe user of the current request.\n\nReturns: `Object`\n\nRead from the controller, or `null` without a controller. The other request properties work the same way: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` and `$.test`.\n\nExample: Use the user and the query\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nThe query string converted by the `filter` schema of the operation.\n\nReturns: `Object`\n\nThe schema is the `filter` argument of `NEWOPERATION()`, for example `'page:Number,q:String'`. Without a schema it returns the raw query. Without a controller it returns an empty object.\n\nExample: Typed query\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nEnds the operation and returns a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | The response, or an error. |\n\nReturns: `$`\n\nAn `Error` or an `ErrorBuilder` with errors is pushed to `$.error`. You can also call it as `$.callback(err, value)`. When the operation has errors and `repeat` left, it runs again instead.\n\nExample: Return a value\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: Pass it as a callback\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nEnds the operation with a success object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | The success flag. |\n| `value` | `Object` | no |  | A value added as `value`. |\n\nReturns: `$`\n\nReturns `{ success: true }` to the callback. `$.success(value)` adds `value`. `$.success(false)` sets `success` to `false`. In a `RUN()` chain, empty keys are left out.\n\nExample: Return the new id\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nEnds the operation with an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Error name, error message or `Error`. |\n| `error` | `String` | no |  | Error message. |\n| `path` | `String` | no |  | Path of the field. |\n| `index` | `Number` | no |  | Index of the item in an array. |\n\nReturns: `$|Function`\n\nThe arguments go to `$.error.push()`. Without arguments it returns a function `function(err)` that you can pass as a callback.\n\nExample: Return an error\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nReturns a callback that ends the operation with a success object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` adds the response; another value is added as it is. |\n\nReturns: `Function(err, response)`\n\nThe returned function `function(err, response)` pushes `err` and calls back, or calls back with `{ success: true }`. With `arg` set to `true`, the response is added as `value`; any other `arg` is added instead of the response.\n\nExample: Return the inserted record\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nReturns a callback that handles errors for you.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Called when there is no error. |\n\nReturns: `Function(err, a, b, c)`\n\nThe returned function `function(err, a, b, c)` calls `$.invalid(err)` when there is an error, otherwise it calls `callback(a, b, c)` with `$` as `this`.\n\nExample: Skip error checks\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nEnds the operation with a redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Target URL. |\n\nReturns: `$`\n\nWhen the operation was called with `controller.callback()`, the controller redirects to `url`.\n\nExample: Redirect after logout\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nEnds the operation without calling the callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` does not call `controller.custom()`. |\n\nReturns: `$`\n\nUse it when the operation answers the request itself. By default it also calls `controller.custom()`, so the framework does not send another response; `true` skips that call.\n\nExample: Answer the request yourself\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nReads or writes a cookie of the current request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cookie name. |\n| `value` | `String` | no |  | New value, or `null` to remove it. |\n| `expire` | `String|Date` | no |  | Expiration, for example `'1 day'`. |\n| `options` | `Object` | no |  | Cookie options. |\n\nReturns: `String|$`\n\nWith only `name` it returns the cookie value. `null` as `value` removes the cookie. Needs a controller.\n\nExample: Write a cookie\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nReplaces `{key}` placeholders in a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Text with placeholders. |\n| `data` | `Object` | no |  | Values for `{data.key}`. |\n\nReturns: `String`\n\nSupported keys start with `user.`, `data.`, `model.` or `value.`, `query.` and `params.`. Unknown keys are kept. Single or double braces work. It exists on the `$` of operations and tasks.\n\nExample: Build a message\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nWrites an audit log entry for the operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Audit message. |\n| `type` | `String` | no |  | Type of the entry. |\n\nReturns: `$`\n\nCalls `AUDIT($, message, type)` with data from the user, the request and the value. It exists on the `$` of operations and tasks.\n\nExample: Audit a change\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nResults of the previous operations in a `RUN()` chain.\n\nReturns: `Object`\n\nAn object with one key per operation that has already ended. Only set inside `RUN()`.\n\nExample: Use a previous result\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformation about a `RUN()` chain.\n\nReturns: `Object`\n\n`$.meta.items` is the list of names, `$.meta.current` the running operation, `$.meta.prev` the previous one and `$.meta.index` the index of the running operation. Only set inside `RUN()`.\n\nExample: Check the previous operation\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nHow many times the running operation was repeated in a `RUN()` chain.\n\nReturns: `Number`\n\nStarts at `0` for each operation and grows each time the `repeat` option runs it again. Only set inside `RUN()`.\n\nExample: Give up early\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDeclares a task with named steps.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the task. |\n| `fn` | `Function(push)` | yes |  | Declares the steps with `push(step, fn($, value))`. `null` removes the task. |\n\n`fn` receives `push(step, fn)`. Each step receives `$` and the value, and `this` is `$`. `NEWTASK(name, null)` removes the task. Put tasks in the `/tasks/` directory.\n\nExample: A task with two steps\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nCreates a task and starts it at a step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the task, or `'name/step'`. |\n| `step` | `String` | yes |  | The first step. |\n| `callback` | `Function(err, response)` | yes |  | Called when the task ends. |\n| `options` | `Controller|Object` | no |  | Controller or `$` object, or the value. |\n| `value` | `Object` | no | `{}` | Value for `$.value`. |\n\nReturns: `TaskBuilder` The task, `$`.\n\n`name` and `step` can be one string `'name/step'`; then the arguments are `TASK('name/step', callback, [options], [value])`. A controller or the `$` of a schema, operation or task as `options` shares its request and its errors; any other `options` is used as the value. The step starts on the next tick, so you can add steps with `$.push()` first. Without a step, start it with `$.exec()`.\n\nThe name can also be a URL with an optional expiration, for example `'https://example.com/task.js <1 hour>'`. The file is downloaded and cached until it expires.\n\nExample: Run a task\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: From a schema action, with \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nRuns the next step of the task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Name of the step. More names are tried in order. |\n\nReturns: `$`\n\nRuns the first step in the list that exists, first in steps added with `$.push()` and then in the task declaration. When none exists, the task ends. Does nothing after the task ended.\n\nExample: Go to the next step\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nReturns a callback that goes to the next step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Name of the next step. |\n\nReturns: `Function(err)`\n\nThe returned function `function(err)` calls `$.invalid(err)` on an error, otherwise it runs `step`, or ends the task when `step` is empty.\n\nExample: Continue after a write\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nEnds the task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | The response. |\n\nReturns: `$`\n\nCalls the task callback with the errors (or `null`) and `data`, or `$.value` when `data` is empty.\n\nExample: End with the value\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nReturns a callback that ends the task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` returns the data of the callback. |\n\nReturns: `Function(err, data)`\n\nThe returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `data` when `send_value` is `true`, or with `$.value`.\n\nExample: End with the result\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nEnds the task with a success object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | A value added as `value`. |\n\nReturns: `$`\n\nEnds the task with `{ success: true }`, plus `value` when `data` is set.\n\nExample: End with success\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nReturns a callback that ends the task with a success object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` adds the data of the callback as `value`. |\n\nReturns: `Function(err, data)`\n\nThe returned function `function(err, data)` calls `$.invalid(err)` on an error, otherwise it ends the task with `{ success: true }`, plus `value: data` when `send_value` is `true`.\n\nExample: Save and finish\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nEnds the task with an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Error name or `Error`. |\n| `msg` | `String` | no |  | Error message. |\n\nReturns: `$`\n\nPushes the error to `$.error` and ends the task. Does nothing after the task ended.\n\nExample: Stop the task\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nAdds a step to this task only.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Name of the step. |\n| `fn` | `Function($, value)` | yes |  | The step. |\n\nReturns: `$`\n\nThe step is used before a step of the same name in the task declaration. Call it on the task that `TASK()` returns, before the first step runs.\n\nExample: Override a step\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nStarts the task at a step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | The first step. |\n| `callback` | `Function(err, response)` | no |  | Called when the task ends. |\n\nReturns: `$`\n\nSets the callback when given and runs `step`. Use it with a task created by `TASK(name)` without a step.\n\nExample: Start later\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nSets the callback of the task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | The callback. |\n\nReturns: `$`\n\n`fn` is called once when the task ends, with the errors (or `null`) and the response.\n\nExample: Set the callback\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nThe value shared by all steps of the task.\n\nReturns: `Object`\n\n`$.model` is the same value. Steps also receive it as the second argument. It is an empty object when no value was passed.\n\nExample: Change the value\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nName of the running step.\n\nReturns: `String`\n\n`$.prev` holds the previous step and `$.name` the name of the task. The request properties (`$.user`, `$.query`, `$.params`, `$.body` and others) read from the controller, like in operations.\n\nExample: Log the step\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nWraps a function with a callback in a Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | A function whose last argument is `callback(err, response)`. |\n| `a` | `Object` | no |  | First argument for `fn`. |\n| `b` | `Object` | no |  | Second argument for `fn`. |\n\nReturns: `Promise`\n\nCalls `fn` with the given arguments and a callback `function(err, response)` as the last argument. The promise resolves with `response` or rejects with `err`. Empty arguments are not passed.\n\nExample: Await a callback\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Read a file\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nAdds a handler for a command.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the command. |\n| `fn` | `Function(a, b, c, d)` | yes |  | The handler. `null` removes all handlers. |\n\nA command can have several handlers; each call adds one. `NEWCOMMAND(name, null)` removes all handlers of the command. Run it with `CMD()`.\n\nExample: A command\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nRuns all handlers of a command.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the command. |\n| `a` | `Object` | no |  | First argument. |\n| `b` | `Object` | no |  | Second argument. |\n| `c` | `Object` | no |  | Third argument. |\n| `d` | `Object` | no |  | Fourth argument. |\n\nPasses up to four arguments to each handler. Does nothing when the command has no handler. Built-in commands include `clear_viewscache`, `clear_smtpcache` and `refresh_tms`.\n\nExample: Run a command\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nReturns a function that runs a command.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the command. |\n| `a` | `Object` | no |  | First argument. |\n| `b` | `Object` | no |  | Second argument. |\n| `c` | `Object` | no |  | Third argument. |\n| `d` | `Object` | no |  | Fourth argument. |\n\nReturns: `Function`\n\nThe returned function runs all handlers with the given arguments. When the command has no handler, it returns `NOOP`.\n\nExample: Run a command later\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nInstalls an extension from source code or a URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Source code, or a URL. |\n| `callback` | `Function(err, module)` | no |  | Called when the extension is installed. |\n| `extend` | `Function(module)` | no |  | Called with the module before it is installed. |\n\n`code` is JavaScript that sets `exports`, or a URL to download it from. Optional exports: `id`, `name`, `install(next)`, `make()`, `done()` and `uninstall()`. Without `id` the id is a hash of `name` or the code. An extension with the same id is removed first. The code can also be HTML with a `<script total>` block and `<file name=\"...\">` blocks; `exports.files` then maps each file name to a temporary path. The added `remove()` method uninstalls the extension. Files in the `/extensions/` directory are installed when the app starts.\n\nExample: Install from a string\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Install from a URL\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nCreates a small in-memory state machine: named steps that move to each other with `$.next()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)` that adds the steps. |\n| `tasks` | `Object` | no | `{}` | Steps as `{ name: function($, value) }`. |\n\nReturns: `Object` The workflow `$`.\n\n`WORKFLOW()` returns a `$` object and passes it to `declaration($)`, where you add steps with `$.push(name, fn)`. Each step is `function($, value)`. It is a local helper, not a registered task: nothing is stored or named globally.\n\n| Member | What it does |\n| --- | --- |\n| `$.push(name, fn)` | Adds the step `fn($, value)` |\n| `$.next(name, [value])` | Runs the step `name` with `value`; `$.trigger()` is an alias. An unknown name destroys the workflow |\n| `$.next2(name)` | Returns `function(value)` that runs `$.next(name, value)`, for callbacks |\n| `$.invalid(err)` | Calls `$.error(err, $)` when you set it, then destroys the workflow |\n| `$.current`, `$.prev` | The name of the current and of the previous step |\n| `$.tasks` | The steps, as an object |\n| `$.clone()` | A new workflow with the same steps |\n| `$.destroy()` | Ends it; later calls of `$.next()` do nothing |\n\n`declaration` can be `null` when you pass the steps as `tasks`.\n\nExample: Steps in order\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZRH4aj61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Operations und Tasks","summary":"Globale Funktionen und das $-Objekt von Operations und Tasks sowie Befehle, Erweiterungen und PROMISIFY().","markdown":"---\ntitle: Operations und Tasks\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operations und Tasks\n\n> Globale Funktionen und das $-Objekt von Operations und Tasks sowie Befehle, Erweiterungen und PROMISIFY().\n\nOperations (`NEWOPERATION()`, `OPERATION()`, `RUN()`) und Tasks (`NEWTASK()`, `TASK()`) enthalten Geschäftslogik außerhalb von Routen. Beide erhalten ein `$`-Objekt; diese Seite listet seine Eigenschaften und Methoden auf, außerdem Befehle, Erweiterungen und `PROMISIFY()`. Der Leitfaden [Operations und Tasks](../../guides/operations-and-tasks/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nRegistriert eine Operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Operation. |\n| `fn` | `Function($, value)` | yes |  | Die Operation. `null` entfernt sie. |\n| `repeat` | `Number` | no |  | Wie oft die Operation erneut ausgeführt wird, wenn sie mit einem Fehler endet. |\n| `stop` | `Boolean` | no | `true` | Stoppt eine `RUN()`-Kette, wenn diese Operation fehlschlägt. |\n| `binderror` | `Boolean` | no | `false` | Speichert in einer `RUN()`-Kette die Fehlerausgabe als Antwort dieser Operation. |\n| `filter` | `String` | no |  | Schema für den Query-String, verwendet von `$.filter`. |\n\nDie Funktion erhält `$` und den Wert. Sie muss mit `$.callback()`, `$.success()`, `$.invalid()` oder einer anderen Methode enden, die den Callback aufruft. Ein Boolean an der Stelle von `repeat` wird als `stop` gelesen, und ein String an einer beliebigen optionalen Position wird als `filter` gelesen. Der Aufruf `NEWOPERATION(name, null)` entfernt die Operation. Lege Operationen im Verzeichnis `/operations/` ab.\n\nExample: Eine Operation\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Nach einem Fehler wiederholen\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nFührt eine Operation aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Operation oder URL einer entfernten Operation. |\n| `value` | `Object` | no | `{}` | Wert für `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Wird aufgerufen, wenn die Operation endet. |\n| `options` | `Object` | no |  | Eigene Optionen, verfügbar als `$.options`. |\n| `controller` | `Controller` | no |  | Controller der aktuellen Anfrage oder ein `$`-Objekt. |\n\nDer Callback erhält `err` (einen `ErrorBuilder` oder `null`), die Antwort und `options`. Ist `value` eine Funktion, ist sie der Callback und der Wert ist ein leeres Objekt. Ein als `options` übergebener Controller oder ein `$`-Objekt wird als Controller verwendet. Eine fehlende Operation endet mit dem Fehler `Operation \"name\" not found.`\n\nDer Name kann auch eine URL mit optionalem Ablauf sein, zum Beispiel `'https://example.com/op.js <5 minutes>'` (`once` und `asap` werden ebenfalls akzeptiert). Die Datei wird heruntergeladen, kompiliert und bis zum Ablauf zwischengespeichert. Sie kann eine `NEWOPERATION()`-Deklaration oder ein Modul mit `exports.install`, `exports.make` oder `exports.exec` enthalten.\n\nExample: Eine Operation aufrufen\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Aus einer Route\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nFührt mehrere Operationen nacheinander aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Namen der Operationen, durch Kommas getrennt. |\n| `value` | `Object` | no | `{}` | Gemeinsamer Wert für `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Wird aufgerufen, wenn die Kette endet. |\n| `options` | `Object` | no |  | Eigene Optionen, verfügbar als `$.options`. |\n| `controller` | `Controller` | no |  | Controller der aktuellen Anfrage. |\n| `response_name` | `String` | no |  | Name der Operation, deren Antwort allein zurückgegeben wird. |\n\n`names` ist ein durch Kommas getrennter String oder ein Array. Alle Operationen teilen sich ein `$` und einen `$.value`. Der Callback erhält `err`, die Antwort und das `$`-Objekt. Die Antwort hat einen Schlüssel pro Operation; mit `response_name` ist sie nur die Antwort dieser Operation. Schlägt eine Operation fehl und ist ihre Option `stop` gleich `true` (der Standard), stoppt die Kette. Nicht existierende Namen werden übersprungen. Ein String an der Stelle von `options` oder `controller` wird als `response_name` gelesen.\n\nExample: Zwei Operationen verketten\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Eine einzelne Antwort zurückgeben\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nRuft eine Funktion für jede registrierte Operation auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Wird mit dem Namen jeder Operation aufgerufen. |\n\nDie Funktion erhält den Namen jeder Operation.\n\nExample: Operationen auflisten\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nDer an die Operation übergebene Wert.\n\nReturns: `Object`\n\n`$.model` ist derselbe Wert. In einer `RUN()`-Kette teilen sich alle Operationen dieses Objekt, sodass Änderungen für die nächsten Operationen sichtbar sind.\n\nExample: Den Wert lesen\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nDie an `OPERATION()` oder `RUN()` übergebenen Optionen.\n\nReturns: `Object`\n\nEin leeres Objekt, wenn keine Optionen übergeben wurden. `OPERATION()` übergibt es erneut als drittes Argument des Callbacks.\n\nExample: Optionen verwenden\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nName der laufenden Operation.\n\nReturns: `String`\n\nIn einer `RUN()`-Kette ändert er sich mit jeder Operation.\n\nExample: Den Namen protokollieren\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\nDer `ErrorBuilder` der Operation.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` fügt hier Fehler hinzu. In einer `RUN()`-Kette erhält jede Operation einen neuen `ErrorBuilder`.\n\nExample: Mehrere Fehler hinzufügen\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nDer an die Operation übergebene Controller oder `undefined`.\n\nReturns: `Controller`\n\n`$.client` ist derselbe Wert. Die Anfrage-Eigenschaften von `$` lesen aus diesem Controller.\n\nExample: Auf einen Controller prüfen\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nDer Benutzer der aktuellen Anfrage.\n\nReturns: `Object`\n\nWird aus dem Controller gelesen, oder `null` ohne Controller. Die anderen Anfrage-Eigenschaften funktionieren genauso: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` und `$.test`.\n\nExample: Den Benutzer und die Query verwenden\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nDer Query-String, konvertiert durch das `filter`-Schema der Operation.\n\nReturns: `Object`\n\nDas Schema ist das Argument `filter` von `NEWOPERATION()`, zum Beispiel `'page:Number,q:String'`. Ohne Schema gibt es die rohe Query zurück. Ohne Controller gibt es ein leeres Objekt zurück.\n\nExample: Typisierte Query\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nBeendet die Operation und gibt einen Wert zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Die Antwort oder ein Fehler. |\n\nReturns: `$`\n\nEin `Error` oder ein `ErrorBuilder` mit Fehlern wird zu `$.error` hinzugefügt. Du kannst die Methode auch als `$.callback(err, value)` aufrufen. Hat die Operation Fehler und ist noch `repeat` übrig, läuft sie stattdessen erneut.\n\nExample: Einen Wert zurückgeben\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: Als Callback übergeben\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nBeendet die Operation mit einem Erfolgsobjekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Das Erfolgs-Flag. |\n| `value` | `Object` | no |  | Ein Wert, der als `value` hinzugefügt wird. |\n\nReturns: `$`\n\nGibt `{ success: true }` an den Callback zurück. `$.success(value)` fügt `value` hinzu. `$.success(false)` setzt `success` auf `false`. In einer `RUN()`-Kette werden leere Schlüssel weggelassen.\n\nExample: Die neue ID zurückgeben\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nBeendet die Operation mit einem Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Fehlername, Fehlermeldung oder `Error`. |\n| `error` | `String` | no |  | Fehlermeldung. |\n| `path` | `String` | no |  | Pfad des Felds. |\n| `index` | `Number` | no |  | Index des Elements in einem Array. |\n\nReturns: `$|Function`\n\nDie Argumente gehen an `$.error.push()`. Ohne Argumente gibt die Methode eine Funktion `function(err)` zurück, die du als Callback übergeben kannst.\n\nExample: Einen Fehler zurückgeben\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nGibt einen Callback zurück, der die Operation mit einem Erfolgsobjekt beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` fügt die Antwort hinzu; ein anderer Wert wird unverändert hinzugefügt. |\n\nReturns: `Function(err, response)`\n\nDie zurückgegebene Funktion `function(err, response)` fügt `err` hinzu und ruft zurück, oder ruft mit `{ success: true }` zurück. Ist `arg` auf `true` gesetzt, wird die Antwort als `value` hinzugefügt; jedes andere `arg` wird anstelle der Antwort hinzugefügt.\n\nExample: Den eingefügten Datensatz zurückgeben\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nGibt einen Callback zurück, der die Fehler für dich behandelt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Wird aufgerufen, wenn kein Fehler vorliegt. |\n\nReturns: `Function(err, a, b, c)`\n\nDie zurückgegebene Funktion `function(err, a, b, c)` ruft bei einem Fehler `$.invalid(err)` auf, sonst ruft sie `callback(a, b, c)` mit `$` als `this` auf.\n\nExample: Fehlerprüfungen sparen\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nBeendet die Operation mit einer Weiterleitung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Ziel-URL. |\n\nReturns: `$`\n\nWurde die Operation mit `controller.callback()` aufgerufen, leitet der Controller zu `url` weiter.\n\nExample: Nach dem Abmelden weiterleiten\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nBeendet die Operation, ohne den Callback aufzurufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` ruft `controller.custom()` nicht auf. |\n\nReturns: `$`\n\nNutze die Methode, wenn die Operation die Anfrage selbst beantwortet. Standardmäßig ruft sie auch `controller.custom()` auf, damit das Framework keine weitere Antwort sendet; `true` überspringt diesen Aufruf.\n\nExample: Die Anfrage selbst beantworten\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLiest oder schreibt ein Cookie der aktuellen Anfrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Cookies. |\n| `value` | `String` | no |  | Neuer Wert oder `null`, um es zu entfernen. |\n| `expire` | `String|Date` | no |  | Ablauf, zum Beispiel `'1 day'`. |\n| `options` | `Object` | no |  | Cookie-Optionen. |\n\nReturns: `String|$`\n\nNur mit `name` gibt sie den Wert des Cookies zurück. `null` als `value` entfernt das Cookie. Braucht einen Controller.\n\nExample: Ein Cookie schreiben\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nErsetzt `{key}`-Platzhalter in einem String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Text mit Platzhaltern. |\n| `data` | `Object` | no |  | Werte für `{data.key}`. |\n\nReturns: `String`\n\nUnterstützte Schlüssel beginnen mit `user.`, `data.`, `model.` oder `value.`, `query.` und `params.`. Unbekannte Schlüssel bleiben erhalten. Einfache oder doppelte geschweifte Klammern funktionieren. Die Methode gibt es auf dem `$` von Operationen und Tasks.\n\nExample: Eine Nachricht zusammenbauen\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nSchreibt einen Audit-Log-Eintrag für die Operation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Audit-Nachricht. |\n| `type` | `String` | no |  | Typ des Eintrags. |\n\nReturns: `$`\n\nRuft `AUDIT($, message, type)` mit Daten des Benutzers, der Anfrage und des Werts auf. Die Methode gibt es auf dem `$` von Operationen und Tasks.\n\nExample: Eine Änderung auditieren\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nErgebnisse der vorherigen Operationen in einer `RUN()`-Kette.\n\nReturns: `Object`\n\nEin Objekt mit einem Schlüssel pro Operation, die bereits beendet ist. Nur innerhalb von `RUN()` gesetzt.\n\nExample: Ein vorheriges Ergebnis verwenden\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformationen über eine `RUN()`-Kette.\n\nReturns: `Object`\n\n`$.meta.items` ist die Liste der Namen, `$.meta.current` die laufende Operation, `$.meta.prev` die vorherige und `$.meta.index` der Index der laufenden Operation. Nur innerhalb von `RUN()` gesetzt.\n\nExample: Die vorherige Operation prüfen\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nWie oft die laufende Operation in einer `RUN()`-Kette wiederholt wurde.\n\nReturns: `Number`\n\nBeginnt für jede Operation bei `0` und wächst jedes Mal, wenn die Option `repeat` sie erneut ausführt. Nur innerhalb von `RUN()` gesetzt.\n\nExample: Früh aufgeben\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDeklariert einen Task mit benannten Schritten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Tasks. |\n| `fn` | `Function(push)` | yes |  | Deklariert die Schritte mit `push(step, fn($, value))`. `null` entfernt den Task. |\n\n`fn` erhält `push(step, fn)`. Jeder Schritt erhält `$` und den Wert, und `this` ist `$`. `NEWTASK(name, null)` entfernt den Task. Lege Tasks im Verzeichnis `/tasks/` ab.\n\nExample: Ein Task mit zwei Schritten\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nErstellt einen Task und startet ihn bei einem Schritt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Tasks oder `'name/step'`. |\n| `step` | `String` | yes |  | Der erste Schritt. |\n| `callback` | `Function(err, response)` | yes |  | Wird aufgerufen, wenn der Task endet. |\n| `options` | `Controller|Object` | no |  | Controller oder `$`-Objekt, oder der Wert. |\n| `value` | `Object` | no | `{}` | Wert für `$.value`. |\n\nReturns: `TaskBuilder` Der Task, `$`.\n\n`name` und `step` können ein einziger String `'name/step'` sein; dann lauten die Argumente `TASK('name/step', callback, [options], [value])`. Ein Controller oder das `$` eines Schemas, einer Operation oder eines Tasks als `options` teilt dessen Anfrage und Fehler; jedes andere `options` wird als Wert verwendet. Der Schritt startet im nächsten Tick, sodass du vorher mit `$.push()` Schritte hinzufügen kannst. Ohne Schritt startest du ihn mit `$.exec()`.\n\nDer Name kann auch eine URL mit optionalem Ablauf sein, zum Beispiel `'https://example.com/task.js <1 hour>'`. Die Datei wird heruntergeladen und bis zum Ablauf zwischengespeichert.\n\nExample: Einen Task ausführen\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: Aus einer Schema-Aktion, mit \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nFührt den nächsten Schritt des Tasks aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Name des Schritts. Weitere Namen werden der Reihe nach versucht. |\n\nReturns: `$`\n\nFührt den ersten existierenden Schritt der Liste aus, zuerst unter den mit `$.push()` hinzugefügten Schritten und dann in der Task-Deklaration. Existiert keiner, endet der Task. Tut nach dem Ende des Tasks nichts.\n\nExample: Zum nächsten Schritt gehen\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nGibt einen Callback zurück, der zum nächsten Schritt geht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Name des nächsten Schritts. |\n\nReturns: `Function(err)`\n\nDie zurückgegebene Funktion `function(err)` ruft bei einem Fehler `$.invalid(err)` auf, sonst führt sie `step` aus oder beendet den Task, wenn `step` leer ist.\n\nExample: Nach einem Schreibvorgang fortfahren\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nBeendet den Task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | Die Antwort. |\n\nReturns: `$`\n\nRuft den Callback des Tasks mit den Fehlern (oder `null`) und `data` auf, oder mit `$.value`, wenn `data` leer ist.\n\nExample: Mit dem Wert beenden\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nGibt einen Callback zurück, der den Task beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` gibt die Daten des Callbacks zurück. |\n\nReturns: `Function(err, data)`\n\nDie zurückgegebene Funktion `function(err, data)` ruft bei einem Fehler `$.invalid(err)` auf, sonst beendet sie den Task mit `data`, wenn `send_value` gleich `true` ist, oder mit `$.value`.\n\nExample: Mit dem Ergebnis beenden\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nBeendet den Task mit einem Erfolgsobjekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Ein Wert, der als `value` hinzugefügt wird. |\n\nReturns: `$`\n\nBeendet den Task mit `{ success: true }`, plus `value`, wenn `data` gesetzt ist.\n\nExample: Mit Erfolg beenden\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nGibt einen Callback zurück, der den Task mit einem Erfolgsobjekt beendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` fügt die Daten des Callbacks als `value` hinzu. |\n\nReturns: `Function(err, data)`\n\nDie zurückgegebene Funktion `function(err, data)` ruft bei einem Fehler `$.invalid(err)` auf, sonst beendet sie den Task mit `{ success: true }`, plus `value: data`, wenn `send_value` gleich `true` ist.\n\nExample: Speichern und abschließen\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nBeendet den Task mit einem Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Fehlername oder `Error`. |\n| `msg` | `String` | no |  | Fehlermeldung. |\n\nReturns: `$`\n\nFügt den Fehler zu `$.error` hinzu und beendet den Task. Tut nach dem Ende des Tasks nichts.\n\nExample: Den Task stoppen\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nFügt nur diesem Task einen Schritt hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Name des Schritts. |\n| `fn` | `Function($, value)` | yes |  | Der Schritt. |\n\nReturns: `$`\n\nDer Schritt wird vor einem gleichnamigen Schritt der Task-Deklaration verwendet. Rufe die Methode auf dem von `TASK()` zurückgegebenen Task auf, bevor der erste Schritt läuft.\n\nExample: Einen Schritt überschreiben\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nStartet den Task bei einem Schritt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Der erste Schritt. |\n| `callback` | `Function(err, response)` | no |  | Wird aufgerufen, wenn der Task endet. |\n\nReturns: `$`\n\nSetzt den Callback, falls angegeben, und führt `step` aus. Nutze die Methode mit einem Task, der mit `TASK(name)` ohne Schritt erstellt wurde.\n\nExample: Später starten\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nSetzt den Callback des Tasks.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | Der Callback. |\n\nReturns: `$`\n\n`fn` wird einmal aufgerufen, wenn der Task endet, mit den Fehlern (oder `null`) und der Antwort.\n\nExample: Den Callback setzen\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nDer Wert, den alle Schritte des Tasks teilen.\n\nReturns: `Object`\n\n`$.model` ist derselbe Wert. Die Schritte erhalten ihn auch als zweites Argument. Er ist ein leeres Objekt, wenn kein Wert übergeben wurde.\n\nExample: Den Wert ändern\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nName des laufenden Schritts.\n\nReturns: `String`\n\n`$.prev` enthält den vorherigen Schritt und `$.name` den Namen des Tasks. Die Anfrage-Eigenschaften (`$.user`, `$.query`, `$.params`, `$.body` und andere) lesen aus dem Controller, wie bei Operationen.\n\nExample: Den Schritt protokollieren\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nVerpackt eine Funktion mit Callback in eine Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Eine Funktion, deren letztes Argument `callback(err, response)` ist. |\n| `a` | `Object` | no |  | Erstes Argument für `fn`. |\n| `b` | `Object` | no |  | Zweites Argument für `fn`. |\n\nReturns: `Promise`\n\nRuft `fn` mit den angegebenen Argumenten und einem Callback `function(err, response)` als letztem Argument auf. Die Promise wird mit `response` aufgelöst oder mit `err` abgelehnt. Leere Argumente werden nicht übergeben.\n\nExample: Auf einen Callback warten\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Eine Datei lesen\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nFügt einen Handler für einen Command hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Commands. |\n| `fn` | `Function(a, b, c, d)` | yes |  | Der Handler. `null` entfernt alle Handler. |\n\nEin Command kann mehrere Handler haben; jeder Aufruf fügt einen hinzu. `NEWCOMMAND(name, null)` entfernt alle Handler des Commands. Führe ihn mit `CMD()` aus.\n\nExample: Ein Command\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nFührt alle Handler eines Commands aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Commands. |\n| `a` | `Object` | no |  | Erstes Argument. |\n| `b` | `Object` | no |  | Zweites Argument. |\n| `c` | `Object` | no |  | Drittes Argument. |\n| `d` | `Object` | no |  | Viertes Argument. |\n\nÜbergibt jedem Handler bis zu vier Argumente. Tut nichts, wenn der Command keinen Handler hat. Zu den eingebauten Commands gehören `clear_viewscache`, `clear_smtpcache` und `refresh_tms`.\n\nExample: Einen Command ausführen\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nGibt eine Funktion zurück, die einen Command ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Commands. |\n| `a` | `Object` | no |  | Erstes Argument. |\n| `b` | `Object` | no |  | Zweites Argument. |\n| `c` | `Object` | no |  | Drittes Argument. |\n| `d` | `Object` | no |  | Viertes Argument. |\n\nReturns: `Function`\n\nDie zurückgegebene Funktion führt alle Handler mit den angegebenen Argumenten aus. Hat der Command keinen Handler, gibt sie `NOOP` zurück.\n\nExample: Einen Command später ausführen\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nInstalliert eine Erweiterung aus Quellcode oder einer URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Quellcode oder eine URL. |\n| `callback` | `Function(err, module)` | no |  | Wird aufgerufen, wenn die Erweiterung installiert ist. |\n| `extend` | `Function(module)` | no |  | Wird mit dem Modul aufgerufen, bevor es installiert wird. |\n\n`code` ist JavaScript, das `exports` setzt, oder eine URL, von der es heruntergeladen wird. Optionale Exporte: `id`, `name`, `install(next)`, `make()`, `done()` und `uninstall()`. Ohne `id` ist die ID ein Hash von `name` oder vom Code. Eine Erweiterung mit derselben ID wird zuerst entfernt. Der Code kann auch HTML mit einem `<script total>`-Block und `<file name=\"...\">`-Blöcken sein; `exports.files` ordnet dann jedem Dateinamen einen temporären Pfad zu. Die hinzugefügte Methode `remove()` deinstalliert die Erweiterung. Dateien im Verzeichnis `/extensions/` werden beim Start der App installiert.\n\nExample: Aus einem String installieren\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Von einer URL installieren\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nErstellt eine kleine Zustandsmaschine im Arbeitsspeicher: benannte Schritte, die mit `$.next()` zueinander wechseln.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)`, die die Schritte hinzufügt. |\n| `tasks` | `Object` | no | `{}` | Schritte als `{ name: function($, value) }`. |\n\nReturns: `Object` Der Workflow `$`.\n\n`WORKFLOW()` gibt ein `$`-Objekt zurück und übergibt es an `declaration($)`, wo du mit `$.push(name, fn)` Schritte hinzufügst. Jeder Schritt ist `function($, value)`. Es ist ein lokaler Helfer, kein registrierter Task: Nichts wird global gespeichert oder benannt.\n\n| Mitglied | Funktion |\n| --- | --- |\n| `$.push(name, fn)` | Fügt den Schritt `fn($, value)` hinzu |\n| `$.next(name, [value])` | Führt den Schritt `name` mit `value` aus; `$.trigger()` ist ein Alias. Ein unbekannter Name zerstört den Workflow |\n| `$.next2(name)` | Gibt `function(value)` zurück, die `$.next(name, value)` ausführt, für Callbacks |\n| `$.invalid(err)` | Ruft `$.error(err, $)` auf, wenn du es gesetzt hast, und zerstört dann den Workflow |\n| `$.current`, `$.prev` | Der Name des aktuellen und des vorherigen Schritts |\n| `$.tasks` | Die Schritte, als Objekt |\n| `$.clone()` | Ein neuer Workflow mit denselben Schritten |\n| `$.destroy()` | Beendet ihn; spätere Aufrufe von `$.next()` tun nichts |\n\n`declaration` kann `null` sein, wenn du die Schritte als `tasks` übergibst.\n\nExample: Schritte der Reihe nach\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZRH4aj61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Operaciones y tareas","summary":"Funciones globales y el objeto $ de las operaciones y tareas, además de comandos, extensiones y PROMISIFY().","markdown":"---\ntitle: Operaciones y tareas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operaciones y tareas\n\n> Funciones globales y el objeto $ de las operaciones y tareas, además de comandos, extensiones y PROMISIFY().\n\nLas operaciones (`NEWOPERATION()`, `OPERATION()`, `RUN()`) y las tareas (`NEWTASK()`, `TASK()`) contienen la lógica de negocio fuera de las rutas. Ambas reciben un objeto `$`; esta página enumera sus propiedades y métodos, y también los comandos, las extensiones y `PROMISIFY()`. La guía [Operaciones y tareas](../../guides/operations-and-tasks/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nRegistra una operación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la operación. |\n| `fn` | `Function($, value)` | yes |  | La operación. `null` la elimina. |\n| `repeat` | `Number` | no |  | Cuántas veces se vuelve a ejecutar la operación cuando termina con un error. |\n| `stop` | `Boolean` | no | `true` | Detiene una cadena `RUN()` cuando esta operación falla. |\n| `binderror` | `Boolean` | no | `false` | En una cadena `RUN()`, guarda la salida de error como respuesta de esta operación. |\n| `filter` | `String` | no |  | Esquema para la query string, usado por `$.filter`. |\n\nLa función recibe `$` y el valor. Debe terminar con `$.callback()`, `$.success()`, `$.invalid()` u otro método que llame al callback. Un booleano en lugar de `repeat` se interpreta como `stop`, y una cadena en cualquier posición opcional se interpreta como `filter`. Llamar a `NEWOPERATION(name, null)` elimina la operación. Pon las operaciones en el directorio `/operations/`.\n\nExample: Una operación\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Repetir tras un error\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nEjecuta una operación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la operación, o la URL de una operación remota. |\n| `value` | `Object` | no | `{}` | Valor para `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Se llama cuando termina la operación. |\n| `options` | `Object` | no |  | Opciones personalizadas, disponibles como `$.options`. |\n| `controller` | `Controller` | no |  | Controlador de la petición actual, o un objeto `$`. |\n\nEl callback recibe `err` (un `ErrorBuilder` o `null`), la respuesta y `options`. Cuando `value` es una función, es el callback y el valor es un objeto vacío. Un controlador o un objeto `$` pasado como `options` se usa como controlador. Una operación que no existe termina con el error `Operation \"name\" not found.`\n\nEl nombre también puede ser una URL con una expiración opcional, por ejemplo `'https://example.com/op.js <5 minutes>'` (también se aceptan `once` y `asap`). El archivo se descarga, se compila y se guarda en caché hasta que expira. Puede contener una declaración `NEWOPERATION()` o un módulo con `exports.install`, `exports.make` o `exports.exec`.\n\nExample: Llamar a una operación\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Desde una ruta\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nEjecuta varias operaciones una tras otra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Nombres de las operaciones, separados por comas. |\n| `value` | `Object` | no | `{}` | Valor compartido para `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Se llama cuando termina la cadena. |\n| `options` | `Object` | no |  | Opciones personalizadas, disponibles como `$.options`. |\n| `controller` | `Controller` | no |  | Controlador de la petición actual. |\n| `response_name` | `String` | no |  | Nombre de la operación cuya respuesta se devuelve sola. |\n\n`names` es una cadena separada por comas o un array. Todas las operaciones comparten un `$` y un `$.value`. El callback recibe `err`, la respuesta y el objeto `$`. La respuesta tiene una clave por operación; con `response_name` es solo la respuesta de esa operación. Cuando una operación falla y su opción `stop` es `true` (el valor por defecto), la cadena se detiene. Los nombres que no existen se omiten. Una cadena en lugar de `options` o `controller` se interpreta como `response_name`.\n\nExample: Encadenar dos operaciones\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Devolver una sola respuesta\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nLlama a una función para cada operación registrada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Se llama con el nombre de cada operación. |\n\nLa función recibe el nombre de cada operación.\n\nExample: Listar operaciones\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nEl valor pasado a la operación.\n\nReturns: `Object`\n\n`$.model` es el mismo valor. En una cadena `RUN()`, todas las operaciones comparten este objeto, así que los cambios son visibles para las operaciones siguientes.\n\nExample: Leer el valor\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nLas opciones pasadas a `OPERATION()` o `RUN()`.\n\nReturns: `Object`\n\nUn objeto vacío cuando no se pasaron opciones. `OPERATION()` lo vuelve a pasar como tercer argumento del callback.\n\nExample: Usar opciones\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nNombre de la operación en ejecución.\n\nReturns: `String`\n\nEn una cadena `RUN()` cambia con cada operación.\n\nExample: Registrar el nombre en el log\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\nEl `ErrorBuilder` de la operación.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` añade los errores aquí. En una cadena `RUN()`, cada operación recibe un `ErrorBuilder` nuevo.\n\nExample: Añadir varios errores\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nEl controlador pasado a la operación, o `undefined`.\n\nReturns: `Controller`\n\n`$.client` es el mismo valor. Las propiedades de la petición de `$` se leen de este controlador.\n\nExample: Comprobar si hay controlador\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nEl usuario de la petición actual.\n\nReturns: `Object`\n\nSe lee del controlador, o es `null` sin controlador. Las demás propiedades de la petición funcionan igual: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` y `$.test`.\n\nExample: Usar el usuario y la query\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertida por el esquema `filter` de la operación.\n\nReturns: `Object`\n\nEl esquema es el argumento `filter` de `NEWOPERATION()`, por ejemplo `'page:Number,q:String'`. Sin esquema, devuelve la query en bruto. Sin controlador, devuelve un objeto vacío.\n\nExample: Query con tipos\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina la operación y devuelve un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La respuesta, o un error. |\n\nReturns: `$`\n\nUn `Error` o un `ErrorBuilder` con errores se añade a `$.error`. También puedes llamarlo como `$.callback(err, value)`. Cuando la operación tiene errores y le quedan repeticiones de `repeat`, se vuelve a ejecutar.\n\nExample: Devolver un valor\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: Pasarlo como callback\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermina la operación con un objeto de éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | El flag de éxito. |\n| `value` | `Object` | no |  | Un valor añadido como `value`. |\n\nReturns: `$`\n\nDevuelve `{ success: true }` al callback. `$.success(value)` añade `value`. `$.success(false)` pone `success` a `false`. En una cadena `RUN()`, las claves vacías se omiten.\n\nExample: Devolver el nuevo id\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nTermina la operación con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Nombre del error, mensaje de error o `Error`. |\n| `error` | `String` | no |  | Mensaje de error. |\n| `path` | `String` | no |  | Ruta del campo. |\n| `index` | `Number` | no |  | Índice del elemento en un array. |\n\nReturns: `$|Function`\n\nLos argumentos van a `$.error.push()`. Sin argumentos, devuelve una función `function(err)` que puedes pasar como callback.\n\nExample: Devolver un error\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nDevuelve un callback que termina la operación con un objeto de éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` añade la respuesta; otro valor se añade tal cual. |\n\nReturns: `Function(err, response)`\n\nLa función devuelta `function(err, response)` añade `err` y llama al callback, o llama al callback con `{ success: true }`. Con `arg` en `true`, la respuesta se añade como `value`; cualquier otro `arg` se añade en lugar de la respuesta.\n\nExample: Devolver el registro insertado\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nDevuelve un callback que gestiona los errores por ti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Se llama cuando no hay error. |\n\nReturns: `Function(err, a, b, c)`\n\nLa función devuelta `function(err, a, b, c)` llama a `$.invalid(err)` cuando hay un error; si no, llama a `callback(a, b, c)` con `$` como `this`.\n\nExample: Omitir comprobaciones de errores\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermina la operación con una redirección.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL de destino. |\n\nReturns: `$`\n\nCuando la operación se llamó con `controller.callback()`, el controlador redirige a `url`.\n\nExample: Redirigir tras cerrar sesión\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nTermina la operación sin llamar al callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` no llama a `controller.custom()`. |\n\nReturns: `$`\n\nÚsalo cuando la operación responde a la petición por sí misma. Por defecto también llama a `controller.custom()`, para que el framework no envíe otra respuesta; `true` omite esa llamada.\n\nExample: Responder tú mismo a la petición\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLee o escribe una cookie de la petición actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cookie. |\n| `value` | `String` | no |  | Nuevo valor, o `null` para eliminarla. |\n| `expire` | `String|Date` | no |  | Expiración, por ejemplo `'1 day'`. |\n| `options` | `Object` | no |  | Opciones de la cookie. |\n\nReturns: `String|$`\n\nSolo con `name`, devuelve el valor de la cookie. `null` como `value` elimina la cookie. Necesita un controlador.\n\nExample: Escribir una cookie\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nReemplaza los placeholders `{key}` de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Texto con placeholders. |\n| `data` | `Object` | no |  | Valores para `{data.key}`. |\n\nReturns: `String`\n\nLas claves admitidas empiezan por `user.`, `data.`, `model.` o `value.`, `query.` y `params.`. Las claves desconocidas se mantienen. Funcionan llaves simples o dobles. Existe en el `$` de operaciones y tareas.\n\nExample: Construir un mensaje\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nEscribe una entrada en el log de auditoría para la operación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Mensaje de auditoría. |\n| `type` | `String` | no |  | Tipo de la entrada. |\n\nReturns: `$`\n\nLlama a `AUDIT($, message, type)` con datos del usuario, la petición y el valor. Existe en el `$` de operaciones y tareas.\n\nExample: Auditar un cambio\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nResultados de las operaciones anteriores en una cadena `RUN()`.\n\nReturns: `Object`\n\nUn objeto con una clave por cada operación que ya ha terminado. Solo se define dentro de `RUN()`.\n\nExample: Usar un resultado anterior\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformación sobre una cadena `RUN()`.\n\nReturns: `Object`\n\n`$.meta.items` es la lista de nombres, `$.meta.current` la operación en ejecución, `$.meta.prev` la anterior y `$.meta.index` el índice de la operación en ejecución. Solo se define dentro de `RUN()`.\n\nExample: Comprobar la operación anterior\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nCuántas veces se repitió la operación en ejecución en una cadena `RUN()`.\n\nReturns: `Number`\n\nEmpieza en `0` para cada operación y aumenta cada vez que la opción `repeat` la vuelve a ejecutar. Solo se define dentro de `RUN()`.\n\nExample: Rendirse pronto\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDeclara una tarea con pasos con nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la tarea. |\n| `fn` | `Function(push)` | yes |  | Declara los pasos con `push(step, fn($, value))`. `null` elimina la tarea. |\n\n`fn` recibe `push(step, fn)`. Cada paso recibe `$` y el valor, y `this` es `$`. `NEWTASK(name, null)` elimina la tarea. Pon las tareas en el directorio `/tasks/`.\n\nExample: Una tarea con dos pasos\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nCrea una tarea y la inicia en un paso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la tarea, o `'name/step'`. |\n| `step` | `String` | yes |  | El primer paso. |\n| `callback` | `Function(err, response)` | yes |  | Se llama cuando termina la tarea. |\n| `options` | `Controller|Object` | no |  | Controlador u objeto `$`, o el valor. |\n| `value` | `Object` | no | `{}` | Valor para `$.value`. |\n\nReturns: `TaskBuilder` La tarea, `$`.\n\n`name` y `step` pueden ser una sola cadena `'name/step'`; entonces los argumentos son `TASK('name/step', callback, [options], [value])`. Un controlador o el `$` de un esquema, una operación o una tarea como `options` comparte su petición y sus errores; cualquier otro `options` se usa como valor. El paso empieza en el siguiente tick, así que antes puedes añadir pasos con `$.push()`. Sin paso, iníciala con `$.exec()`.\n\nEl nombre también puede ser una URL con una expiración opcional, por ejemplo `'https://example.com/task.js <1 hour>'`. El archivo se descarga y se guarda en caché hasta que expira.\n\nExample: Ejecutar una tarea\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: Desde una acción de esquema, con \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nEjecuta el siguiente paso de la tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nombre del paso. Los demás nombres se prueban en orden. |\n\nReturns: `$`\n\nEjecuta el primer paso de la lista que existe, buscando primero en los pasos añadidos con `$.push()` y después en la declaración de la tarea. Cuando no existe ninguno, la tarea termina. No hace nada después de que la tarea haya terminado.\n\nExample: Ir al siguiente paso\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nDevuelve un callback que va al siguiente paso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Nombre del siguiente paso. |\n\nReturns: `Function(err)`\n\nLa función devuelta `function(err)` llama a `$.invalid(err)` si hay un error; si no, ejecuta `step`, o termina la tarea cuando `step` está vacío.\n\nExample: Continuar tras una escritura\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nTermina la tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | La respuesta. |\n\nReturns: `$`\n\nLlama al callback de la tarea con los errores (o `null`) y `data`, o `$.value` cuando `data` está vacío.\n\nExample: Terminar con el valor\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nDevuelve un callback que termina la tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` devuelve los datos del callback. |\n\nReturns: `Function(err, data)`\n\nLa función devuelta `function(err, data)` llama a `$.invalid(err)` si hay un error; si no, termina la tarea con `data` cuando `send_value` es `true`, o con `$.value`.\n\nExample: Terminar con el resultado\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nTermina la tarea con un objeto de éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Un valor añadido como `value`. |\n\nReturns: `$`\n\nTermina la tarea con `{ success: true }`, más `value` cuando `data` está definido.\n\nExample: Terminar con éxito\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nDevuelve un callback que termina la tarea con un objeto de éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` añade los datos del callback como `value`. |\n\nReturns: `Function(err, data)`\n\nLa función devuelta `function(err, data)` llama a `$.invalid(err)` si hay un error; si no, termina la tarea con `{ success: true }`, más `value: data` cuando `send_value` es `true`.\n\nExample: Guardar y terminar\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nTermina la tarea con un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Nombre del error o `Error`. |\n| `msg` | `String` | no |  | Mensaje de error. |\n\nReturns: `$`\n\nAñade el error a `$.error` y termina la tarea. No hace nada después de que la tarea haya terminado.\n\nExample: Detener la tarea\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nAñade un paso solo a esta tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nombre del paso. |\n| `fn` | `Function($, value)` | yes |  | El paso. |\n\nReturns: `$`\n\nEl paso se usa antes que un paso con el mismo nombre de la declaración de la tarea. Llámalo sobre la tarea que devuelve `TASK()`, antes de que se ejecute el primer paso.\n\nExample: Sobrescribir un paso\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nInicia la tarea en un paso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | El primer paso. |\n| `callback` | `Function(err, response)` | no |  | Se llama cuando termina la tarea. |\n\nReturns: `$`\n\nDefine el callback si se indica y ejecuta `step`. Úsalo con una tarea creada con `TASK(name)` sin paso.\n\nExample: Iniciar más tarde\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nDefine el callback de la tarea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | El callback. |\n\nReturns: `$`\n\n`fn` se llama una vez cuando termina la tarea, con los errores (o `null`) y la respuesta.\n\nExample: Definir el callback\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nEl valor compartido por todos los pasos de la tarea.\n\nReturns: `Object`\n\n`$.model` es el mismo valor. Los pasos también lo reciben como segundo argumento. Es un objeto vacío cuando no se pasó ningún valor.\n\nExample: Cambiar el valor\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nNombre del paso en ejecución.\n\nReturns: `String`\n\n`$.prev` contiene el paso anterior y `$.name` el nombre de la tarea. Las propiedades de la petición (`$.user`, `$.query`, `$.params`, `$.body` y otras) se leen del controlador, como en las operaciones.\n\nExample: Registrar el paso en el log\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nEnvuelve una función con callback en una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una función cuyo último argumento es `callback(err, response)`. |\n| `a` | `Object` | no |  | Primer argumento para `fn`. |\n| `b` | `Object` | no |  | Segundo argumento para `fn`. |\n\nReturns: `Promise`\n\nLlama a `fn` con los argumentos dados y un callback `function(err, response)` como último argumento. La promesa se resuelve con `response` o se rechaza con `err`. Los argumentos vacíos no se pasan.\n\nExample: Esperar con await un callback\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Leer un archivo\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nAñade un manejador para un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del comando. |\n| `fn` | `Function(a, b, c, d)` | yes |  | El manejador. `null` elimina todos los manejadores. |\n\nUn comando puede tener varios manejadores; cada llamada añade uno. `NEWCOMMAND(name, null)` elimina todos los manejadores del comando. Ejecútalo con `CMD()`.\n\nExample: Un comando\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nEjecuta todos los manejadores de un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del comando. |\n| `a` | `Object` | no |  | Primer argumento. |\n| `b` | `Object` | no |  | Segundo argumento. |\n| `c` | `Object` | no |  | Tercer argumento. |\n| `d` | `Object` | no |  | Cuarto argumento. |\n\nPasa hasta cuatro argumentos a cada manejador. No hace nada cuando el comando no tiene manejador. Entre los comandos integrados están `clear_viewscache`, `clear_smtpcache` y `refresh_tms`.\n\nExample: Ejecutar un comando\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nDevuelve una función que ejecuta un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del comando. |\n| `a` | `Object` | no |  | Primer argumento. |\n| `b` | `Object` | no |  | Segundo argumento. |\n| `c` | `Object` | no |  | Tercer argumento. |\n| `d` | `Object` | no |  | Cuarto argumento. |\n\nReturns: `Function`\n\nLa función devuelta ejecuta todos los manejadores con los argumentos indicados. Cuando el comando no tiene manejador, devuelve `NOOP`.\n\nExample: Ejecutar un comando más tarde\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nInstala una extensión desde código fuente o una URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Código fuente, o una URL. |\n| `callback` | `Function(err, module)` | no |  | Se llama cuando la extensión está instalada. |\n| `extend` | `Function(module)` | no |  | Se llama con el módulo antes de instalarlo. |\n\n`code` es JavaScript que define `exports`, o una URL desde la que descargarlo. Exports opcionales: `id`, `name`, `install(next)`, `make()`, `done()` y `uninstall()`. Sin `id`, el id es un hash de `name` o del código. Una extensión con el mismo id se elimina primero. El código también puede ser HTML con un bloque `<script total>` y bloques `<file name=\"...\">`; entonces `exports.files` asigna a cada nombre de archivo una ruta temporal. El método añadido `remove()` desinstala la extensión. Los archivos del directorio `/extensions/` se instalan al arrancar la aplicación.\n\nExample: Instalar desde una cadena\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Instalar desde una URL\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nCrea una pequeña máquina de estados en memoria: pasos con nombre que pasan de uno a otro con `$.next()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)` que añade los pasos. |\n| `tasks` | `Object` | no | `{}` | Pasos como `{ name: function($, value) }`. |\n\nReturns: `Object` El workflow `$`.\n\n`WORKFLOW()` devuelve un objeto `$` y lo pasa a `declaration($)`, donde añades pasos con `$.push(name, fn)`. Cada paso es `function($, value)`. Es una utilidad local, no una tarea registrada: no se guarda ni se nombra nada a nivel global.\n\n| Miembro | Qué hace |\n| --- | --- |\n| `$.push(name, fn)` | Añade el paso `fn($, value)` |\n| `$.next(name, [value])` | Ejecuta el paso `name` con `value`; `$.trigger()` es un alias. Un nombre desconocido destruye el workflow |\n| `$.next2(name)` | Devuelve `function(value)` que ejecuta `$.next(name, value)`, para callbacks |\n| `$.invalid(err)` | Llama a `$.error(err, $)` cuando lo defines y luego destruye el workflow |\n| `$.current`, `$.prev` | El nombre del paso actual y del anterior |\n| `$.tasks` | Los pasos, como objeto |\n| `$.clone()` | Un workflow nuevo con los mismos pasos |\n| `$.destroy()` | Lo termina; las llamadas posteriores a `$.next()` no hacen nada |\n\n`declaration` puede ser `null` cuando pasas los pasos como `tasks`.\n\nExample: Pasos en orden\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZRH4aj61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Opérations et tâches","summary":"Fonctions globales et objet $ des opérations et des tâches, ainsi que les commandes, les extensions et PROMISIFY().","markdown":"---\ntitle: \"Opérations et tâches\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Opérations et tâches\n\n> Fonctions globales et objet $ des opérations et des tâches, ainsi que les commandes, les extensions et PROMISIFY().\n\nLes opérations (`NEWOPERATION()`, `OPERATION()`, `RUN()`) et les tâches (`NEWTASK()`, `TASK()`) contiennent la logique métier en dehors des routes. Toutes deux reçoivent un objet `$` ; cette page liste ses propriétés et ses méthodes, ainsi que les commandes, les extensions et `PROMISIFY()`. Le guide [Opérations et tâches](../../guides/operations-and-tasks/) explique comment les utiliser avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nEnregistre une opération.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'opération. |\n| `fn` | `Function($, value)` | yes |  | L'opération. `null` la supprime. |\n| `repeat` | `Number` | no |  | Le nombre de fois où l'opération est exécutée de nouveau quand elle se termine par une erreur. |\n| `stop` | `Boolean` | no | `true` | Arrête une chaîne `RUN()` quand cette opération échoue. |\n| `binderror` | `Boolean` | no | `false` | Dans une chaîne `RUN()`, stocke la sortie d'erreur comme réponse de cette opération. |\n| `filter` | `String` | no |  | Schéma pour la query string, utilisé par `$.filter`. |\n\nLa fonction reçoit `$` et la valeur. Elle doit se terminer par `$.callback()`, `$.success()`, `$.invalid()` ou une autre méthode qui appelle le callback. Un booléen à la place de `repeat` est lu comme `stop`, et une chaîne à n'importe quelle position facultative est lue comme `filter`. Appeler `NEWOPERATION(name, null)` supprime l'opération. Place les opérations dans le répertoire `/operations/`.\n\nExample: Une opération\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Répéter après une erreur\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nExécute une opération.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'opération, ou URL d'une opération distante. |\n| `value` | `Object` | no | `{}` | Valeur pour `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Appelé quand l'opération se termine. |\n| `options` | `Object` | no |  | Options personnalisées, disponibles dans `$.options`. |\n| `controller` | `Controller` | no |  | Contrôleur de la requête courante, ou un objet `$`. |\n\nLe callback reçoit `err` (un `ErrorBuilder` ou `null`), la réponse et `options`. Quand `value` est une fonction, c'est le callback et la valeur est un objet vide. Un contrôleur ou un objet `$` passé comme `options` est utilisé comme contrôleur. Une opération manquante se termine par l'erreur `Operation \"name\" not found.`\n\nLe nom peut aussi être une URL avec une expiration facultative, par exemple `'https://example.com/op.js <5 minutes>'` (`once` et `asap` sont aussi acceptés). Le fichier est téléchargé, compilé et mis en cache jusqu'à son expiration. Il peut contenir une déclaration `NEWOPERATION()` ou un module avec `exports.install`, `exports.make` ou `exports.exec`.\n\nExample: Appeler une opération\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Depuis une route\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nExécute plusieurs opérations l'une après l'autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Noms des opérations, séparés par des virgules. |\n| `value` | `Object` | no | `{}` | Valeur partagée pour `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Appelé quand la chaîne se termine. |\n| `options` | `Object` | no |  | Options personnalisées, disponibles dans `$.options`. |\n| `controller` | `Controller` | no |  | Contrôleur de la requête courante. |\n| `response_name` | `String` | no |  | Nom de l'opération dont la réponse est renvoyée seule. |\n\n`names` est une chaîne séparée par des virgules ou un tableau. Toutes les opérations partagent un même `$` et un même `$.value`. Le callback reçoit `err`, la réponse et l'objet `$`. La réponse a une clé par opération ; avec `response_name`, c'est uniquement la réponse de cette opération. Quand une opération échoue et que son option `stop` vaut `true` (la valeur par défaut), la chaîne s'arrête. Les noms inexistants sont ignorés. Une chaîne à la place de `options` ou `controller` est lue comme `response_name`.\n\nExample: Enchaîner deux opérations\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Renvoyer une seule réponse\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nAppelle une fonction pour chaque opération enregistrée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Appelée avec le nom de chaque opération. |\n\nLa fonction reçoit le nom de chaque opération.\n\nExample: Lister les opérations\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nLa valeur passée à l'opération.\n\nReturns: `Object`\n\n`$.model` est la même valeur. Dans une chaîne `RUN()`, toutes les opérations partagent cet objet : les modifications sont donc visibles par les opérations suivantes.\n\nExample: Lire la valeur\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nLes options passées à `OPERATION()` ou `RUN()`.\n\nReturns: `Object`\n\nUn objet vide quand aucune option n'a été passée. `OPERATION()` la repasse comme troisième argument du callback.\n\nExample: Utiliser les options\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nNom de l'opération en cours.\n\nReturns: `String`\n\nDans une chaîne `RUN()`, il change à chaque opération.\n\nExample: Journaliser le nom\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\nL'`ErrorBuilder` de l'opération.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` y ajoute les erreurs. Dans une chaîne `RUN()`, chaque opération reçoit un nouvel `ErrorBuilder`.\n\nExample: Ajouter plusieurs erreurs\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nLe contrôleur passé à l'opération, ou `undefined`.\n\nReturns: `Controller`\n\n`$.client` est la même valeur. Les propriétés de requête de `$` sont lues depuis ce contrôleur.\n\nExample: Vérifier la présence d'un contrôleur\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nL'utilisateur de la requête courante.\n\nReturns: `Object`\n\nLu depuis le contrôleur, ou `null` sans contrôleur. Les autres propriétés de la requête fonctionnent de la même façon : `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` et `$.test`.\n\nExample: Utiliser l'utilisateur et la query\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertie par le schéma `filter` de l'opération.\n\nReturns: `Object`\n\nLe schéma est l'argument `filter` de `NEWOPERATION()`, par exemple `'page:Number,q:String'`. Sans schéma, elle renvoie la query brute. Sans contrôleur, elle renvoie un objet vide.\n\nExample: Query typée\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermine l'opération et renvoie une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La réponse, ou une erreur. |\n\nReturns: `$`\n\nUn `Error` ou un `ErrorBuilder` contenant des erreurs est ajouté à `$.error`. Tu peux aussi l'appeler sous la forme `$.callback(err, value)`. Quand l'opération a des erreurs et qu'il reste des `repeat`, elle s'exécute de nouveau à la place.\n\nExample: Renvoyer une valeur\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: La passer comme callback\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermine l'opération avec un objet de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Le flag de succès. |\n| `value` | `Object` | no |  | Une valeur ajoutée en tant que `value`. |\n\nReturns: `$`\n\nRenvoie `{ success: true }` au callback. `$.success(value)` ajoute `value`. `$.success(false)` met `success` à `false`. Dans une chaîne `RUN()`, les clés vides sont omises.\n\nExample: Renvoyer le nouvel id\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nTermine l'opération avec une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Nom de l'erreur, message d'erreur ou `Error`. |\n| `error` | `String` | no |  | Message d'erreur. |\n| `path` | `String` | no |  | Chemin du champ. |\n| `index` | `Number` | no |  | Index de l'élément dans un tableau. |\n\nReturns: `$|Function`\n\nLes arguments sont passés à `$.error.push()`. Sans arguments, elle renvoie une fonction `function(err)` que tu peux passer comme callback.\n\nExample: Renvoyer une erreur\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nRenvoie un callback qui termine l'opération avec un objet de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` ajoute la réponse ; une autre valeur est ajoutée telle quelle. |\n\nReturns: `Function(err, response)`\n\nLa fonction renvoyée `function(err, response)` ajoute `err` et appelle le callback, ou appelle le callback avec `{ success: true }`. Avec `arg` à `true`, la réponse est ajoutée en tant que `value` ; tout autre `arg` est ajouté à la place de la réponse.\n\nExample: Renvoyer l'enregistrement inséré\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nRenvoie un callback qui gère les erreurs à ta place.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Appelé quand il n'y a pas d'erreur. |\n\nReturns: `Function(err, a, b, c)`\n\nLa fonction renvoyée `function(err, a, b, c)` appelle `$.invalid(err)` en cas d'erreur, sinon elle appelle `callback(a, b, c)` avec `$` comme `this`.\n\nExample: Éviter les vérifications d'erreurs\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermine l'opération par une redirection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL cible. |\n\nReturns: `$`\n\nQuand l'opération a été appelée avec `controller.callback()`, le contrôleur redirige vers `url`.\n\nExample: Rediriger après la déconnexion\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nTermine l'opération sans appeler le callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` n'appelle pas `controller.custom()`. |\n\nReturns: `$`\n\nUtilise-la quand l'opération répond elle-même à la requête. Par défaut, elle appelle aussi `controller.custom()`, afin que le framework n'envoie pas d'autre réponse ; `true` évite cet appel.\n\nExample: Répondre toi-même à la requête\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLit ou écrit un cookie de la requête courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du cookie. |\n| `value` | `String` | no |  | Nouvelle valeur, ou `null` pour le supprimer. |\n| `expire` | `String|Date` | no |  | Expiration, par exemple `'1 day'`. |\n| `options` | `Object` | no |  | Options du cookie. |\n\nReturns: `String|$`\n\nAvec seulement `name`, elle renvoie la valeur du cookie. `null` comme `value` supprime le cookie. Nécessite un contrôleur.\n\nExample: Écrire un cookie\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nRemplace les placeholders `{key}` dans une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Texte contenant des placeholders. |\n| `data` | `Object` | no |  | Valeurs pour `{data.key}`. |\n\nReturns: `String`\n\nLes clés prises en charge commencent par `user.`, `data.`, `model.` ou `value.`, `query.` et `params.`. Les clés inconnues sont conservées. Les accolades simples ou doubles fonctionnent. Elle existe sur le `$` des opérations et des tâches.\n\nExample: Construire un message\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nÉcrit une entrée de journal d'audit pour l'opération.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Message d'audit. |\n| `type` | `String` | no |  | Type de l'entrée. |\n\nReturns: `$`\n\nAppelle `AUDIT($, message, type)` avec des données provenant de l'utilisateur, de la requête et de la valeur. Elle existe sur le `$` des opérations et des tâches.\n\nExample: Auditer une modification\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nRésultats des opérations précédentes dans une chaîne `RUN()`.\n\nReturns: `Object`\n\nUn objet avec une clé par opération déjà terminée. Défini uniquement dans `RUN()`.\n\nExample: Utiliser un résultat précédent\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformations sur une chaîne `RUN()`.\n\nReturns: `Object`\n\n`$.meta.items` est la liste des noms, `$.meta.current` l'opération en cours, `$.meta.prev` la précédente et `$.meta.index` l'index de l'opération en cours. Défini uniquement dans `RUN()`.\n\nExample: Vérifier l'opération précédente\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nLe nombre de répétitions de l'opération en cours dans une chaîne `RUN()`.\n\nReturns: `Number`\n\nCommence à `0` pour chaque opération et augmente chaque fois que l'option `repeat` l'exécute de nouveau. Défini uniquement dans `RUN()`.\n\nExample: Abandonner plus tôt\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDéclare une tâche avec des étapes nommées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la tâche. |\n| `fn` | `Function(push)` | yes |  | Déclare les étapes avec `push(step, fn($, value))`. `null` supprime la tâche. |\n\n`fn` reçoit `push(step, fn)`. Chaque étape reçoit `$` et la valeur, et `this` est `$`. `NEWTASK(name, null)` supprime la tâche. Place les tâches dans le répertoire `/tasks/`.\n\nExample: Une tâche à deux étapes\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nCrée une tâche et la démarre à une étape.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la tâche, ou `'name/step'`. |\n| `step` | `String` | yes |  | La première étape. |\n| `callback` | `Function(err, response)` | yes |  | Appelé quand la tâche se termine. |\n| `options` | `Controller|Object` | no |  | Contrôleur ou objet `$`, ou la valeur. |\n| `value` | `Object` | no | `{}` | Valeur pour `$.value`. |\n\nReturns: `TaskBuilder` La tâche, `$`.\n\n`name` et `step` peuvent former une seule chaîne `'name/step'` ; les arguments sont alors `TASK('name/step', callback, [options], [value])`. Un contrôleur ou le `$` d'un schéma, d'une opération ou d'une tâche passé comme `options` partage sa requête et ses erreurs ; toute autre valeur de `options` est utilisée comme valeur. L'étape démarre au tick suivant : tu peux donc d'abord ajouter des étapes avec `$.push()`. Sans étape, démarre-la avec `$.exec()`.\n\nLe nom peut aussi être une URL avec une expiration facultative, par exemple `'https://example.com/task.js <1 hour>'`. Le fichier est téléchargé et mis en cache jusqu'à son expiration.\n\nExample: Exécuter une tâche\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: Depuis une action de schéma, avec \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nExécute l'étape suivante de la tâche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nom de l'étape. D'autres noms sont essayés dans l'ordre. |\n\nReturns: `$`\n\nExécute la première étape de la liste qui existe, d'abord parmi les étapes ajoutées avec `$.push()`, puis dans la déclaration de la tâche. Quand aucune n'existe, la tâche se termine. Ne fait rien une fois la tâche terminée.\n\nExample: Passer à l'étape suivante\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nRenvoie un callback qui passe à l'étape suivante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Nom de l'étape suivante. |\n\nReturns: `Function(err)`\n\nLa fonction renvoyée `function(err)` appelle `$.invalid(err)` en cas d'erreur, sinon elle exécute `step`, ou termine la tâche quand `step` est vide.\n\nExample: Continuer après une écriture\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nTermine la tâche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | La réponse. |\n\nReturns: `$`\n\nAppelle le callback de la tâche avec les erreurs (ou `null`) et `data`, ou `$.value` quand `data` est vide.\n\nExample: Terminer avec la valeur\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nRenvoie un callback qui termine la tâche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` renvoie les données du callback. |\n\nReturns: `Function(err, data)`\n\nLa fonction renvoyée `function(err, data)` appelle `$.invalid(err)` en cas d'erreur, sinon elle termine la tâche avec `data` quand `send_value` vaut `true`, ou avec `$.value`.\n\nExample: Terminer avec le résultat\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nTermine la tâche avec un objet de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Une valeur ajoutée en tant que `value`. |\n\nReturns: `$`\n\nTermine la tâche avec `{ success: true }`, plus `value` quand `data` est défini.\n\nExample: Terminer avec succès\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nRenvoie un callback qui termine la tâche avec un objet de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` ajoute les données du callback en tant que `value`. |\n\nReturns: `Function(err, data)`\n\nLa fonction renvoyée `function(err, data)` appelle `$.invalid(err)` en cas d'erreur, sinon elle termine la tâche avec `{ success: true }`, plus `value: data` quand `send_value` vaut `true`.\n\nExample: Enregistrer et terminer\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nTermine la tâche avec une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Nom de l'erreur ou `Error`. |\n| `msg` | `String` | no |  | Message d'erreur. |\n\nReturns: `$`\n\nAjoute l'erreur à `$.error` et termine la tâche. Ne fait rien une fois la tâche terminée.\n\nExample: Arrêter la tâche\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nAjoute une étape à cette tâche uniquement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nom de l'étape. |\n| `fn` | `Function($, value)` | yes |  | L'étape. |\n\nReturns: `$`\n\nL'étape est utilisée avant une étape du même nom dans la déclaration de la tâche. Appelle-la sur la tâche que renvoie `TASK()`, avant l'exécution de la première étape.\n\nExample: Remplacer une étape\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nDémarre la tâche à une étape.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | La première étape. |\n| `callback` | `Function(err, response)` | no |  | Appelé quand la tâche se termine. |\n\nReturns: `$`\n\nDéfinit le callback s'il est fourni et exécute `step`. Utilise-la avec une tâche créée par `TASK(name)` sans étape.\n\nExample: Démarrer plus tard\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nDéfinit le callback de la tâche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | Le callback. |\n\nReturns: `$`\n\n`fn` est appelée une fois quand la tâche se termine, avec les erreurs (ou `null`) et la réponse.\n\nExample: Définir le callback\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nLa valeur partagée par toutes les étapes de la tâche.\n\nReturns: `Object`\n\n`$.model` est la même valeur. Les étapes la reçoivent aussi comme deuxième argument. C'est un objet vide quand aucune valeur n'a été passée.\n\nExample: Modifier la valeur\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nNom de l'étape en cours.\n\nReturns: `String`\n\n`$.prev` contient l'étape précédente et `$.name` le nom de la tâche. Les propriétés de la requête (`$.user`, `$.query`, `$.params`, `$.body` et d'autres) sont lues depuis le contrôleur, comme dans les opérations.\n\nExample: Journaliser l'étape\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nEnveloppe une fonction à callback dans une Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Une fonction dont le dernier argument est `callback(err, response)`. |\n| `a` | `Object` | no |  | Premier argument pour `fn`. |\n| `b` | `Object` | no |  | Deuxième argument pour `fn`. |\n\nReturns: `Promise`\n\nAppelle `fn` avec les arguments donnés et un callback `function(err, response)` en dernier argument. La promesse est résolue avec `response` ou rejetée avec `err`. Les arguments vides ne sont pas transmis.\n\nExample: Attendre un callback avec await\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Lire un fichier\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nAjoute un gestionnaire pour une commande.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la commande. |\n| `fn` | `Function(a, b, c, d)` | yes |  | Le gestionnaire. `null` supprime tous les gestionnaires. |\n\nUne commande peut avoir plusieurs gestionnaires ; chaque appel en ajoute un. `NEWCOMMAND(name, null)` supprime tous les gestionnaires de la commande. Exécute-la avec `CMD()`.\n\nExample: Une commande\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nExécute tous les gestionnaires d'une commande.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la commande. |\n| `a` | `Object` | no |  | Premier argument. |\n| `b` | `Object` | no |  | Deuxième argument. |\n| `c` | `Object` | no |  | Troisième argument. |\n| `d` | `Object` | no |  | Quatrième argument. |\n\nPasse jusqu'à quatre arguments à chaque gestionnaire. Ne fait rien quand la commande n'a pas de gestionnaire. Les commandes intégrées comprennent `clear_viewscache`, `clear_smtpcache` et `refresh_tms`.\n\nExample: Exécuter une commande\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nRenvoie une fonction qui exécute une commande.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la commande. |\n| `a` | `Object` | no |  | Premier argument. |\n| `b` | `Object` | no |  | Deuxième argument. |\n| `c` | `Object` | no |  | Troisième argument. |\n| `d` | `Object` | no |  | Quatrième argument. |\n\nReturns: `Function`\n\nLa fonction renvoyée exécute tous les gestionnaires avec les arguments donnés. Quand la commande n'a pas de gestionnaire, elle renvoie `NOOP`.\n\nExample: Exécuter une commande plus tard\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nInstalle une extension depuis du code source ou une URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Code source, ou une URL. |\n| `callback` | `Function(err, module)` | no |  | Appelé quand l'extension est installée. |\n| `extend` | `Function(module)` | no |  | Appelé avec le module avant son installation. |\n\n`code` est du JavaScript qui définit `exports`, ou une URL d'où le télécharger. Exports facultatifs : `id`, `name`, `install(next)`, `make()`, `done()` et `uninstall()`. Sans `id`, l'id est un hachage de `name` ou du code. Une extension ayant le même id est d'abord supprimée. Le code peut aussi être du HTML avec un bloc `<script total>` et des blocs `<file name=\"...\">` ; `exports.files` associe alors chaque nom de fichier à un chemin temporaire. La méthode ajoutée `remove()` désinstalle l'extension. Les fichiers du répertoire `/extensions/` sont installés au démarrage de l'application.\n\nExample: Installer depuis une chaîne\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Installer depuis une URL\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nCrée une petite machine à états en mémoire : des étapes nommées qui passent de l'une à l'autre avec `$.next()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)` qui ajoute les étapes. |\n| `tasks` | `Object` | no | `{}` | Étapes sous la forme `{ name: function($, value) }`. |\n\nReturns: `Object` Le workflow `$`.\n\n`WORKFLOW()` renvoie un objet `$` et le passe à `declaration($)`, où tu ajoutes des étapes avec `$.push(name, fn)`. Chaque étape est `function($, value)`. C'est un utilitaire local, pas une tâche enregistrée : rien n'est stocké ni nommé globalement.\n\n| Membre | Rôle |\n| --- | --- |\n| `$.push(name, fn)` | Ajoute l'étape `fn($, value)` |\n| `$.next(name, [value])` | Exécute l'étape `name` avec `value` ; `$.trigger()` est un alias. Un nom inconnu détruit le workflow |\n| `$.next2(name)` | Renvoie `function(value)` qui exécute `$.next(name, value)`, pour les callbacks |\n| `$.invalid(err)` | Appelle `$.error(err, $)` si tu l'as définie, puis détruit le workflow |\n| `$.current`, `$.prev` | Le nom de l'étape courante et de l'étape précédente |\n| `$.tasks` | Les étapes, sous forme d'objet |\n| `$.clone()` | Un nouveau workflow avec les mêmes étapes |\n| `$.destroy()` | Le termine ; les appels ultérieurs de `$.next()` ne font rien |\n\n`declaration` peut valoir `null` quand tu passes les étapes dans `tasks`.\n\nExample: Étapes dans l'ordre\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZRH4aj61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Operazioni e task","summary":"Funzioni globali e l'oggetto $ di operazioni e task, più comandi, estensioni e PROMISIFY().","markdown":"---\ntitle: Operazioni e task\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operazioni e task\n\n> Funzioni globali e l'oggetto $ di operazioni e task, più comandi, estensioni e PROMISIFY().\n\nLe operazioni (`NEWOPERATION()`, `OPERATION()`, `RUN()`) e i task (`NEWTASK()`, `TASK()`) contengono la logica di business al di fuori delle route. Entrambi ricevono un oggetto `$`; questa pagina elenca le sue proprietà e i suoi metodi, oltre a comandi, estensioni e `PROMISIFY()`. La guida [Operazioni e task](../../guides/operations-and-tasks/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nRegistra un'operazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'operazione. |\n| `fn` | `Function($, value)` | yes |  | L'operazione. `null` la rimuove. |\n| `repeat` | `Number` | no |  | Quante volte eseguire di nuovo l'operazione quando termina con un errore. |\n| `stop` | `Boolean` | no | `true` | Ferma una catena `RUN()` quando questa operazione fallisce. |\n| `binderror` | `Boolean` | no | `false` | In una catena `RUN()`, memorizza l'output dell'errore come risposta di questa operazione. |\n| `filter` | `String` | no |  | Schema per la query string, usato da `$.filter`. |\n\nLa funzione riceve `$` e il valore. Deve terminare con `$.callback()`, `$.success()`, `$.invalid()` o un altro metodo che chiama la callback. Un booleano al posto di `repeat` viene letto come `stop`, e una stringa in qualsiasi posizione facoltativa viene letta come `filter`. Chiamare `NEWOPERATION(name, null)` rimuove l'operazione. Metti le operazioni nella directory `/operations/`.\n\nExample: Un'operazione\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Ripetere dopo un errore\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nEsegue una singola operazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome dell'operazione, oppure URL di un'operazione remota. |\n| `value` | `Object` | no | `{}` | Valore per `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Chiamata quando l'operazione termina. |\n| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |\n| `controller` | `Controller` | no |  | Controller della richiesta corrente, oppure un oggetto `$`. |\n\nLa callback riceve `err` (un `ErrorBuilder` o `null`), la risposta e `options`. Quando `value` è una funzione, è la callback e il valore è un oggetto vuoto. Un controller o un oggetto `$` passato come `options` viene usato come controller. Un'operazione mancante termina con l'errore `Operation \"name\" not found.`\n\nIl nome può anche essere un URL con una scadenza facoltativa, ad esempio `'https://example.com/op.js <5 minutes>'` (sono accettati anche `once` e `asap`). Il file viene scaricato, compilato e messo in cache fino alla scadenza. Può contenere una dichiarazione `NEWOPERATION()` o un modulo con `exports.install`, `exports.make` o `exports.exec`.\n\nExample: Chiamare un'operazione\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Da una route\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nEsegue più operazioni una dopo l'altra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Nomi delle operazioni, separati da virgole. |\n| `value` | `Object` | no | `{}` | Valore condiviso per `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Chiamata quando la catena termina. |\n| `options` | `Object` | no |  | Opzioni personalizzate, disponibili come `$.options`. |\n| `controller` | `Controller` | no |  | Controller della richiesta corrente. |\n| `response_name` | `String` | no |  | Nome dell'operazione la cui risposta viene restituita da sola. |\n\n`names` è una stringa separata da virgole o un array. Tutte le operazioni condividono un solo `$` e un solo `$.value`. La callback riceve `err`, la risposta e l'oggetto `$`. La risposta ha una chiave per ogni operazione; con `response_name` è solo la risposta di quell'operazione. Quando un'operazione fallisce e la sua opzione `stop` è `true` (il valore predefinito), la catena si ferma. I nomi che non esistono vengono saltati. Una stringa al posto di `options` o `controller` viene letta come `response_name`.\n\nExample: Concatenare due operazioni\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Restituire una sola risposta\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nChiama una funzione per ogni operazione registrata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Chiamata con il nome di ogni operazione. |\n\nLa funzione riceve il nome di ogni operazione.\n\nExample: Elencare le operazioni\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nIl valore passato all'operazione.\n\nReturns: `Object`\n\n`$.model` è lo stesso valore. In una catena `RUN()`, ogni operazione condivide questo oggetto, quindi le modifiche sono visibili alle operazioni successive.\n\nExample: Leggere il valore\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nLe opzioni passate a `OPERATION()` o `RUN()`.\n\nReturns: `Object`\n\nUn oggetto vuoto quando non sono state passate opzioni. `OPERATION()` lo ripassa come terzo argomento della callback.\n\nExample: Usare le opzioni\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nNome dell'operazione in esecuzione.\n\nReturns: `String`\n\nIn una catena `RUN()` cambia con ogni operazione.\n\nExample: Registrare il nome nel log\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\nL'`ErrorBuilder` dell'operazione.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` aggiunge qui gli errori. In una catena `RUN()`, ogni operazione riceve un nuovo `ErrorBuilder`.\n\nExample: Aggiungere più errori\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nIl controller passato all'operazione, oppure `undefined`.\n\nReturns: `Controller`\n\n`$.client` è lo stesso valore. Le proprietà della richiesta di `$` vengono lette da questo controller.\n\nExample: Verificare la presenza di un controller\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nL'utente della richiesta corrente.\n\nReturns: `Object`\n\nLetto dal controller, oppure `null` senza un controller. Le altre proprietà della richiesta funzionano allo stesso modo: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` e `$.test`.\n\nExample: Usare l'utente e la query\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nLa query string convertita dallo schema `filter` dell'operazione.\n\nReturns: `Object`\n\nLo schema è l'argomento `filter` di `NEWOPERATION()`, ad esempio `'page:Number,q:String'`. Senza schema restituisce la query grezza. Senza un controller restituisce un oggetto vuoto.\n\nExample: Query tipizzata\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nTermina l'operazione e restituisce un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | La risposta, oppure un errore. |\n\nReturns: `$`\n\nUn `Error` o un `ErrorBuilder` con errori viene aggiunto a `$.error`. Puoi anche chiamarlo come `$.callback(err, value)`. Quando l'operazione ha errori e restano ripetizioni di `repeat`, viene invece eseguita di nuovo.\n\nExample: Restituire un valore\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: Passarlo come callback\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nTermina l'operazione con un oggetto di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Il flag di successo. |\n| `value` | `Object` | no |  | Un valore aggiunto come `value`. |\n\nReturns: `$`\n\nRestituisce `{ success: true }` alla callback. `$.success(value)` aggiunge `value`. `$.success(false)` imposta `success` a `false`. In una catena `RUN()`, le chiavi vuote vengono omesse.\n\nExample: Restituire il nuovo id\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nTermina l'operazione con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Nome dell'errore, messaggio di errore o `Error`. |\n| `error` | `String` | no |  | Messaggio di errore. |\n| `path` | `String` | no |  | Percorso del campo. |\n| `index` | `Number` | no |  | Indice dell'elemento in un array. |\n\nReturns: `$|Function`\n\nGli argomenti vanno a `$.error.push()`. Senza argomenti restituisce una funzione `function(err)` che puoi passare come callback.\n\nExample: Restituire un errore\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nRestituisce una callback che termina l'operazione con un oggetto di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` aggiunge la risposta; un altro valore viene aggiunto così com'è. |\n\nReturns: `Function(err, response)`\n\nLa funzione restituita `function(err, response)` aggiunge `err` e richiama la callback, oppure la richiama con `{ success: true }`. Con `arg` impostato a `true`, la risposta viene aggiunta come `value`; qualsiasi altro `arg` viene aggiunto al posto della risposta.\n\nExample: Restituire il record inserito\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nRestituisce una callback che gestisce gli errori per te.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Chiamata quando non c'è alcun errore. |\n\nReturns: `Function(err, a, b, c)`\n\nLa funzione restituita `function(err, a, b, c)` chiama `$.invalid(err)` quando c'è un errore, altrimenti chiama `callback(a, b, c)` con `$` come `this`.\n\nExample: Saltare i controlli degli errori\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nTermina l'operazione con un redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL di destinazione. |\n\nReturns: `$`\n\nQuando l'operazione è stata chiamata con `controller.callback()`, il controller esegue il redirect a `url`.\n\nExample: Redirect dopo il logout\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nTermina l'operazione senza chiamare la callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` non chiama `controller.custom()`. |\n\nReturns: `$`\n\nUsalo quando l'operazione risponde da sé alla richiesta. Per impostazione predefinita chiama anche `controller.custom()`, così il framework non invia un'altra risposta; `true` salta questa chiamata.\n\nExample: Rispondere da te alla richiesta\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nLegge o scrive un cookie della richiesta corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del cookie. |\n| `value` | `String` | no |  | Nuovo valore, oppure `null` per rimuoverlo. |\n| `expire` | `String|Date` | no |  | Scadenza, ad esempio `'1 day'`. |\n| `options` | `Object` | no |  | Opzioni del cookie. |\n\nReturns: `String|$`\n\nCon il solo `name` restituisce il valore del cookie. `null` come `value` rimuove il cookie. Richiede un controller.\n\nExample: Scrivere un cookie\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nSostituisce i segnaposto `{key}` in una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Testo con segnaposto. |\n| `data` | `Object` | no |  | Valori per `{data.key}`. |\n\nReturns: `String`\n\nLe chiavi supportate iniziano con `user.`, `data.`, `model.` o `value.`, `query.` e `params.`. Le chiavi sconosciute vengono mantenute. Funzionano sia le parentesi graffe singole che doppie. Esiste sul `$` di operazioni e task.\n\nExample: Costruire un messaggio\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nScrive una voce del log di audit per l'operazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Messaggio di audit. |\n| `type` | `String` | no |  | Tipo della voce. |\n\nReturns: `$`\n\nChiama `AUDIT($, message, type)` con i dati dell'utente, della richiesta e del valore. Esiste sul `$` di operazioni e task.\n\nExample: Registrare una modifica nell'audit\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nRisultati delle operazioni precedenti in una catena `RUN()`.\n\nReturns: `Object`\n\nUn oggetto con una chiave per ogni operazione già terminata. Impostato solo dentro `RUN()`.\n\nExample: Usare un risultato precedente\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformazioni su una catena `RUN()`.\n\nReturns: `Object`\n\n`$.meta.items` è l'elenco dei nomi, `$.meta.current` l'operazione in esecuzione, `$.meta.prev` quella precedente e `$.meta.index` l'indice dell'operazione in esecuzione. Impostato solo dentro `RUN()`.\n\nExample: Controllare l'operazione precedente\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nQuante volte l'operazione in esecuzione è stata ripetuta in una catena `RUN()`.\n\nReturns: `Number`\n\nParte da `0` per ogni operazione e cresce ogni volta che l'opzione `repeat` la esegue di nuovo. Impostato solo dentro `RUN()`.\n\nExample: Rinunciare in anticipo\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDichiara un task con step con nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del task. |\n| `fn` | `Function(push)` | yes |  | Dichiara gli step con `push(step, fn($, value))`. `null` rimuove il task. |\n\n`fn` riceve `push(step, fn)`. Ogni step riceve `$` e il valore, e `this` è `$`. `NEWTASK(name, null)` rimuove il task. Metti i task nella directory `/tasks/`.\n\nExample: Un task con due step\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nCrea un task e lo avvia da uno step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del task, oppure `'name/step'`. |\n| `step` | `String` | yes |  | Il primo step. |\n| `callback` | `Function(err, response)` | yes |  | Chiamata quando il task termina. |\n| `options` | `Controller|Object` | no |  | Controller o oggetto `$`, oppure il valore. |\n| `value` | `Object` | no | `{}` | Valore per `$.value`. |\n\nReturns: `TaskBuilder` Il task, `$`.\n\n`name` e `step` possono essere un'unica stringa `'name/step'`; in tal caso gli argomenti sono `TASK('name/step', callback, [options], [value])`. Un controller o il `$` di uno schema, di un'operazione o di un task come `options` ne condivide la richiesta e gli errori; qualsiasi altro `options` viene usato come valore. Lo step parte al tick successivo, quindi puoi prima aggiungere step con `$.push()`. Senza uno step, avvialo con `$.exec()`.\n\nIl nome può anche essere un URL con una scadenza facoltativa, ad esempio `'https://example.com/task.js <1 hour>'`. Il file viene scaricato e messo in cache fino alla scadenza.\n\nExample: Eseguire un task\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: Da un'azione di uno schema, con \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nEsegue lo step successivo del task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nome dello step. Altri nomi vengono provati in ordine. |\n\nReturns: `$`\n\nEsegue il primo step dell'elenco che esiste, prima tra gli step aggiunti con `$.push()` e poi nella dichiarazione del task. Quando non ne esiste nessuno, il task termina. Non fa nulla dopo che il task è terminato.\n\nExample: Passare allo step successivo\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nRestituisce una callback che passa allo step successivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Nome dello step successivo. |\n\nReturns: `Function(err)`\n\nLa funzione restituita `function(err)` chiama `$.invalid(err)` in caso di errore, altrimenti esegue `step`, oppure termina il task quando `step` è vuoto.\n\nExample: Continuare dopo una scrittura\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nTermina il task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | La risposta. |\n\nReturns: `$`\n\nChiama la callback del task con gli errori (o `null`) e `data`, oppure `$.value` quando `data` è vuoto.\n\nExample: Terminare con il valore\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nRestituisce una callback che termina il task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` restituisce i dati della callback. |\n\nReturns: `Function(err, data)`\n\nLa funzione restituita `function(err, data)` chiama `$.invalid(err)` in caso di errore, altrimenti termina il task con `data` quando `send_value` è `true`, oppure con `$.value`.\n\nExample: Terminare con il risultato\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nTermina il task con un oggetto di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Un valore aggiunto come `value`. |\n\nReturns: `$`\n\nTermina il task con `{ success: true }`, più `value` quando `data` è impostato.\n\nExample: Terminare con successo\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nRestituisce una callback che termina il task con un oggetto di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` aggiunge i dati della callback come `value`. |\n\nReturns: `Function(err, data)`\n\nLa funzione restituita `function(err, data)` chiama `$.invalid(err)` in caso di errore, altrimenti termina il task con `{ success: true }`, più `value: data` quando `send_value` è `true`.\n\nExample: Salvare e terminare\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nTermina il task con un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Nome dell'errore o `Error`. |\n| `msg` | `String` | no |  | Messaggio di errore. |\n\nReturns: `$`\n\nAggiunge l'errore a `$.error` e termina il task. Non fa nulla dopo che il task è terminato.\n\nExample: Fermare il task\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nAggiunge uno step solo a questo task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Nome dello step. |\n| `fn` | `Function($, value)` | yes |  | Lo step. |\n\nReturns: `$`\n\nLo step viene usato prima di uno step con lo stesso nome nella dichiarazione del task. Chiamalo sul task restituito da `TASK()`, prima che venga eseguito il primo step.\n\nExample: Sovrascrivere uno step\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nAvvia il task da uno step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Il primo step. |\n| `callback` | `Function(err, response)` | no |  | Chiamata quando il task termina. |\n\nReturns: `$`\n\nImposta la callback se indicata ed esegue `step`. Usalo con un task creato da `TASK(name)` senza uno step.\n\nExample: Avviare più tardi\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nImposta la callback del task.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | La callback. |\n\nReturns: `$`\n\n`fn` viene chiamata una volta quando il task termina, con gli errori (o `null`) e la risposta.\n\nExample: Impostare la callback\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nIl valore condiviso da tutti gli step del task.\n\nReturns: `Object`\n\n`$.model` è lo stesso valore. Gli step lo ricevono anche come secondo argomento. È un oggetto vuoto quando non è stato passato alcun valore.\n\nExample: Modificare il valore\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nNome dello step in esecuzione.\n\nReturns: `String`\n\n`$.prev` contiene lo step precedente e `$.name` il nome del task. Le proprietà della richiesta (`$.user`, `$.query`, `$.params`, `$.body` e altre) vengono lette dal controller, come nelle operazioni.\n\nExample: Registrare lo step nel log\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nAvvolge in una Promise una funzione con callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una funzione il cui ultimo argomento è `callback(err, response)`. |\n| `a` | `Object` | no |  | Primo argomento per `fn`. |\n| `b` | `Object` | no |  | Secondo argomento per `fn`. |\n\nReturns: `Promise`\n\nChiama `fn` con gli argomenti dati e una callback `function(err, response)` come ultimo argomento. La promise si risolve con `response` o viene rifiutata con `err`. Gli argomenti vuoti non vengono passati.\n\nExample: Attendere una callback\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Leggere un file\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nAggiunge un handler per un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del comando. |\n| `fn` | `Function(a, b, c, d)` | yes |  | L'handler. `null` rimuove tutti gli handler. |\n\nUn comando può avere più handler; ogni chiamata ne aggiunge uno. `NEWCOMMAND(name, null)` rimuove tutti gli handler del comando. Eseguilo con `CMD()`.\n\nExample: Un comando\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nEsegue tutti gli handler di un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del comando. |\n| `a` | `Object` | no |  | Primo argomento. |\n| `b` | `Object` | no |  | Secondo argomento. |\n| `c` | `Object` | no |  | Terzo argomento. |\n| `d` | `Object` | no |  | Quarto argomento. |\n\nPassa fino a quattro argomenti a ogni handler. Non fa nulla quando il comando non ha handler. I comandi integrati includono `clear_viewscache`, `clear_smtpcache` e `refresh_tms`.\n\nExample: Eseguire un comando\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nRestituisce una funzione che esegue un comando.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del comando. |\n| `a` | `Object` | no |  | Primo argomento. |\n| `b` | `Object` | no |  | Secondo argomento. |\n| `c` | `Object` | no |  | Terzo argomento. |\n| `d` | `Object` | no |  | Quarto argomento. |\n\nReturns: `Function`\n\nLa funzione restituita esegue tutti gli handler con gli argomenti indicati. Quando il comando non ha handler, restituisce `NOOP`.\n\nExample: Eseguire un comando più tardi\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nInstalla un'estensione da codice sorgente o da un URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Codice sorgente, oppure un URL. |\n| `callback` | `Function(err, module)` | no |  | Chiamata quando l'estensione è installata. |\n| `extend` | `Function(module)` | no |  | Chiamata con il modulo prima che venga installato. |\n\n`code` è JavaScript che imposta `exports`, oppure un URL da cui scaricarlo. Export facoltativi: `id`, `name`, `install(next)`, `make()`, `done()` e `uninstall()`. Senza `id` l'id è un hash di `name` o del codice. Un'estensione con lo stesso id viene prima rimossa. Il codice può anche essere HTML con un blocco `<script total>` e blocchi `<file name=\"...\">`; `exports.files` associa quindi ogni nome di file a un percorso temporaneo. Il metodo aggiunto `remove()` disinstalla l'estensione. I file nella directory `/extensions/` vengono installati all'avvio dell'app.\n\nExample: Installare da una stringa\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Installare da un URL\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nCrea una piccola macchina a stati in memoria: step con nome che passano dall'uno all'altro con `$.next()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)` che aggiunge gli step. |\n| `tasks` | `Object` | no | `{}` | Step come `{ name: function($, value) }`. |\n\nReturns: `Object` Il workflow `$`.\n\n`WORKFLOW()` restituisce un oggetto `$` e lo passa a `declaration($)`, dove aggiungi gli step con `$.push(name, fn)`. Ogni step è `function($, value)`. È un helper locale, non un task registrato: nulla viene memorizzato o nominato a livello globale.\n\n| Membro | Cosa fa |\n| --- | --- |\n| `$.push(name, fn)` | Aggiunge lo step `fn($, value)` |\n| `$.next(name, [value])` | Esegue lo step `name` con `value`; `$.trigger()` è un alias. Un nome sconosciuto distrugge il workflow |\n| `$.next2(name)` | Restituisce `function(value)` che esegue `$.next(name, value)`, per le callback |\n| `$.invalid(err)` | Chiama `$.error(err, $)` se l'hai impostato, poi distrugge il workflow |\n| `$.current`, `$.prev` | Il nome dello step corrente e di quello precedente |\n| `$.tasks` | Gli step, come oggetto |\n| `$.clone()` | Un nuovo workflow con gli stessi step |\n| `$.destroy()` | Lo termina; le chiamate successive di `$.next()` non fanno nulla |\n\n`declaration` può essere `null` quando passi gli step come `tasks`.\n\nExample: Step in ordine\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZRH4aj61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/operations-and-tasks/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Operácie a úlohy","summary":"Globálne funkcie a objekt $ operácií a úloh, k tomu príkazy, rozšírenia a PROMISIFY().","markdown":"---\ntitle: \"Operácie a úlohy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/operations-and-tasks/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Operácie a úlohy\n\n> Globálne funkcie a objekt $ operácií a úloh, k tomu príkazy, rozšírenia a PROMISIFY().\n\nOperácie (`NEWOPERATION()`, `OPERATION()`, `RUN()`) a úlohy (`NEWTASK()`, `TASK()`) držia biznis logiku mimo trás. Obe dostávajú objekt `$`; táto stránka uvádza jeho vlastnosti a metódy a tiež príkazy, rozšírenia a `PROMISIFY()`. Návod [Operácie a úlohy](../../guides/operations-and-tasks/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])\n\nType: `method`\n\nZaregistruje operáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie. |\n| `fn` | `Function($, value)` | yes |  | Operácia. `null` ju odstráni. |\n| `repeat` | `Number` | no |  | Koľkokrát spustiť operáciu znova, keď skončí chybou. |\n| `stop` | `Boolean` | no | `true` | Zastaví reťazec `RUN()`, keď táto operácia zlyhá. |\n| `binderror` | `Boolean` | no | `false` | V reťazci `RUN()` uloží chybový výstup ako odpoveď tejto operácie. |\n| `filter` | `String` | no |  | Schéma pre query string, používa ju `$.filter`. |\n\nFunkcia dostane `$` a hodnotu. Musí skončiť volaním `$.callback()`, `$.success()`, `$.invalid()` alebo inej metódy, ktorá zavolá callback. Boolean na mieste `repeat` sa číta ako `stop` a reťazec na akejkoľvek voliteľnej pozícii sa číta ako `filter`. Volanie `NEWOPERATION(name, null)` operáciu odstráni. Operácie ukladaj do priečinka `/operations/`.\n\nExample: Operácia\n```js\nNEWOPERATION('users_count', function($, value) {\n\tNOSQL('users').count().callback(function(err, count) {\n\t\tif (err)\n\t\t\t$.invalid(err);\n\t\telse\n\t\t\t$.callback(count);\n\t});\n});\n```\n\nExample: Opakovanie po chybe\n```js\nNEWOPERATION('ping', function($) {\n\tRESTBuilder.GET('https://example.com/ping').callback($.done());\n}, 3);\n```\n\n### OPERATION(name, [value], callback, [options], [controller])\n\nType: `method`\n\nSpustí jednu operáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov operácie alebo URL vzdialenej operácie. |\n| `value` | `Object` | no | `{}` | Hodnota pre `$.value`. |\n| `callback` | `Function(err, response, options)` | yes |  | Zavolá sa, keď operácia skončí. |\n| `options` | `Object` | no |  | Vlastné voľby, dostupné ako `$.options`. |\n| `controller` | `Controller` | no |  | Kontrolér aktuálnej požiadavky alebo objekt `$`. |\n\nCallback dostane `err` (`ErrorBuilder` alebo `null`), odpoveď a `options`. Keď je `value` funkcia, je to callback a hodnota je prázdny objekt. Kontrolér alebo objekt `$` odovzdaný ako `options` sa použije ako kontrolér. Chýbajúca operácia skončí chybou `Operation \"name\" not found.`\n\nNázov môže byť aj URL s voliteľnou expiráciou, napríklad `'https://example.com/op.js <5 minutes>'` (prijímajú sa aj `once` a `asap`). Súbor sa stiahne, skompiluje a uloží do cache, kým neexpiruje. Môže obsahovať deklaráciu `NEWOPERATION()` alebo modul s `exports.install`, `exports.make` alebo `exports.exec`.\n\nExample: Volanie operácie\n```js\nOPERATION('users_count', function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Z routy\n```js\nexports.install = function() {\n\tROUTE('GET /api/users/count/', count);\n};\n\nfunction count() {\n\tvar self = this;\n\tOPERATION('users_count', self.query, self.callback(), self);\n}\n```\n\n### RUN(names, [value], callback, [options], [controller], [response_name])\n\nType: `method`\n\nSpustí niekoľko operácií jednu po druhej.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `names` | `String|Array` | yes |  | Názvy operácií oddelené čiarkami. |\n| `value` | `Object` | no | `{}` | Zdieľaná hodnota pre `$.value`. |\n| `callback` | `Function(err, response, $)` | yes |  | Zavolá sa, keď reťazec skončí. |\n| `options` | `Object` | no |  | Vlastné voľby, dostupné ako `$.options`. |\n| `controller` | `Controller` | no |  | Kontrolér aktuálnej požiadavky. |\n| `response_name` | `String` | no |  | Názov operácie, ktorej odpoveď sa vráti samostatne. |\n\n`names` je reťazec oddelený čiarkami alebo pole. Všetky operácie zdieľajú jeden `$` a jedno `$.value`. Callback dostane `err`, odpoveď a objekt `$`. Odpoveď má jeden kľúč pre každú operáciu; s `response_name` je to iba odpoveď tejto operácie. Keď operácia zlyhá a jej voľba `stop` je `true` (predvolené), reťazec sa zastaví. Názvy, ktoré neexistujú, sa preskočia. Reťazec na mieste `options` alebo `controller` sa číta ako `response_name`.\n\nExample: Reťazenie dvoch operácií\n```js\nRUN('check, save', { email: 'peter@example.com' }, function(err, response) {\n\t// response.check, response.save\n\tconsole.log(err, response);\n});\n```\n\nExample: Vrátenie jednej odpovede\n```js\nfunction create() {\n\tvar self = this;\n\tRUN('check, save', self.body, self.callback(), null, self, 'save');\n}\n```\n\n### EACHOPERATION(fn)\n\nType: `method`\n\nZavolá funkciu pre každú zaregistrovanú operáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(name)` | yes |  | Zavolá sa s názvom každej operácie. |\n\nFunkcia dostane názov každej operácie.\n\nExample: Výpis operácií\n```js\nEACHOPERATION(function(name) {\n\tconsole.log(name);\n});\n```\n\n### $.value\n\nType: `property`\n\nHodnota odovzdaná operácii.\n\nReturns: `Object`\n\n`$.model` je tá istá hodnota. V reťazci `RUN()` tento objekt zdieľa každá operácia, takže zmeny vidia aj ďalšie operácie.\n\nExample: Čítanie hodnoty\n```js\nNEWOPERATION('greet', function($) {\n\t$.callback('Hello ' + $.value.name);\n});\n```\n\n### $.options\n\nType: `property`\n\nVoľby odovzdané do `OPERATION()` alebo `RUN()`.\n\nReturns: `Object`\n\nPrázdny objekt, keď neboli odovzdané žiadne voľby. `OPERATION()` ho znova odovzdá ako tretí argument callbacku.\n\nExample: Použitie volieb\n```js\nNEWOPERATION('export', function($) {\n\t$.callback({ format: $.options.format || 'json' });\n});\n\nOPERATION('export', {}, console.log, { format: 'csv' });\n```\n\n### $.name\n\nType: `property`\n\nNázov bežiacej operácie.\n\nReturns: `String`\n\nV reťazci `RUN()` sa mení s každou operáciou.\n\nExample: Zalogovanie názvu\n```js\nNEWOPERATION('sync', function($) {\n\tconsole.log('Running', $.name);\n\t$.success();\n});\n```\n\n### $.error\n\nType: `property`\n\n`ErrorBuilder` operácie.\n\nReturns: `ErrorBuilder`\n\n`$.invalid()` sem pridáva chyby. V reťazci `RUN()` dostane každá operácia nový `ErrorBuilder`.\n\nExample: Pridanie viacerých chýb\n```js\nNEWOPERATION('validate', function($) {\n\t!$.value.name && $.error.push('name');\n\t!$.value.email && $.error.push('email');\n\t$.callback();\n});\n```\n\n### $.controller\n\nType: `property`\n\nKontrolér odovzdaný operácii alebo `undefined`.\n\nReturns: `Controller`\n\n`$.client` je tá istá hodnota. Vlastnosti požiadavky v `$` sa čítajú z tohto kontroléra.\n\nExample: Kontrola kontroléra\n```js\nNEWOPERATION('whoami', function($) {\n\tif ($.controller)\n\t\t$.callback($.user);\n\telse\n\t\t$.invalid('401');\n});\n```\n\n### $.user\n\nType: `property`\n\nPoužívateľ aktuálnej požiadavky.\n\nReturns: `Object`\n\nČíta sa z kontroléra, alebo je `null` bez kontroléra. Ostatné vlastnosti požiadavky fungujú rovnako: `$.session`, `$.sessionid`, `$.language`, `$.ip`, `$.id`, `$.req`, `$.res`, `$.url`, `$.uri`, `$.path`, `$.split`, `$.params`, `$.query`, `$.body`, `$.files`, `$.headers`, `$.ua`, `$.mobile` a `$.test`.\n\nExample: Použitie používateľa a query\n```js\nNEWOPERATION('my_orders', function($) {\n\tNOSQL('orders').find().where('userid', $.user.id).take($.query.take || 20).callback($.callback);\n});\n```\n\n### $.filter\n\nType: `property`\n\nQuery string skonvertovaný schémou `filter` operácie.\n\nReturns: `Object`\n\nSchéma je argument `filter` z `NEWOPERATION()`, napríklad `'page:Number,q:String'`. Bez schémy vráti surový query. Bez kontroléra vráti prázdny objekt.\n\nExample: Typovaný query\n```js\nNEWOPERATION('products', function($) {\n\tvar filter = $.filter;\n\t$.callback({ page: filter.page, q: filter.q });\n}, 'page:Number,q:String');\n```\n\n### $.callback([value])\n\nType: `method`\n\nUkončí operáciu a vráti hodnotu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | no |  | Odpoveď alebo chyba. |\n\nReturns: `$`\n\n`Error` alebo `ErrorBuilder` s chybami sa pridá do `$.error`. Môžeš ju volať aj ako `$.callback(err, value)`. Keď má operácia chyby a zostáva jej `repeat`, spustí sa namiesto toho znova.\n\nExample: Vrátenie hodnoty\n```js\nNEWOPERATION('now', function($) {\n\t$.callback(NOW);\n});\n```\n\nExample: Odovzdanie ako callback\n```js\nNEWOPERATION('users', function($) {\n\tNOSQL('users').find().callback($.callback);\n});\n```\n\n### $.success([success], [value])\n\nType: `method`\n\nUkončí operáciu objektom úspechu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean` | no | `true` | Flag úspechu. |\n| `value` | `Object` | no |  | Hodnota pridaná ako `value`. |\n\nReturns: `$`\n\nVráti callbacku `{ success: true }`. `$.success(value)` pridá `value`. `$.success(false)` nastaví `success` na `false`. V reťazci `RUN()` sa prázdne kľúče vynechajú.\n\nExample: Vrátenie nového id\n```js\nNEWOPERATION('contact_save', function($) {\n\tvar id = UID();\n\t$.value.id = id;\n\tNOSQL('contacts').insert($.value).callback(function() {\n\t\t$.success(id);\n\t});\n});\n```\n\n### $.invalid([name], [error], [path], [index])\n\nType: `method`\n\nUkončí operáciu chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Error` | no |  | Názov chyby, chybová správa alebo `Error`. |\n| `error` | `String` | no |  | Chybová správa. |\n| `path` | `String` | no |  | Cesta k poľu. |\n| `index` | `Number` | no |  | Index položky v poli. |\n\nReturns: `$|Function`\n\nArgumenty idú do `$.error.push()`. Bez argumentov vráti funkciu `function(err)`, ktorú môžeš odovzdať ako callback.\n\nExample: Vrátenie chyby\n```js\nNEWOPERATION('login', function($) {\n\tif (!$.value.email) {\n\t\t$.invalid('email', 'Email is required');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.done([arg])\n\nType: `method`\n\nVráti callback, ktorý ukončí operáciu objektom úspechu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg` | `Boolean|Object` | no |  | `true` pridá odpoveď; iná hodnota sa pridá tak, ako je. |\n\nReturns: `Function(err, response)`\n\nVrátená funkcia `function(err, response)` pridá `err` a zavolá callback, alebo zavolá callback s `{ success: true }`. Keď je `arg` nastavený na `true`, odpoveď sa pridá ako `value`; akýkoľvek iný `arg` sa pridá namiesto odpovede.\n\nExample: Vrátenie vloženého záznamu\n```js\nNEWOPERATION('save', function($) {\n\tNOSQL('contacts').insert($.value).callback($.done(true));\n});\n```\n\n### $.successful(callback)\n\nType: `method`\n\nVráti callback, ktorý za teba spracuje chyby.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(a, b, c)` | yes |  | Zavolá sa, keď nenastane chyba. |\n\nReturns: `Function(err, a, b, c)`\n\nVrátená funkcia `function(err, a, b, c)` zavolá `$.invalid(err)`, keď nastane chyba, inak zavolá `callback(a, b, c)` s `$` ako `this`.\n\nExample: Vynechanie kontroly chýb\n```js\nNEWOPERATION('count', function($) {\n\tNOSQL('users').count().callback($.successful(function(count) {\n\t\t$.callback({ count: count });\n\t}));\n});\n```\n\n### $.redirect(url)\n\nType: `method`\n\nUkončí operáciu presmerovaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová URL. |\n\nReturns: `$`\n\nKeď bola operácia zavolaná s `controller.callback()`, kontrolér presmeruje na `url`.\n\nExample: Presmerovanie po odhlásení\n```js\nNEWOPERATION('logout', function($) {\n\t$.cookie('session', null);\n\t$.redirect('/');\n});\n```\n\n### $.noop([nocustomresponse])\n\nType: `method`\n\nUkončí operáciu bez zavolania callbacku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `nocustomresponse` | `Boolean` | no | `false` | `true` nezavolá `controller.custom()`. |\n\nReturns: `$`\n\nPouži ju, keď operácia odpovedá na požiadavku sama. Predvolene zavolá aj `controller.custom()`, takže framework neodošle ďalšiu odpoveď; `true` toto volanie vynechá.\n\nExample: Vlastná odpoveď na požiadavku\n```js\nNEWOPERATION('ping', function($) {\n\t$.controller.plain('pong');\n\t$.noop(true);\n});\n```\n\n### $.cookie(name, [value], [expire], [options])\n\nType: `method`\n\nPrečíta alebo zapíše cookie aktuálnej požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov cookie. |\n| `value` | `String` | no |  | Nová hodnota alebo `null` na odstránenie. |\n| `expire` | `String|Date` | no |  | Expirácia, napríklad `'1 day'`. |\n| `options` | `Object` | no |  | Voľby cookie. |\n\nReturns: `String|$`\n\nS iba `name` vráti hodnotu cookie. `null` ako `value` cookie odstráni. Potrebuje kontrolér.\n\nExample: Zápis cookie\n```js\nNEWOPERATION('remember', function($) {\n\t$.cookie('lang', $.value.lang, '1 year');\n\t$.success();\n});\n```\n\n### $.variables(str, [data])\n\nType: `method`\n\nNahradí zástupné symboly `{key}` v reťazci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Text so zástupnými symbolmi. |\n| `data` | `Object` | no |  | Hodnoty pre `{data.key}`. |\n\nReturns: `String`\n\nPodporované kľúče začínajú na `user.`, `data.`, `model.` alebo `value.`, `query.` a `params.`. Neznáme kľúče sa ponechajú. Fungujú jednoduché aj dvojité zložené zátvorky. Existuje na `$` operácií aj úloh.\n\nExample: Zostavenie správy\n```js\nNEWOPERATION('notify', function($) {\n\tvar text = $.variables('Hello {user.name}, order {data.id} is ready.', { id: $.value.id });\n\t$.callback(text);\n});\n```\n\n### $.audit([message], [type])\n\nType: `method`\n\nZapíše záznam do audit logu pre operáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `String` | no |  | Správa auditu. |\n| `type` | `String` | no |  | Typ záznamu. |\n\nReturns: `$`\n\nZavolá `AUDIT($, message, type)` s dátami používateľa, požiadavky a hodnoty. Existuje na `$` operácií aj úloh.\n\nExample: Audit zmeny\n```js\nNEWOPERATION('remove', function($) {\n\t$.audit('Removed product ' + $.value.id);\n\t$.success();\n});\n```\n\n### $.response\n\nType: `property`\n\nVýsledky predchádzajúcich operácií v reťazci `RUN()`.\n\nReturns: `Object`\n\nObjekt s jedným kľúčom pre každú operáciu, ktorá už skončila. Nastavuje sa iba vnútri `RUN()`.\n\nExample: Použitie predchádzajúceho výsledku\n```js\nNEWOPERATION('invoice', function($) {\n\tvar order = $.response.order;\n\t$.callback({ total: order.value.price });\n});\n```\n\n### $.meta\n\nType: `property`\n\nInformácie o reťazci `RUN()`.\n\nReturns: `Object`\n\n`$.meta.items` je zoznam názvov, `$.meta.current` bežiaca operácia, `$.meta.prev` predchádzajúca a `$.meta.index` index bežiacej operácie. Nastavuje sa iba vnútri `RUN()`.\n\nExample: Kontrola predchádzajúcej operácie\n```js\nNEWOPERATION('save', function($) {\n\tif ($.meta.prev !== 'check') {\n\t\t$.invalid('check');\n\t\treturn;\n\t}\n\t$.success();\n});\n```\n\n### $.repeated\n\nType: `property`\n\nKoľkokrát sa bežiaca operácia v reťazci `RUN()` opakovala.\n\nReturns: `Number`\n\nZačína na `0` pre každú operáciu a rastie zakaždým, keď ju voľba `repeat` spustí znova. Nastavuje sa iba vnútri `RUN()`.\n\nExample: Predčasné vzdanie\n```js\nNEWOPERATION('fetch', function($) {\n\tif ($.repeated > 1)\n\t\tconsole.log('Second retry');\n\tRESTBuilder.GET('https://example.com/data').callback($.callback);\n}, 3);\n```\n\n### NEWTASK(name, fn)\n\nType: `method`\n\nDeklaruje úlohu s pomenovanými krokmi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úlohy. |\n| `fn` | `Function(push)` | yes |  | Deklaruje kroky pomocou `push(step, fn($, value))`. `null` úlohu odstráni. |\n\n`fn` dostane `push(step, fn)`. Každý krok dostane `$` a hodnotu a `this` je `$`. `NEWTASK(name, null)` úlohu odstráni. Úlohy ukladaj do priečinka `/tasks/`.\n\nExample: Úloha s dvoma krokmi\n```js\nNEWTASK('signup', function(push) {\n\n\tpush('check', function($, value) {\n\t\tif (!value.email) {\n\t\t\t$.invalid('email');\n\t\t\treturn;\n\t\t}\n\t\t$.next('save');\n\t});\n\n\tpush('save', function($, value) {\n\t\tNOSQL('users').insert(value).callback($.done());\n\t});\n\n});\n```\n\n### TASK(name, step, callback, [options], [value])\n\nType: `method`\n\nVytvorí úlohu a spustí ju od kroku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov úlohy alebo `'name/step'`. |\n| `step` | `String` | yes |  | Prvý krok. |\n| `callback` | `Function(err, response)` | yes |  | Zavolá sa, keď úloha skončí. |\n| `options` | `Controller|Object` | no |  | Kontrolér alebo objekt `$`, prípadne hodnota. |\n| `value` | `Object` | no | `{}` | Hodnota pre `$.value`. |\n\nReturns: `TaskBuilder` Úloha, `$`.\n\n`name` a `step` môžu byť jeden reťazec `'name/step'`; potom sú argumenty `TASK('name/step', callback, [options], [value])`. Kontrolér alebo `$` schémy, operácie či úlohy ako `options` zdieľa svoju požiadavku a svoje chyby; akékoľvek iné `options` sa použije ako hodnota. Krok sa spustí v ďalšom ticku, takže môžeš najprv pridať kroky pomocou `$.push()`. Bez kroku ju spustíš pomocou `$.exec()`.\n\nNázov môže byť aj URL s voliteľnou expiráciou, napríklad `'https://example.com/task.js <1 hour>'`. Súbor sa stiahne a uloží do cache, kým neexpiruje.\n\nExample: Spustenie úlohy\n```js\nTASK('signup', 'check', function(err, response) {\n\tconsole.log(err, response);\n}, { email: 'peter@example.com' });\n```\n\nExample: Z akcie schémy, s \"name/step\"\n```js\nTASK('signup/check', $.callback, $, $.model);\n```\n\n### $.next(step, [step2], [...])\n\nType: `method`\n\nSpustí ďalší krok úlohy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Názov kroku. Ďalšie názvy sa skúšajú postupne. |\n\nReturns: `$`\n\nSpustí prvý existujúci krok zo zoznamu, najprv medzi krokmi pridanými pomocou `$.push()` a potom v deklarácii úlohy. Keď žiadny neexistuje, úloha skončí. Po skončení úlohy nerobí nič.\n\nExample: Prechod na ďalší krok\n```js\npush('check', function($, value) {\n\t$.next(value.paid ? 'ship' : 'pay');\n});\n```\n\n### $.next2([step])\n\nType: `method`\n\nVráti callback, ktorý prejde na ďalší krok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | no |  | Názov ďalšieho kroku. |\n\nReturns: `Function(err)`\n\nVrátená funkcia `function(err)` pri chybe zavolá `$.invalid(err)`, inak spustí `step` alebo ukončí úlohu, keď je `step` prázdny.\n\nExample: Pokračovanie po zápise\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.next2('notify'));\n});\n```\n\n### $.end([data])\n\nType: `method`\n\nUkončí úlohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no | `$.value` | Odpoveď. |\n\nReturns: `$`\n\nZavolá callback úlohy s chybami (alebo `null`) a `data`, alebo s `$.value`, keď je `data` prázdne.\n\nExample: Ukončenie s hodnotou\n```js\npush('price', function($, value) {\n\tvalue.total = value.price * value.count;\n\t$.end();\n});\n```\n\n### $.end2([send_value])\n\nType: `method`\n\nVráti callback, ktorý ukončí úlohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` vráti dáta callbacku. |\n\nReturns: `Function(err, data)`\n\nVrátená funkcia `function(err, data)` pri chybe zavolá `$.invalid(err)`, inak ukončí úlohu s `data`, keď je `send_value` `true`, alebo s `$.value`.\n\nExample: Ukončenie s výsledkom\n```js\npush('load', function($, value) {\n\tNOSQL('orders').one().where('id', value.id).callback($.end2(true));\n});\n```\n\n### $.success([data])\n\nType: `method`\n\nUkončí úlohu objektom úspechu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Hodnota pridaná ako `value`. |\n\nReturns: `$`\n\nUkončí úlohu s `{ success: true }`, plus `value`, keď je `data` nastavené.\n\nExample: Ukončenie s úspechom\n```js\npush('notify', function($, value) {\n\tMAIL(value.email, 'Order', '=?/mails/order', value);\n\t$.success(value.id);\n});\n```\n\n### $.done([send_value])\n\nType: `method`\n\nVráti callback, ktorý ukončí úlohu objektom úspechu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `send_value` | `Boolean` | no | `false` | `true` pridá dáta callbacku ako `value`. |\n\nReturns: `Function(err, data)`\n\nVrátená funkcia `function(err, data)` pri chybe zavolá `$.invalid(err)`, inak ukončí úlohu s `{ success: true }`, plus `value: data`, keď je `send_value` `true`.\n\nExample: Uloženie a dokončenie\n```js\npush('save', function($, value) {\n\tNOSQL('orders').insert(value).callback($.done(true));\n});\n```\n\n### $.invalid(err, [msg])\n\nType: `method`\n\nUkončí úlohu chybou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String|Error` | yes |  | Názov chyby alebo `Error`. |\n| `msg` | `String` | no |  | Chybová správa. |\n\nReturns: `$`\n\nPridá chybu do `$.error` a ukončí úlohu. Po skončení úlohy nerobí nič.\n\nExample: Zastavenie úlohy\n```js\npush('check', function($, value) {\n\tif (!value.items.length)\n\t\t$.invalid('items', 'The order is empty');\n\telse\n\t\t$.next('save');\n});\n```\n\n### $.push(step, fn)\n\nType: `method`\n\nPridá krok iba do tejto úlohy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Názov kroku. |\n| `fn` | `Function($, value)` | yes |  | Krok. |\n\nReturns: `$`\n\nKrok sa použije pred krokom s rovnakým názvom v deklarácii úlohy. Zavolaj ho na úlohe, ktorú vráti `TASK()`, pred spustením prvého kroku.\n\nExample: Prepísanie kroku\n```js\nvar task = TASK('signup', 'check', console.log, { email: 'peter@example.com' });\ntask.push('save', function($, value) {\n\t$.success();\n});\n```\n\n### $.exec(step, [callback])\n\nType: `method`\n\nSpustí úlohu od kroku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `step` | `String` | yes |  | Prvý krok. |\n| `callback` | `Function(err, response)` | no |  | Zavolá sa, keď úloha skončí. |\n\nReturns: `$`\n\nNastaví callback, ak je zadaný, a spustí `step`. Použi ho s úlohou vytvorenou pomocou `TASK(name)` bez kroku.\n\nExample: Neskoršie spustenie\n```js\nvar task = TASK('signup');\ntask.value = { email: 'peter@example.com' };\ntask.exec('check', console.log);\n```\n\n### $.callback(fn)\n\nType: `method`\n\nNastaví callback úlohy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(err, response)` | yes |  | Callback. |\n\nReturns: `$`\n\n`fn` sa zavolá raz, keď úloha skončí, s chybami (alebo `null`) a odpoveďou.\n\nExample: Nastavenie callbacku\n```js\nvar task = TASK('signup');\ntask.callback(function(err, response) {\n\tconsole.log(err, response);\n});\ntask.exec('check');\n```\n\n### $.value\n\nType: `property`\n\nHodnota zdieľaná všetkými krokmi úlohy.\n\nReturns: `Object`\n\n`$.model` je tá istá hodnota. Kroky ju dostávajú aj ako druhý argument. Je to prázdny objekt, keď nebola odovzdaná žiadna hodnota.\n\nExample: Zmena hodnoty\n```js\npush('price', function($) {\n\t$.value.price = 100;\n\t$.next('save');\n});\n```\n\n### $.current\n\nType: `property`\n\nNázov bežiaceho kroku.\n\nReturns: `String`\n\n`$.prev` obsahuje predchádzajúci krok a `$.name` názov úlohy. Vlastnosti požiadavky (`$.user`, `$.query`, `$.params`, `$.body` a ďalšie) sa čítajú z kontroléra, rovnako ako pri operáciách.\n\nExample: Zalogovanie kroku\n```js\npush('save', function($) {\n\tconsole.log($.name, $.prev, '->', $.current);\n\t$.success();\n});\n```\n\n### PROMISIFY(fn, [a], [b])\n\nType: `method` · Since: `0.0.97`\n\nZabalí funkciu s callbackom do Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia, ktorej posledný argument je `callback(err, response)`. |\n| `a` | `Object` | no |  | Prvý argument pre `fn`. |\n| `b` | `Object` | no |  | Druhý argument pre `fn`. |\n\nReturns: `Promise`\n\nZavolá `fn` so zadanými argumentmi a callbackom `function(err, response)` ako posledným argumentom. Promise sa vyrieši s `response` alebo zamietne s `err`. Prázdne argumenty sa neodovzdávajú.\n\nExample: Čakanie na callback\n```js\nasync function count() {\n\tvar self = this;\n\ttry {\n\t\tvar response = await PROMISIFY(OPERATION, 'users_count');\n\t\tself.json(response);\n\t} catch (err) {\n\t\tself.invalid(err);\n\t}\n}\n```\n\nExample: Čítanie súboru\n```js\nvar body = await PROMISIFY(F.Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\n### NEWCOMMAND(name, fn)\n\nType: `method`\n\nPridá handler pre príkaz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov príkazu. |\n| `fn` | `Function(a, b, c, d)` | yes |  | Handler. `null` odstráni všetky handlery. |\n\nPríkaz môže mať viac handlerov; každé volanie pridá jeden. `NEWCOMMAND(name, null)` odstráni všetky handlery príkazu. Spustíš ho pomocou `CMD()`.\n\nExample: Príkaz\n```js\nNEWCOMMAND('clear_prices', function(category) {\n\tMAIN.prices && delete MAIN.prices[category];\n});\n```\n\n### CMD(name, [a], [b], [c], [d])\n\nType: `method`\n\nSpustí všetky handlery príkazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov príkazu. |\n| `a` | `Object` | no |  | Prvý argument. |\n| `b` | `Object` | no |  | Druhý argument. |\n| `c` | `Object` | no |  | Tretí argument. |\n| `d` | `Object` | no |  | Štvrtý argument. |\n\nOdovzdá každému handleru najviac štyri argumenty. Nerobí nič, keď príkaz nemá žiadny handler. Medzi vstavané príkazy patria `clear_viewscache`, `clear_smtpcache` a `refresh_tms`.\n\nExample: Spustenie príkazu\n```js\nCMD('clear_prices', 'books');\nCMD('clear_viewscache');\n```\n\n### CMD2(name, [a], [b], [c], [d])\n\nType: `method`\n\nVráti funkciu, ktorá spustí príkaz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov príkazu. |\n| `a` | `Object` | no |  | Prvý argument. |\n| `b` | `Object` | no |  | Druhý argument. |\n| `c` | `Object` | no |  | Tretí argument. |\n| `d` | `Object` | no |  | Štvrtý argument. |\n\nReturns: `Function`\n\nVrátená funkcia spustí všetky handlery so zadanými argumentmi. Keď príkaz nemá žiadny handler, vráti `NOOP`.\n\nExample: Neskoršie spustenie príkazu\n```js\nsetTimeout(CMD2('clear_viewscache'), 5000);\n```\n\n### NEWEXTENSION(code, [callback], [extend])\n\nType: `method`\n\nNainštaluje rozšírenie zo zdrojového kódu alebo z URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Zdrojový kód alebo URL. |\n| `callback` | `Function(err, module)` | no |  | Zavolá sa po nainštalovaní rozšírenia. |\n| `extend` | `Function(module)` | no |  | Zavolá sa s modulom pred jeho inštaláciou. |\n\n`code` je JavaScript, ktorý nastavuje `exports`, alebo URL, z ktorej sa stiahne. Voliteľné exporty: `id`, `name`, `install(next)`, `make()`, `done()` a `uninstall()`. Bez `id` je id hash z `name` alebo z kódu. Rozšírenie s rovnakým id sa najprv odstráni. Kód môže byť aj HTML s blokom `<script total>` a blokmi `<file name=\"...\">`; `exports.files` potom mapuje každý názov súboru na dočasnú cestu. Pridaná metóda `remove()` rozšírenie odinštaluje. Súbory v priečinku `/extensions/` sa nainštalujú pri štarte aplikácie.\n\nExample: Inštalácia z reťazca\n```js\nvar code = 'exports.name = \\'Hello\\';\\nexports.make = function() {\\n\\tROUTE(\\'GET /hello/\\', function() { this.plain(\\'Hello\\'); });\\n};';\n\nNEWEXTENSION(code, function(err, module) {\n\tconsole.log(err, module.id);\n});\n```\n\nExample: Inštalácia z URL\n```js\nNEWEXTENSION('https://example.com/extension.js', function(err, module) {\n\terr && console.error(err);\n});\n```\n\n### WORKFLOW(declaration, [tasks])\n\nType: `method`\n\nVytvorí malý stavový automat v pamäti: pomenované kroky, ktoré medzi sebou prechádzajú pomocou `$.next()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `declaration` | `Function` | yes |  | `function($)`, ktorá pridá kroky. |\n| `tasks` | `Object` | no | `{}` | Kroky ako `{ name: function($, value) }`. |\n\nReturns: `Object` Workflow `$`.\n\n`WORKFLOW()` vráti objekt `$` a odovzdá ho do `declaration($)`, kde pridávaš kroky pomocou `$.push(name, fn)`. Každý krok je `function($, value)`. Je to lokálny pomocník, nie zaregistrovaná úloha: nič sa neukladá ani globálne nepomenúva.\n\n| Člen | Čo robí |\n| --- | --- |\n| `$.push(name, fn)` | Pridá krok `fn($, value)` |\n| `$.next(name, [value])` | Spustí krok `name` s `value`; `$.trigger()` je alias. Neznámy názov workflow zničí |\n| `$.next2(name)` | Vráti `function(value)`, ktorá spustí `$.next(name, value)`, pre callbacky |\n| `$.invalid(err)` | Zavolá `$.error(err, $)`, ak ho nastavíš, potom workflow zničí |\n| `$.current`, `$.prev` | Názov aktuálneho a predchádzajúceho kroku |\n| `$.tasks` | Kroky ako objekt |\n| `$.clone()` | Nový workflow s rovnakými krokmi |\n| `$.destroy()` | Ukončí ho; neskoršie volania `$.next()` nerobia nič |\n\n`declaration` môže byť `null`, keď kroky odovzdáš ako `tasks`.\n\nExample: Kroky v poradí\n```js\nvar flow = WORKFLOW(function($) {\n\n\t$.error = function(err) {\n\t\tconsole.log('Error:', err);\n\t};\n\n\t$.push('load', function($, id) {\n\t\tNOSQL('orders').one().where('id', id).callback(function(err, order) {\n\t\t\tif (order)\n\t\t\t\t$.next('send', order);\n\t\t\telse\n\t\t\t\t$.invalid('error-orders-404');\n\t\t});\n\t});\n\n\t$.push('send', function($, order) {\n\t\tMAIL(order.email, 'Your order', 'mails/order', order);\n\t\t$.destroy();\n\t});\n\n});\n\nflow.next('load', '123');\n```\n","entries":[{"type":"method","name":"NEWOPERATION()","signature":"NEWOPERATION(name, fn, [repeat], [stop], [binderror], [filter])","since":"","deprecated":false},{"type":"method","name":"OPERATION()","signature":"OPERATION(name, [value], callback, [options], [controller])","since":"","deprecated":false},{"type":"method","name":"RUN()","signature":"RUN(names, [value], callback, [options], [controller], [response_name])","since":"","deprecated":false},{"type":"method","name":"EACHOPERATION()","signature":"EACHOPERATION(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.options","signature":"$.options","since":"","deprecated":false},{"type":"property","name":"$.name","signature":"$.name","since":"","deprecated":false},{"type":"property","name":"$.error","signature":"$.error","since":"","deprecated":false},{"type":"property","name":"$.controller","signature":"$.controller","since":"","deprecated":false},{"type":"property","name":"$.user","signature":"$.user","since":"","deprecated":false},{"type":"property","name":"$.filter","signature":"$.filter","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback([value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([success], [value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid([name], [error], [path], [index])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([arg])","since":"","deprecated":false},{"type":"method","name":"$.successful()","signature":"$.successful(callback)","since":"","deprecated":false},{"type":"method","name":"$.redirect()","signature":"$.redirect(url)","since":"","deprecated":false},{"type":"method","name":"$.noop()","signature":"$.noop([nocustomresponse])","since":"","deprecated":false},{"type":"method","name":"$.cookie()","signature":"$.cookie(name, [value], [expire], [options])","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data])","since":"","deprecated":false},{"type":"method","name":"$.audit()","signature":"$.audit([message], [type])","since":"","deprecated":false},{"type":"property","name":"$.response","signature":"$.response","since":"","deprecated":false},{"type":"property","name":"$.meta","signature":"$.meta","since":"","deprecated":false},{"type":"property","name":"$.repeated","signature":"$.repeated","since":"","deprecated":false},{"type":"method","name":"NEWTASK()","signature":"NEWTASK(name, fn)","since":"","deprecated":false},{"type":"method","name":"TASK()","signature":"TASK(name, step, callback, [options], [value])","since":"","deprecated":false},{"type":"method","name":"$.next()","signature":"$.next(step, [step2], [...])","since":"","deprecated":false},{"type":"method","name":"$.next2()","signature":"$.next2([step])","since":"","deprecated":false},{"type":"method","name":"$.end()","signature":"$.end([data])","since":"","deprecated":false},{"type":"method","name":"$.end2()","signature":"$.end2([send_value])","since":"","deprecated":false},{"type":"method","name":"$.success()","signature":"$.success([data])","since":"","deprecated":false},{"type":"method","name":"$.done()","signature":"$.done([send_value])","since":"","deprecated":false},{"type":"method","name":"$.invalid()","signature":"$.invalid(err, [msg])","since":"","deprecated":false},{"type":"method","name":"$.push()","signature":"$.push(step, fn)","since":"","deprecated":false},{"type":"method","name":"$.exec()","signature":"$.exec(step, [callback])","since":"","deprecated":false},{"type":"method","name":"$.callback()","signature":"$.callback(fn)","since":"","deprecated":false},{"type":"property","name":"$.value","signature":"$.value","since":"","deprecated":false},{"type":"property","name":"$.current","signature":"$.current","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b])","since":"0.0.97","deprecated":false},{"type":"method","name":"NEWCOMMAND()","signature":"NEWCOMMAND(name, fn)","since":"","deprecated":false},{"type":"method","name":"CMD()","signature":"CMD(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"CMD2()","signature":"CMD2(name, [a], [b], [c], [d])","since":"","deprecated":false},{"type":"method","name":"NEWEXTENSION()","signature":"NEWEXTENSION(code, [callback], [extend])","since":"","deprecated":false},{"type":"method","name":"WORKFLOW()","signature":"WORKFLOW(declaration, [tasks])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Utilities","summary":"The functions of U (utils.js) and the global helpers and objects of the framework.","markdown":"---\ntitle: Utilities\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilities\n\n> The functions of U (utils.js) and the global helpers and objects of the framework.\n\nTotal.js defines helpers in the global scope and in the object `U` (`Utils`), so every file of an app can use them without `require()`. The guide [Utilities](../../guides/utilities/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### U\n\nType: `property`\n\nThe utility library of the framework (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` and `utils` are the same object. It is global, so you use it in controllers, schemas, modules and plugins without `require()`.\n\nExample: Use a helper\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nA global alias of the framework instance `F`.\n\nReturns: `Framework`\n\n`Total`, `F` and `framework` refer to the same object.\n\nExample: Same object\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\nA `Date` that the framework refreshes regularly.\n\nReturns: `Date`\n\nReading `NOW` is cheaper than `new Date()`. The framework sets it again in its internal intervals (about every minute) and in some calls, such as `LOGGER()`. Use it where a precision of a minute is enough; use `new Date()` for an exact time. `F.datetime` reads and writes the same value.\n\nExample: Timestamp of a record\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nA frozen empty object.\n\nReturns: `Object`\n\nUse it as a default value that is never modified. It is frozen, so assignments to it have no effect.\n\nExample: Default options\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nA frozen empty array.\n\nReturns: `Array`\n\nUse it as a default value that is never modified. It is frozen, so `push()` throws an error.\n\nExample: Default list\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nAn empty function.\n\nReturns: `undefined`\n\nPass it where a callback is required and you do not need the result.\n\nExample: Ignore a callback\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nAn empty global object for your own shared data.\n\nReturns: `Object`\n\nThe framework creates `MAIN = {}` and does not use it. Store application-wide values in it, for example data loaded at start.\n\nExample: Shared settings\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nAn empty global object for your own repository of values.\n\nReturns: `Object`\n\nThe framework creates `REPO = {}` and does not use it. It is a second namespace like `MAIN`.\n\nExample: Cache a list\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nAn empty global object for your own shared functions.\n\nReturns: `Object`\n\nThe framework creates `FUNC = {}`. Put helpers there that several files of the app call.\n\nExample: Shared function\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nA global object for temporary data that the framework clears.\n\nReturns: `Object`\n\nThe framework replaces `TEMP` with a new empty object in its periodic cleanup (every `CONF.default_interval_clear_cache` minutes, 10 by default). Do not keep anything there that you need later.\n\nExample: Short-lived value\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nAll loaded modules by their name.\n\nReturns: `Object`\n\nThe same object as `F.modules`. A key is the name of the file in `/modules/` (or the `id` the module exports).\n\nExample: List modules\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nReturns a loaded module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the module. |\n\nReturns: `Object` The module, or `null`.\n\nReads `F.modules[name]`. The result is the `exports` of the module file, or `null` when no module of that name is loaded.\n\nExample: Call a module\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nAppends a line to a log file in the `/logs/` directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the log file without `.log`. |\n| `value` | `Object` | yes |  | One or more values to write. |\n\nReturns: `undefined`\n\nThe line is `yyyy-MM-dd HH:mm:ss | values` in the file `{name}.log`. Values are separated by a space; objects are formatted with `util.inspect()`. The directory is created when it does not exist, and writes go through `U.queue()` with at most 5 writes at the same time.\n\nExample: Log a payment\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nCalls a callback-style function and returns a Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | A function that takes a callback as its last argument. |\n| `a` | `Object` | no |  | First argument. |\n| `b` | `Object` | no |  | Second argument. |\n| `c` | `Object` | no |  | Third argument. |\n\nReturns: `Promise`\n\n`fn` is called with the given arguments and a callback `function(err, response)` as the last argument. The Promise rejects with `err` or resolves with `response`. Up to three arguments are supported; arguments that are `undefined` are not passed.\n\nExample: Read a file\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Your own function\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nWaits until a condition is true.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Returns `true` when the wait is over. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximum time in ms. |\n| `interval` | `Number` | no | `500` | Time between checks in ms. |\n\nReturns: `undefined`\n\n`validator()` is checked at once and then every `interval` ms. When it returns `true`, `callback(null, true)` is called. When `timeout` ms pass first, `callback(Error('Timeout'), false)` is called.\n\nExample: Wait for a connection\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nCreates a short unique identifier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | A name of an independent counter. |\n| `date` | `Date` | no | `NOW` | The time encoded in the ID. |\n\nReturns: `String`\n\nThe ID is a time-based string, for example `24j0y001xn51d`, which sorts by the time it was created. It is unique within the running instance (the framework adds a random instance key). `type` keeps a separate counter for each type, so IDs of different collections do not share a sequence. `date` creates the ID for another time. `CONF.default_uid` selects the version: `r` gives a random ID (`UIDR()`), `f` a base-62 variant; the default is the `d` version.\n\nExample: A new record\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Counter per type\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nCreates a unique identifier with the time part in base 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | A name of an independent counter. |\n| `date` | `Date` | no | `NOW` | The time encoded in the ID. |\n\nReturns: `String`\n\nWorks like `UID()` but encodes the time in hexadecimal, so the ID is a little longer (version `c`). It ignores `CONF.default_uid`.\n\nExample: Hex-based ID\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nCreates a GUID or a random string of a given length.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Length of a random string. |\n\nReturns: `String`\n\nWithout `length` it returns a string in the UUID form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` built from the current time and random numbers. With `length` it returns random lowercase letters and digits of that length. Also available as `U.GUID()`.\n\nExample: UUID form\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Random token\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nCreates a deep copy of an object or an array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object or array to copy. |\n| `skip` | `Object` | no |  | Keys to leave out, as `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Leaves out functions. |\n\nReturns: `Object` A new object.\n\nNested objects and arrays are copied; `Date` and `Error` values are kept by reference, and Buffers are copied. `skip` is an object of keys to leave out (`{ password: 1 }`) on the first level of objects. Also available as `U.clone()`.\n\nExample: Copy without a key\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nCopies all properties of `source` to `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Object to read. |\n| `target` | `Object` | no |  | Object to write. |\n\nReturns: `Object` The target.\n\nEvery key of `source` is cloned into `target`, also keys that `target` does not have. Without `target` it returns a new copy of `source`. It is `U.copy(source, target, true)`.\n\nExample: Merge\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCreates a hash of a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text. |\n| `type` | `String` | no |  | A hash algorithm. |\n\nReturns: `Number|String`\n\nWithout `type` it returns a fast numeric hash (unsigned 32-bit). `type` can be `md5`, `sha1`, `sha256`, `sha512`, `crc32` or `crc32unsigned`. It calls `value.hash()`.\n\nExample: Numeric and MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nAdds an object to a URL as a query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | The URL. |\n| `obj` | `Object` | yes |  | Values of the query string. |\n\nReturns: `String`\n\nValues that are `null` or `undefined` are left out; dates become ISO strings and arrays are joined with commas. Keys and values are encoded. The URL can start with a method (`GET /api/`); the query is added to the path. Without a URL it returns only `?key=value`.\n\nExample: Build a URL\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompares two arrays of objects by a key.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Name of the key, for example `id`. |\n| `db` | `Object[]` | yes |  | The stored items. |\n| `form` | `Object[]` | yes |  | The new items. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nReturns `{ add, upd, rem }`: `add` holds items of `form` that are not in `db`, `upd` holds `{ db, form }` pairs that exist in both, and `rem` holds the key values of items of `db` that are missing in `form`. Use it to save a list that a user edited.\n\nExample: Sync a list\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nReturns a path in the root directory of the app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A relative path. |\n\nReturns: `String`\n\nThe result always uses `/` as the separator.\n\nExample: A file in the root\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nReturns a path in the temporary directory and creates the directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String`\n\nThe directory is `CONF.directory_temp`. `PATH.tmp()` and `PATH.temporary()` are aliases.\n\nExample: Temporary file\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nReturns a path in the databases directory and creates the directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String`\n\nThe directory is `CONF.directory_databases`.\n\nExample: A data file\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nReturns a path in the logs directory and creates the directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String`\n\nThe directory is `CONF.directory_logs`. `LOGGER()` writes there.\n\nExample: Read a log\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nCreates a directory with all missing parent directories.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | An absolute path. |\n| `cache` | `Boolean` | no | `false` | Skips paths created before. |\n\nReturns: `undefined`\n\nIt works synchronously. With `cache` set to `true`, a path that was already created is not checked again until the framework clears its cache.\n\nExample: Directory for uploads\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nReturns a random integer between `min` and `max`, both included.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | The highest value. |\n| `min` | `Number` | no | `0` | The lowest value. |\n\nReturns: `Number`\n\nExample: A dice\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nReturns a random string of letters and digits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Number of characters. |\n\nReturns: `String`\n\nCharacters are `0-9`, `A-Z` and `a-z`.\n\nExample: A code\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nReturns a random string of letters.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Number of characters. |\n\nReturns: `String`\n\nCharacters are `A-Z` and `a-z`, without digits.\n\nExample: Letters only\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nReturns a string of random digits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Number of digits. |\n\nReturns: `String`\n\nThe first digit is never `0`, so `+value` has the same number of digits. The result is a string.\n\nExample: A PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigns an ID so that it cannot be changed by the client.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | The ID. |\n| `key` | `String` | no | `CONF.secret` | A secret key. |\n\nReturns: `String`\n\nThe result contains the ID and a checksum of the ID and the key, for example `n3ck9tg6x123`. The value is not hidden; it is protected against changes. Use `U.decrypt_uid()` to read it back.\n\nExample: Link with a signed ID\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nReads an ID signed by `U.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The signed ID. |\n| `key` | `String` | no | `CONF.secret` | The secret key used to sign it. |\n\nReturns: `String|Number` The ID, or `null`.\n\nReturns the original ID (a number when a number was signed), or `null` when the checksum does not match.\n\nExample: Verify an ID from a URL\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nCopies the values of `source` to the keys that `target` already has.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Object to read. |\n| `target` | `Object` | no |  | Object to write. |\n\nReturns: `Object` The target.\n\nOnly keys that exist in `target` (with a value other than `undefined`) are written; values are cloned. Without `target` it returns a new copy of `source`. To copy all keys, use `COPY()`.\n\nExample: Update known fields\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nAdds the properties of `source` to `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Object to write. |\n| `source` | `Object` | yes |  | Object to read. |\n| `rewrite` | `Boolean` | no | `true` | Overwrites existing values. |\n\nReturns: `Object` The target.\n\nValues are cloned. With `rewrite` set to `false`, keys that already have a value in `target` are kept, so `source` acts as a set of defaults.\n\nExample: Defaults\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nKeeps only some properties of an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | The object or array of objects. |\n| `props` | `String[]|Object` | yes |  | Keys to keep. |\n| `reverse` | `Boolean` | no | `false` | Removes the listed keys instead. |\n\nReturns: `Object|Object[]`\n\n`props` is an array of keys or an object whose keys are used. With `reverse` set to `true`, the listed keys are removed instead. An array as `source` reduces each item. The result is a new object.\n\nExample: Public fields\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nReads a value by a path such as `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object. |\n| `path` | `String` | yes |  | The path with dots. |\n\nReturns: `Object` The value.\n\nReturns `undefined` when a part of the path does not exist. Indexes are written as `items[0].name`. Paths that contain code-like characters (spaces, brackets of calls, `__proto__` and similar) return `undefined`.\n\nExample: Nested value\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nWrites a value by a path such as `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object. |\n| `path` | `String` | yes |  | The path with dots. |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `Object` The value.\n\nMissing objects on the path are created. A path that ends with `[]` pushes the value to an array. Paths that contain code-like characters are ignored.\n\nExample: Build an object\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nTrims all string values of an object or an array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | The value to trim. |\n| `clean` | `Boolean` | no | `false` | Replaces empty strings with `undefined`. |\n\nReturns: `Object` The same value.\n\nNested objects and arrays are trimmed too; the object is changed in place. With `clean` set to `true`, empty strings become `undefined`.\n\nExample: Clean a form\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtracts keywords from a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | The text. |\n| `forSearch` | `Boolean` | no | `true` | Normalizes the words for search. |\n| `alternative` | `Boolean` | no | `false` | Shortens the words. |\n| `max_count` | `Number` | no | `200` | Maximum number of words read. |\n| `max_length` | `Number` | no | `20` | Longer words are skipped. |\n| `min_length` | `Number` | no | `2` | Shorter words are skipped. |\n\nReturns: `String[]`\n\nThe text is lowercased and split into words; the result is a list of unique words, the most frequent first. With `forSearch` (the default), diacritics are removed and `y` is replaced with `i`, so the same words match in a search. `alternative` shortens each word to 80 % of its length to match word forms. `content` can be an array of texts.\n\nExample: Search index\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nRuns functions with a limit of how many run at the same time.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the queue. |\n| `max` | `Number` | yes |  | Maximum running functions. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | A value passed to `fn`. |\n\nReturns: `Boolean`\n\nEach call adds `fn(next, param)` to the queue `name`. At most `max` functions of that queue run at once; each must call `next()` when it finishes. Returns `true` when `fn` starts at once, `false` when it waits.\n\nExample: Three downloads at once\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nCreates a compare function for `Array.sort()` from a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | The sort definition. |\n\nReturns: `Function` `function(a, b)`\n\n`sort` is a list of fields separated by commas, each with an optional `_asc` or `_desc` suffix, for example `price_desc,name`. Nested fields such as `address.city` are supported. Strings, numbers, booleans and dates are compared by their type.\n\nExample: Sort products\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nJoins paths relative to the root directory of the app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | One or more parts of the path. |\n\nReturns: `String` An absolute path.\n\nA part that starts with `~` is an absolute path and replaces what was before it. On Windows the result uses `/`.\n\nExample: Paths in the app\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nJoins parts of a path with `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | One or more parts. |\n\nReturns: `String`\n\nSlashes at the start and the end of each part are removed, and the result starts with `/`. Empty parts are skipped.\n\nExample: Join\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nReturns the extension of a file name without the dot.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The file name or URL. |\n| `raw` | `Boolean` | no | `false` | Keeps the original case. |\n\nReturns: `String`\n\nThe extension is lowercased unless `raw` is `true`. A query string after `?` is ignored. Returns an empty string when there is no extension.\n\nExample: Extension\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nReturns the last part of a path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The path. |\n\nReturns: `String`\n\nWorks with `/` and `\\` separators; a trailing separator is ignored.\n\nExample: File name\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nReturns the content type (MIME type) for an extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | The extension. |\n\nReturns: `String`\n\nThe extension can start with a dot. An unknown extension gives `application/octet-stream`.\n\nExample: MIME type\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nRegisters or changes the content type of an extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | The extension, with or without a dot. |\n| `type` | `String` | yes |  | The content type. |\n\nReturns: `Boolean` `true`\n\nThe framework uses the table to serve static files, so a new extension also becomes a known static file.\n\nExample: A new extension\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nLists all files and directories in a directory and its subdirectories.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | A filter. |\n| `unified` | `Boolean` | no | `false` | Uses `/` on Windows. |\n\nReturns: `Promise|undefined` A Promise without a callback.\n\n`callback(files, directories)` receives arrays of absolute paths. Without a callback the method returns a Promise of `{ files, directories }`. `filter` is a string (part of the name, not case-sensitive), a RegExp, or `function(path, isDirectory)` that returns `true` to keep an item; the string and RegExp filters apply to files only. With `unified` set to `true`, paths on Windows use `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nLists files with their stats.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | A filter. |\n| `unified` | `Boolean` | no | `false` | Uses `/` on Windows. |\n\nReturns: `Promise|undefined` A Promise without a callback.\n\nWorks like `U.ls()`, but each file is `{ filename, stats }`, where `stats` is the `fs.Stats` object (size, dates). Directories are still paths.\n\nExample: Total size\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nEncodes HTML special characters.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `String`\n\n`null` and `undefined` give an empty string; other values are converted to a string first. It calls `String.encode()`.\n\nExample: Safe HTML\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDecodes HTML entities back to characters.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `String`\n\nThe opposite of `U.encode()`. `null` and `undefined` give an empty string.\n\nExample: Plain text\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nEncodes a string or a Buffer to Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | The value. |\n\nReturns: `String`\n\n`U.atob(value)` decodes Base64 back to a UTF-8 string.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nParses XML into a flat object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | The XML. |\n| `replace` | `Boolean` | no | `false` | Replaces special characters in keys. |\n\nReturns: `Object`\n\nEach key is the path of an element joined with dots, for example `root.item`; repeated elements give an array of values. Attributes are stored under the key with `[]`, for example `root.item[]`. With `replace` set to `true`, the characters `[`, `]`, `:`, `.` and `_` in keys become `_`. CDATA is read as text.\n\nExample: Read XML\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConverts any value to an integer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n| `def` | `Number` | no | `0` | Value for empty or invalid input. |\n\nReturns: `Number`\n\n`null`, `undefined` and an empty string give `def`. A number is returned as it is. `U.parseFloat(value, [def])` and `U.parseBoolean(value, [def])` work the same way for decimals and booleans (`def` is `false` for booleans; a number is `true` when it is greater than 0).\n\nExample: Query values\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nReturns the distance between two GPS coordinates in kilometres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Latitude of the first point. |\n| `lon1` | `Number` | yes |  | Longitude of the first point. |\n| `lat2` | `Number` | yes |  | Latitude of the second point. |\n| `lon2` | `Number` | yes |  | Longitude of the second point. |\n\nReturns: `Number` Kilometres.\n\nUses the haversine formula on a sphere with a radius of 6371 km; the result has at most 3 decimal places.\n\nExample: Bratislava to Prague\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifies CSS with the built-in compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | CSS code. |\n\nReturns: `String`\n\nThe same compiler the framework uses for static `.css` files.\n\nExample: Minify\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifies JavaScript with the built-in compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | JavaScript code. |\n\nReturns: `String`\n\nRemoves comments and white space. The same compiler the framework uses for static `.js` files.\n\nExample: Minify\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifies HTML with the built-in compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML code. |\n\nReturns: `String`\n\nRemoves white space between tags.\n\nExample: Minify\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nStores a named status of your app and passes it to `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | The name of the status, or a `$` object. |\n| `data` | `Object` | yes |  | Any value. |\n| `timeout` | `Number` | no |  | Delays the update and merges calls in this time, in milliseconds. |\n\nReturns: `undefined` Nothing.\n\nEach `id` has one status object `{ id, data, date }`. `STATUS()` replaces its `data`, sets `date` and calls `DEF.onStatus(meta)` when you define it. Instead of an `id` you can pass a `$` object; its `ID` (or `name`) is the id.\n\nWith `timeout` (in milliseconds), the update is delayed: the first call starts the timer, later calls only change `data`, and `DEF.onStatus()` runs once with the last data when the timer ends. Use it for values that change often, like a progress.\n\nWith `CONF.allow_stats_status` (default `true`), all statuses are added as `status` to the stats snapshot that Total.js writes to `<main script>.json` (`CONF.allow_stats_snapshot`).\n\nExample: Progress of an import\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nEncrypts a string with a key and a random mask.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | The text to encrypt. |\n| `key` | `String` | yes |  | The key. |\n| `encode` | `String` | no | `base64` | A Buffer encoding or `buffer`. |\n\nReturns: `String|Buffer` The encrypted value.\n\nThe output changes on every call because of a random 4-byte mask. `encode` is a Buffer encoding (default `base64`); `buffer` returns the raw Buffer. Read it back with `U.decrypt_data()` and the same key. This is light obfuscation, not a replacement for `U.encrypt_crypto()`.\n\nExample: Encrypt a JSON string\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nDecrypts a value made by `U.encrypt_data()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | The encrypted value. |\n| `key` | `String` | yes |  | The key used for encryption. |\n| `encode` | `String` | no | `base64` | The encoding of `value`. |\n\nReturns: `String` The decrypted text or `null`.\n\n`value` is a string in the `encode` encoding (default `base64`) or a Buffer. Returns `null` when the value cannot be read. A wrong key gives a wrong string, not `null`, so check the result (for example with `parseJSON()`).\n\nExample: Decrypt a token\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nEncrypts data with a Node.js cipher.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | A cipher name, for example `aes-256-cbc`. |\n| `key` | `String` | yes |  | The key. |\n| `value` | `String|Buffer` | yes |  | The data. |\n\nReturns: `Buffer` The encrypted data.\n\nUses `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. The key length must fit the cipher (32 characters for `aes-256-cbc`). `CONF.default_crypto_iv` is created from the app by default, so set it in the config when other apps must decrypt the data.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nDecrypts data made by `U.encrypt_crypto()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The cipher name. |\n| `key` | `String` | yes |  | The key. |\n| `value` | `Buffer` | yes |  | The encrypted data. |\n\nReturns: `Buffer` The decrypted data or `undefined`.\n\nUses `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Returns `undefined` when the data cannot be decrypted.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nConverts a number to a base-62 string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | A positive number. |\n\nReturns: `String`\n\nThe alphabet is digits, then upper-case and lower-case letters. Decimals are floored. Read it back with `U.from62()`.\n\nExample: Short code\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nConverts a base-62 string from `U.convert62()` back to a number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | A base-62 string. |\n\nReturns: `Number`\n\nExample: Back to a number\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nReturns a fixed-length numeric group for an identifier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | An identifier. |\n| `count` | `Number` | no | `4` | The number of digits. |\n\nReturns: `String` A string of digits.\n\nThe value is `HASH(id, true)` modulo `10^count`, padded with zeros to `count` digits. The same id always gives the same group, so it is useful for spreading files into sub-directories.\n\nExample: Sub-directories\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nConverts any value to a boolean.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | A value. |\n| `def` | `Boolean` | no | `false` | The default value. |\n\nReturns: `Boolean`\n\nA boolean is returned as it is, a number is `true` when greater than `0`, other values are converted to a string and parsed with `String.parseBoolean()`. `null` and `undefined` return `def`.\n\nExample: Query value\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nConverts any value to a decimal number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | A value. |\n| `def` | `Number` | no | `0` | The default value. |\n\nReturns: `Number`\n\nA number is returned as it is, other values are converted to a string and parsed with `String.parseFloat()`. `null`, `undefined` and an empty string return `def`.\n\nExample: Price\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nChecks that a value is a valid `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | A value. |\n\nReturns: `Boolean`\n\nReturns `false` for an invalid date such as `new Date('abc')`.\n\nExample: Validate a date\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nEnglish names of the days of the week.\n\nReturns: `String Array`\n\nThe array starts with `Sunday`, so it matches `Date.getDay()`.\n\nExample: Day name\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nEnglish names of the months.\n\nReturns: `String Array`\n\nThe array starts with `January`, so it matches `Date.getMonth()`.\n\nExample: Month name\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nReturns the text of an HTTP status code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | An HTTP status code. |\n| `addCode` | `Boolean` | no | `true` | Adds the code to the text. |\n\nReturns: `String`\n\nThe text comes from `http.STATUS_CODES`. With `addCode` (default `true`) the code is added in front.\n\nExample: Status text\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSerializes an object into a URL-encoded query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | An object. |\n\nReturns: `String` For example `q=total&page=2`.\n\nStrings are encoded with `encodeURIComponent()`, numbers and booleans are added as they are, arrays are joined with `,`. `null`, `undefined`, empty strings and other objects (including dates) are skipped. Returns an empty string when nothing is added.\n\nExample: Query string\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDecodes a base64 string to a UTF-8 string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | A base64 string. |\n\nReturns: `String`\n\nThe reverse of `U.btoa()`.\n\nExample: Decode\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nChecks that a URL is relative.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | A URL. |\n\nReturns: `Boolean`\n\nReturns `false` when the URL starts with `//` or contains `http://` or `https://`.\n\nExample: Safe redirect\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nChecks that a URL looks like a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | A URL path. |\n\nReturns: `Boolean`\n\nReturns `true` when the last 8 characters of the URL contain a dot, for example `/img/logo.png`.\n\nExample: File or route\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nResolves the IPv4 address of a URL and caches it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | A URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | A value passed to the callback. |\n\nReturns: `Array|undefined` The cached addresses when no callback is given.\n\n`callback(err, uri, param, addresses)` receives the parsed URL with `uri.host` replaced by the first address. The addresses are cached per host; without a callback the method returns the cached addresses (or `undefined`). A failed lookup is tried once more. The `clear_dnscache` command clears the cache.\n\nExample: DNS lookup\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nJoins URL parts with exactly one `/` between them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | One or more URL parts. |\n\nReturns: `String`\n\nUnlike `U.join()`, it does not add a leading `/` and keeps the parts as they are.\n\nExample: Build a URL\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nAdds `/` to the start and the end of a path when it is missing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | A path. |\n\nReturns: `String`\n\nExample: Normalize\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nAdds a trailing delimiter to a path when it is missing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | A path. |\n| `delimiter` | `String` | no | `/` | The delimiter. |\n\nReturns: `String`\n\nAn empty path returns the delimiter.\n\nExample: Directory path\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nReturns the file extension of a content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | A content type. |\n\nReturns: `String`\n\nSearches the content types known to `U.getContentType()` (including the ones added with `U.setContentType()`). Returns the first match without a dot, or `undefined`.\n\nExample: Extension\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nConverts an object into an array of `{ key, value }` items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | An object. |\n\nReturns: `Array`\n\n`null` or `undefined` returns `EMPTYARRAY`.\n\nExample: Key-value list\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nShortcut for `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | The data. |\n| `encoding` | `String` | no | `utf8` | The encoding of a string. |\n\nReturns: `Buffer`\n\nExample: From base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nShortcut for `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | The size in bytes. |\n\nReturns: `Buffer` A buffer filled with zeros.\n\nExample: Empty buffer\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nA `JSON.stringify()` replacer that removes `null` and `undefined` values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key. |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `Object`\n\nExample: Smaller JSON\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nThe state of the queues created by `U.queue()`.\n\nReturns: `Object`\n\nAn object keyed by the queue name. Each item has `limit`, `running` and `pending` (the waiting callbacks). Read it for monitoring only.\n\nExample: Waiting items\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nA small event emitter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | An object to extend. |\n\nReturns: `EventEmitter2`\n\n`new U.EventEmitter2()` creates an emitter. `U.EventEmitter2(obj)` (without `new`) adds `emit()`, `on()`, `once()`, `off()`, `removeListener()` and `removeAllListeners()` to an existing object and returns it; `U.EventEmitter2.extend(obj)` does the same. Listeners are kept in `$events`. `emit()` passes up to 7 arguments and `this` is the emitter.\n\nExample: Extend an object\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nRemoves a listener or all listeners of an event.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name. |\n| `fn` | `Function` | no |  | The listener. |\n\nReturns: `EventEmitter2` The emitter.\n\nWithout `fn` all listeners of `name` are removed. `removeListener()` is an alias. `removeAllListeners([name])` removes the listeners of one event or of all events.\n\nExample: Remove a listener\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nCalls a callback after `next()` was called `count` times.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | How many `next()` calls to wait for. |\n| `callback` | `Function` | no |  | The function to call. |\n\nReturns: `Callback` An instance with `next()` and `done(fn)`.\n\nReturns an instance with `next()` and `done(callback)`. The callback runs once, when the pending count reaches zero. The class is also available as the global `Callback`.\n\nExample: Wait for 3 tasks\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nStores many items in temporary files, page by page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | A unique name, used in the file names. |\n| `max` | `Number` | no | `50` | The number of items per file. |\n\nReturns: `Chunker`\n\nEvery `max` items written with `write()` go to one file `{name}-{index}.chunker` in the temp directory, compressed with deflate. Read them back page by page with `each()` or `read()`. Properties: `compress` (default `true`), `autoremove` (default `true`, removes each file after it is read), `count`, `pages` and `percentage` (progress of `each()`). The class is available as `U.Chunker`.\n\nExample: Export in pages\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nAdds an item.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | An item that can be serialized to JSON. |\n\nReturns: `Chunker`\n\nWhen `max` items are waiting, they are written to a new file. `append()` is an alias. Call `end()` after the last item.\n\nExample: Write\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nWrites the remaining items to the last file.\n\nReturns: `Chunker`\n\nExample: Finish writing\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nReads all pages one by one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | Runs after the last page. |\n\nReturns: `Chunker`\n\n`onItem(items, next, index)` gets the items of one page; call `next()` to read the next page. `onEnd()` runs after the last page. `percentage` shows the progress.\n\nExample: Process pages\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nReads one page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | The page index from `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`callback(err, items)` gets the items of the page, or an empty array when the file does not exist. It waits while files are still being written.\n\nExample: First page\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nRemoves all files of the chunker.\n\nReturns: `Chunker`\n\n`destroy()` also removes the files and releases the instance.\n\nExample: Clean up\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nQueries an array of objects with the NoSQL query builder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | The items or a URL. |\n\nReturns: `Reader`\n\n`items` is an array (or one object), or a URL of TextDB content that is downloaded and streamed. Without `items`, add data with `reader.push(items)` and finish with `reader.push(null)`, or use `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` and `stats(groupfield, datefield, key, [type])` return a NoSQL query builder (`where()`, `sort()`, `take()`, `callback()`...). `list()` returns `{ page, pages, limit, count, items }`. `assign(data)` creates a query from a serialized query object.\n\nExample: Filter an array\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nAdds items to the reader.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | The data, or `null` at the end. |\n\nReturns: `undefined`\n\nPass an array or one object for each chunk of data, then `null` to finish and get the results.\n\nExample: Push data\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nSplits a stream of chunks into parts by delimiters.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | The delimiter or the start of a part. |\n| `end` | `String|Buffer` | no |  | The end of a part. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | The number of parts to skip. |\n| `stream` | `Stream` | no |  | A stream for the `end` event. |\n\nReturns: `Function` `function(chunk)`.\n\nReturns `function(chunk)` that you pass every chunk to. Without `end`, every part ends with `beg` (and includes it), for example a line ending with `\\n`. With `end`, every part starts with `beg` and ends with `end`. `callback(value, index)` gets each part as a string; return `false` to stop. `skip` skips the first parts. With `stream`, the remaining data is processed on the stream `end` event. `U.streamer2()` is the same but gives Buffers.\n\nExample: Read lines\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nSame as `U.streamer()`, but the parts are Buffers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | The delimiter or the start of a part. |\n| `end` | `String|Buffer` | no |  | The end of a part. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | The number of parts to skip. |\n| `stream` | `Stream` | no |  | A stream for the `end` event. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Binary parts\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nReads a text file line by line in batches.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The file. |\n\nReturns: `Object` A stream reader.\n\nReturns a TextDB stream reader. Set `ondocuments` (called with `this.docs`, the lines of one batch joined by `,`; return `false` to stop) and `$callback` (called at the end), then call `openread()`. Set `array = true` to get `docs` as an array of lines. Lines that start with `-` are skipped.\n\nExample: Read a JSON-lines file\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias for Node.js `path.join()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | One or more parts of the path. |\n\nReturns: `String`\n\nExample: Join\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nChecks that a file or directory exists.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | A path. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Check a file\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nCreates an app directory if it does not exist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The directory name. |\n\nReturns: `undefined`\n\n`name` is the name of a `CONF.directory_{name}` setting, for example `databases`. The check runs once per name.\n\nExample: Make sure the directory exists\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias for `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` is an alias for `U.ls2()`.\n\nExample: List files\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nRemoves files one by one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | The files. |\n| `callback` | `Function` | no |  | Runs at the end. |\n\nReturns: `undefined`\n\nErrors are ignored.\n\nExample: Remove files\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nRemoves directories with all their content.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | The directories. |\n| `callback` | `Function` | no |  | Runs at the end. |\n\nReturns: `undefined`\n\nErrors are ignored.\n\nExample: Remove a directory\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nReturns a path in the private directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_private` (default `/private/`).\n\nExample: Path\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nReturns a path in the models directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_models` (default `/models/`).\n\nExample: Path\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nReturns a path in the builds directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_builds` (default `/builds/`).\n\nExample: Path\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nReturns a path in the views directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_views` (default `/views/`).\n\nExample: Path\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nReturns a path in the updates directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_updates` (default `/updates/`).\n\nExample: Path\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nReturns a path in the modules directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_modules` (default `/modules/`).\n\nExample: Path\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nReturns a path in the schemas directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_schemas` (default `/schemas/`).\n\nExample: Path\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nReturns a path in the extensions directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_extensions` (default `/extensions/`).\n\nExample: Path\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nReturns a path in the operations directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_operations` (default `/operations/`).\n\nExample: Path\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nReturns a path in the tasks directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_tasks` (default `/tasks/`).\n\nExample: Path\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nReturns a path in the controllers directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_controllers` (default `/controllers/`).\n\nExample: Path\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nReturns a path in the definitions directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_definitions` (default `/definitions/`).\n\nExample: Path\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nReturns a path in the tests directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_tests` (default `/tests/`).\n\nExample: Path\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nReturns a path in the services directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_services` (default `/services/`).\n\nExample: Path\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nReturns a path in the packages directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_packages` (default `/packages/`).\n\nExample: Path\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nReturns a path in the themes directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_themes` (default `/themes/`).\n\nExample: Path\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nReturns a path in the components directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_components` (default `/components/`).\n\nExample: Path\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nReturns a path in the templates directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_templates` (default `/templates/`).\n\nExample: Path\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nReturns a path in the plugins directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_plugins` (default `/plugins/`).\n\nExample: Path\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nReturns a path in the flowstreams directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name. |\n\nReturns: `String` An absolute path.\n\nThe directory is `CONF.directory_flowstreams` (default `/flowstreams/`).\n\nExample: Path\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nPrints a warning about obsolete code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | What is obsolete. |\n| `message` | `String` | yes |  | What to use instead. |\n\nIt writes the date, the name and the message to the console and increases `F.stats.other.obsolete`. Nothing is printed when `CONF.nowarnings` is `true` (the framework sets it when the watcher restarts the application with `--restart`).\n\nExample: Warn\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nGenerates a unique identifier with a decimal time part.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | A name of a separate counter. |\n| `date` | `Date` | no | `NOW` | The time of the identifier. |\n\nReturns: `String` The identifier.\n\nLike `UID()`, but the time part is the number of minutes since 2020-01-31 23:00 UTC written in decimal digits. Identifiers end with the version letter `b`. With `type`, every type has its own counter. `date` builds the identifier for another time.\n\nExample: Identifier\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Hilfsfunktionen","summary":"Die Funktionen von U (utils.js) sowie die globalen Helfer und Objekte des Frameworks.","markdown":"---\ntitle: Hilfsfunktionen\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Hilfsfunktionen\n\n> Die Funktionen von U (utils.js) sowie die globalen Helfer und Objekte des Frameworks.\n\nTotal.js definiert Helfer im globalen Gültigkeitsbereich und im Objekt `U` (`Utils`), sodass jede Datei einer App sie ohne `require()` verwenden kann. Der Leitfaden [Hilfsfunktionen](../../guides/utilities/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### U\n\nType: `property`\n\nDie Hilfsbibliothek des Frameworks (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` und `utils` sind dasselbe Objekt. Es ist global, daher verwendest du es in Controllern, Schemas, Modulen und Plugins ohne `require()`.\n\nExample: Einen Helfer verwenden\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nEin globaler Alias der Framework-Instanz `F`.\n\nReturns: `Framework`\n\n`Total`, `F` und `framework` verweisen auf dasselbe Objekt.\n\nExample: Dasselbe Objekt\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\nEin `Date`, das das Framework regelmäßig aktualisiert.\n\nReturns: `Date`\n\n`NOW` zu lesen ist günstiger als `new Date()`. Das Framework setzt es in seinen internen Intervallen (etwa jede Minute) und bei manchen Aufrufen wie `LOGGER()` neu. Verwende es, wo eine Genauigkeit von einer Minute genügt; verwende `new Date()` für eine exakte Zeit. `F.datetime` liest und schreibt denselben Wert.\n\nExample: Zeitstempel eines Datensatzes\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nEin eingefrorenes leeres Objekt.\n\nReturns: `Object`\n\nVerwende es als Standardwert, der nie verändert wird. Es ist eingefroren, daher haben Zuweisungen keine Wirkung.\n\nExample: Standardoptionen\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nEin eingefrorenes leeres Array.\n\nReturns: `Array`\n\nVerwende es als Standardwert, der nie verändert wird. Es ist eingefroren, daher wirft `push()` einen Fehler.\n\nExample: Standardliste\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nEine leere Funktion.\n\nReturns: `undefined`\n\nÜbergib sie dort, wo ein Callback erforderlich ist und du das Ergebnis nicht brauchst.\n\nExample: Einen Callback ignorieren\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nEin leeres globales Objekt für deine eigenen gemeinsamen Daten.\n\nReturns: `Object`\n\nDas Framework erstellt `MAIN = {}` und verwendet es nicht. Speichere darin anwendungsweite Werte, zum Beispiel beim Start geladene Daten.\n\nExample: Gemeinsame Einstellungen\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nEin leeres globales Objekt für dein eigenes Repository von Werten.\n\nReturns: `Object`\n\nDas Framework erstellt `REPO = {}` und verwendet es nicht. Es ist ein zweiter Namensraum wie `MAIN`.\n\nExample: Eine Liste cachen\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nEin leeres globales Objekt für deine eigenen gemeinsamen Funktionen.\n\nReturns: `Object`\n\nDas Framework erstellt `FUNC = {}`. Leg dort Helfer ab, die mehrere Dateien der App aufrufen.\n\nExample: Gemeinsame Funktion\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nEin globales Objekt für temporäre Daten, das das Framework leert.\n\nReturns: `Object`\n\nDas Framework ersetzt `TEMP` bei seiner periodischen Bereinigung (alle `CONF.default_interval_clear_cache` Minuten, standardmäßig 10) durch ein neues leeres Objekt. Bewahre dort nichts auf, was du später brauchst.\n\nExample: Kurzlebiger Wert\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nAlle geladenen Module nach ihrem Namen.\n\nReturns: `Object`\n\nDasselbe Objekt wie `F.modules`. Ein Schlüssel ist der Name der Datei in `/modules/` (oder die `id`, die das Modul exportiert).\n\nExample: Module auflisten\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nGibt ein geladenes Modul zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Moduls. |\n\nReturns: `Object` Das Modul oder `null`.\n\nLiest `F.modules[name]`. Das Ergebnis sind die `exports` der Moduldatei oder `null`, wenn kein Modul dieses Namens geladen ist.\n\nExample: Ein Modul aufrufen\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nHängt eine Zeile an eine Logdatei im Verzeichnis `/logs/` an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Logdatei ohne `.log`. |\n| `value` | `Object` | yes |  | Ein oder mehrere zu schreibende Werte. |\n\nReturns: `undefined`\n\nDie Zeile lautet `yyyy-MM-dd HH:mm:ss | values` in der Datei `{name}.log`. Die Werte werden durch ein Leerzeichen getrennt; Objekte werden mit `util.inspect()` formatiert. Das Verzeichnis wird erstellt, wenn es nicht existiert, und Schreibvorgänge laufen über `U.queue()` mit höchstens 5 gleichzeitigen Schreibvorgängen.\n\nExample: Eine Zahlung protokollieren\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nRuft eine Funktion im Callback-Stil auf und gibt eine Promise zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Eine Funktion, die einen Callback als letztes Argument erwartet. |\n| `a` | `Object` | no |  | Erstes Argument. |\n| `b` | `Object` | no |  | Zweites Argument. |\n| `c` | `Object` | no |  | Drittes Argument. |\n\nReturns: `Promise`\n\n`fn` wird mit den angegebenen Argumenten und einem Callback `function(err, response)` als letztem Argument aufgerufen. Die Promise wird mit `err` abgelehnt oder mit `response` aufgelöst. Bis zu drei Argumente werden unterstützt; Argumente, die `undefined` sind, werden nicht übergeben.\n\nExample: Eine Datei lesen\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Deine eigene Funktion\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nWartet, bis eine Bedingung erfüllt ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Gibt `true` zurück, wenn das Warten vorbei ist. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximale Zeit in ms. |\n| `interval` | `Number` | no | `500` | Zeit zwischen den Prüfungen in ms. |\n\nReturns: `undefined`\n\n`validator()` wird sofort und dann alle `interval` ms geprüft. Gibt er `true` zurück, wird `callback(null, true)` aufgerufen. Vergehen zuerst `timeout` ms, wird `callback(Error('Timeout'), false)` aufgerufen.\n\nExample: Auf eine Verbindung warten\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nErstellt einen kurzen, eindeutigen Bezeichner.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Ein Name für einen unabhängigen Zähler. |\n| `date` | `Date` | no | `NOW` | Die in der ID kodierte Zeit. |\n\nReturns: `String`\n\nDie ID ist ein zeitbasierter String, zum Beispiel `24j0y001xn51d`, der nach seiner Erstellungszeit sortierbar ist. Sie ist innerhalb der laufenden Instanz eindeutig (das Framework fügt einen zufälligen Instanzschlüssel hinzu). `type` führt für jeden Typ einen eigenen Zähler, sodass IDs verschiedener Collections keine gemeinsame Sequenz teilen. `date` erstellt die ID für eine andere Zeit. `CONF.default_uid` wählt die Version: `r` ergibt eine zufällige ID (`UIDR()`), `f` eine Base-62-Variante; Standard ist die Version `d`.\n\nExample: Ein neuer Datensatz\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Zähler pro Typ\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nErstellt einen eindeutigen Bezeichner mit dem Zeitanteil zur Basis 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Ein Name für einen unabhängigen Zähler. |\n| `date` | `Date` | no | `NOW` | Die in der ID kodierte Zeit. |\n\nReturns: `String`\n\nFunktioniert wie `UID()`, kodiert die Zeit aber hexadezimal, sodass die ID etwas länger ist (Version `c`). Es ignoriert `CONF.default_uid`.\n\nExample: Hex-basierte ID\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nErstellt eine GUID oder einen zufälligen String einer bestimmten Länge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Länge eines zufälligen Strings. |\n\nReturns: `String`\n\nOhne `length` gibt es einen String in der UUID-Form `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` zurück, gebildet aus der aktuellen Zeit und Zufallszahlen. Mit `length` gibt es zufällige Kleinbuchstaben und Ziffern dieser Länge zurück. Auch als `U.GUID()` verfügbar.\n\nExample: UUID-Form\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Zufälliges Token\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nErstellt eine tiefe Kopie eines Objekts oder eines Arrays.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das zu kopierende Objekt oder Array. |\n| `skip` | `Object` | no |  | Auszulassende Schlüssel, als `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Lässt Funktionen aus. |\n\nReturns: `Object` Ein neues Objekt.\n\nVerschachtelte Objekte und Arrays werden kopiert; `Date`- und `Error`-Werte werden als Referenz behalten, und Buffer werden kopiert. `skip` ist ein Objekt mit Schlüsseln, die auf der ersten Ebene von Objekten ausgelassen werden (`{ password: 1 }`). Auch als `U.clone()` verfügbar.\n\nExample: Ohne einen Schlüssel kopieren\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nKopiert alle Eigenschaften von `source` nach `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Zu lesendes Objekt. |\n| `target` | `Object` | no |  | Zu schreibendes Objekt. |\n\nReturns: `Object` Das Ziel.\n\nJeder Schlüssel von `source` wird in `target` geklont, auch Schlüssel, die `target` nicht hat. Ohne `target` gibt es eine neue Kopie von `source` zurück. Es entspricht `U.copy(source, target, true)`.\n\nExample: Zusammenführen\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nErstellt einen Hash eines Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der Text. |\n| `type` | `String` | no |  | Ein Hash-Algorithmus. |\n\nReturns: `Number|String`\n\nOhne `type` gibt es einen schnellen numerischen Hash zurück (vorzeichenlos, 32 Bit). `type` kann `md5`, `sha1`, `sha256`, `sha512`, `crc32` oder `crc32unsigned` sein. Es ruft `value.hash()` auf.\n\nExample: Numerisch und MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nFügt einer URL ein Objekt als Query String hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Die URL. |\n| `obj` | `Object` | yes |  | Werte des Query Strings. |\n\nReturns: `String`\n\nWerte, die `null` oder `undefined` sind, werden ausgelassen; Datumsangaben werden zu ISO-Strings, und Arrays werden mit Kommas verbunden. Schlüssel und Werte werden kodiert. Die URL kann mit einer Methode beginnen (`GET /api/`); der Query String wird an den Pfad angehängt. Ohne URL gibt es nur `?key=value` zurück.\n\nExample: Eine URL bauen\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nVergleicht zwei Arrays von Objekten anhand eines Schlüssels.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Name des Schlüssels, zum Beispiel `id`. |\n| `db` | `Object[]` | yes |  | Die gespeicherten Elemente. |\n| `form` | `Object[]` | yes |  | Die neuen Elemente. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nGibt `{ add, upd, rem }` zurück: `add` enthält Elemente von `form`, die nicht in `db` sind, `upd` enthält `{ db, form }`-Paare, die in beiden existieren, und `rem` enthält die Schlüsselwerte der Elemente von `db`, die in `form` fehlen. Verwende es, um eine Liste zu speichern, die ein Benutzer bearbeitet hat.\n\nExample: Eine Liste synchronisieren\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nGibt einen Pfad im Stammverzeichnis der App zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein relativer Pfad. |\n\nReturns: `String`\n\nDas Ergebnis verwendet immer `/` als Trennzeichen.\n\nExample: Eine Datei im Stammverzeichnis\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nGibt einen Pfad im temporären Verzeichnis zurück und erstellt das Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String`\n\nDas Verzeichnis ist `CONF.directory_temp`. `PATH.tmp()` und `PATH.temporary()` sind Aliase.\n\nExample: Temporäre Datei\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nGibt einen Pfad im Datenbankverzeichnis zurück und erstellt das Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String`\n\nDas Verzeichnis ist `CONF.directory_databases`.\n\nExample: Eine Datendatei\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nGibt einen Pfad im Log-Verzeichnis zurück und erstellt das Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String`\n\nDas Verzeichnis ist `CONF.directory_logs`. `LOGGER()` schreibt dorthin.\n\nExample: Ein Log lesen\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nErstellt ein Verzeichnis mit allen fehlenden übergeordneten Verzeichnissen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein absoluter Pfad. |\n| `cache` | `Boolean` | no | `false` | Überspringt zuvor erstellte Pfade. |\n\nReturns: `undefined`\n\nEs arbeitet synchron. Ist `cache` auf `true` gesetzt, wird ein bereits erstellter Pfad nicht erneut geprüft, bis das Framework seinen Cache leert.\n\nExample: Verzeichnis für Uploads\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nGibt eine zufällige Ganzzahl zwischen `min` und `max` zurück, beide eingeschlossen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Der höchste Wert. |\n| `min` | `Number` | no | `0` | Der niedrigste Wert. |\n\nReturns: `Number`\n\nExample: Ein Würfel\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nGibt einen zufälligen String aus Buchstaben und Ziffern zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Anzahl der Zeichen. |\n\nReturns: `String`\n\nDie Zeichen sind `0-9`, `A-Z` und `a-z`.\n\nExample: Ein Code\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nGibt einen zufälligen String aus Buchstaben zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Anzahl der Zeichen. |\n\nReturns: `String`\n\nDie Zeichen sind `A-Z` und `a-z`, ohne Ziffern.\n\nExample: Nur Buchstaben\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nGibt einen String aus zufälligen Ziffern zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Anzahl der Ziffern. |\n\nReturns: `String`\n\nDie erste Ziffer ist nie `0`, sodass `+value` dieselbe Anzahl von Ziffern hat. Das Ergebnis ist ein String.\n\nExample: Eine PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigniert eine ID, sodass sie vom Client nicht verändert werden kann.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | Die ID. |\n| `key` | `String` | no | `CONF.secret` | Ein geheimer Schlüssel. |\n\nReturns: `String`\n\nDas Ergebnis enthält die ID und eine Prüfsumme aus der ID und dem Schlüssel, zum Beispiel `n3ck9tg6x123`. Der Wert ist nicht verborgen; er ist gegen Änderungen geschützt. Verwende `U.decrypt_uid()`, um ihn zurückzulesen.\n\nExample: Link mit einer signierten ID\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nLiest eine mit `U.encrypt_uid()` signierte ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Die signierte ID. |\n| `key` | `String` | no | `CONF.secret` | Der geheime Schlüssel, mit dem signiert wurde. |\n\nReturns: `String|Number` Die ID oder `null`.\n\nGibt die ursprüngliche ID zurück (eine Zahl, wenn eine Zahl signiert wurde) oder `null`, wenn die Prüfsumme nicht übereinstimmt.\n\nExample: Eine ID aus einer URL prüfen\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nKopiert die Werte von `source` in die Schlüssel, die `target` bereits hat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Zu lesendes Objekt. |\n| `target` | `Object` | no |  | Zu schreibendes Objekt. |\n\nReturns: `Object` Das Ziel.\n\nNur Schlüssel, die in `target` existieren (mit einem anderen Wert als `undefined`), werden geschrieben; die Werte werden geklont. Ohne `target` gibt es eine neue Kopie von `source` zurück. Um alle Schlüssel zu kopieren, verwende `COPY()`.\n\nExample: Bekannte Felder aktualisieren\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nFügt die Eigenschaften von `source` zu `target` hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Zu schreibendes Objekt. |\n| `source` | `Object` | yes |  | Zu lesendes Objekt. |\n| `rewrite` | `Boolean` | no | `true` | Überschreibt vorhandene Werte. |\n\nReturns: `Object` Das Ziel.\n\nDie Werte werden geklont. Ist `rewrite` auf `false` gesetzt, bleiben Schlüssel erhalten, die in `target` bereits einen Wert haben, sodass `source` als Satz von Standardwerten dient.\n\nExample: Standardwerte\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nBehält nur einige Eigenschaften eines Objekts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | Das Objekt oder Array von Objekten. |\n| `props` | `String[]|Object` | yes |  | Zu behaltende Schlüssel. |\n| `reverse` | `Boolean` | no | `false` | Entfernt stattdessen die aufgeführten Schlüssel. |\n\nReturns: `Object|Object[]`\n\n`props` ist ein Array von Schlüsseln oder ein Objekt, dessen Schlüssel verwendet werden. Ist `reverse` auf `true` gesetzt, werden die aufgeführten Schlüssel stattdessen entfernt. Ein Array als `source` reduziert jedes Element. Das Ergebnis ist ein neues Objekt.\n\nExample: Öffentliche Felder\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLiest einen Wert über einen Pfad wie `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das Objekt. |\n| `path` | `String` | yes |  | Der Pfad mit Punkten. |\n\nReturns: `Object` Der Wert.\n\nGibt `undefined` zurück, wenn ein Teil des Pfades nicht existiert. Indizes werden als `items[0].name` geschrieben. Pfade mit codeähnlichen Zeichen (Leerzeichen, Klammern von Aufrufen, `__proto__` und Ähnliches) geben `undefined` zurück.\n\nExample: Verschachtelter Wert\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nSchreibt einen Wert über einen Pfad wie `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das Objekt. |\n| `path` | `String` | yes |  | Der Pfad mit Punkten. |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `Object` Der Wert.\n\nFehlende Objekte auf dem Pfad werden erstellt. Ein Pfad, der mit `[]` endet, fügt den Wert an ein Array an. Pfade mit codeähnlichen Zeichen werden ignoriert.\n\nExample: Ein Objekt aufbauen\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nTrimmt alle String-Werte eines Objekts oder eines Arrays.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | Der zu trimmende Wert. |\n| `clean` | `Boolean` | no | `false` | Ersetzt leere Strings durch `undefined`. |\n\nReturns: `Object` Derselbe Wert.\n\nVerschachtelte Objekte und Arrays werden ebenfalls getrimmt; das Objekt wird direkt geändert. Ist `clean` auf `true` gesetzt, werden leere Strings zu `undefined`.\n\nExample: Ein Formular bereinigen\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrahiert Schlüsselwörter aus einem Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | Der Text. |\n| `forSearch` | `Boolean` | no | `true` | Normalisiert die Wörter für die Suche. |\n| `alternative` | `Boolean` | no | `false` | Kürzt die Wörter. |\n| `max_count` | `Number` | no | `200` | Maximale Anzahl gelesener Wörter. |\n| `max_length` | `Number` | no | `20` | Längere Wörter werden übersprungen. |\n| `min_length` | `Number` | no | `2` | Kürzere Wörter werden übersprungen. |\n\nReturns: `String[]`\n\nDer Text wird in Kleinbuchstaben umgewandelt und in Wörter aufgeteilt; das Ergebnis ist eine Liste eindeutiger Wörter, die häufigsten zuerst. Mit `forSearch` (Standard) werden diakritische Zeichen entfernt und `y` wird durch `i` ersetzt, sodass dieselben Wörter bei einer Suche übereinstimmen. `alternative` kürzt jedes Wort auf 80 % seiner Länge, um Wortformen abzugleichen. `content` kann ein Array von Texten sein.\n\nExample: Suchindex\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nFührt Funktionen aus und begrenzt, wie viele gleichzeitig laufen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name der Queue. |\n| `max` | `Number` | yes |  | Maximale Anzahl laufender Funktionen. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | Ein Wert, der an `fn` übergeben wird. |\n\nReturns: `Boolean`\n\nJeder Aufruf fügt `fn(next, param)` zur Queue `name` hinzu. Höchstens `max` Funktionen dieser Queue laufen gleichzeitig; jede muss `next()` aufrufen, wenn sie fertig ist. Gibt `true` zurück, wenn `fn` sofort startet, `false`, wenn sie wartet.\n\nExample: Drei Downloads gleichzeitig\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nErstellt aus einem Text eine Vergleichsfunktion für `Array.sort()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Die Sortierdefinition. |\n\nReturns: `Function` `function(a, b)`\n\n`sort` ist eine kommagetrennte Liste von Feldern, jeweils mit einem optionalen Suffix `_asc` oder `_desc`, zum Beispiel `price_desc,name`. Verschachtelte Felder wie `address.city` werden unterstützt. Strings, Zahlen, boolesche Werte und Datumsangaben werden nach ihrem Typ verglichen.\n\nExample: Produkte sortieren\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nVerbindet Pfade relativ zum Stammverzeichnis der App.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein oder mehrere Teile des Pfades. |\n\nReturns: `String` Ein absoluter Pfad.\n\nEin Teil, der mit `~` beginnt, ist ein absoluter Pfad und ersetzt alles davor. Unter Windows verwendet das Ergebnis `/`.\n\nExample: Pfade in der App\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nVerbindet Teile eines Pfades mit `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein oder mehrere Teile. |\n\nReturns: `String`\n\nSchrägstriche am Anfang und am Ende jedes Teils werden entfernt, und das Ergebnis beginnt mit `/`. Leere Teile werden übersprungen.\n\nExample: Verbinden\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nGibt die Endung eines Dateinamens ohne den Punkt zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der Dateiname oder die URL. |\n| `raw` | `Boolean` | no | `false` | Behält die ursprüngliche Groß- und Kleinschreibung bei. |\n\nReturns: `String`\n\nDie Endung wird in Kleinbuchstaben umgewandelt, außer `raw` ist `true`. Ein Query String nach `?` wird ignoriert. Gibt einen leeren String zurück, wenn es keine Endung gibt.\n\nExample: Endung\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nGibt den letzten Teil eines Pfades zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Der Pfad. |\n\nReturns: `String`\n\nFunktioniert mit den Trennzeichen `/` und `\\`; ein abschließendes Trennzeichen wird ignoriert.\n\nExample: Dateiname\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nGibt den Content-Type (MIME-Typ) für eine Endung zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Die Endung. |\n\nReturns: `String`\n\nDie Endung kann mit einem Punkt beginnen. Eine unbekannte Endung ergibt `application/octet-stream`.\n\nExample: MIME-Typ\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nRegistriert oder ändert den Content-Type einer Endung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Die Endung, mit oder ohne Punkt. |\n| `type` | `String` | yes |  | Der Content-Type. |\n\nReturns: `Boolean` `true`\n\nDas Framework verwendet die Tabelle, um statische Dateien auszuliefern, daher wird eine neue Endung auch zu einer bekannten statischen Datei.\n\nExample: Eine neue Endung\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nListet alle Dateien und Verzeichnisse in einem Verzeichnis und seinen Unterverzeichnissen auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Das Verzeichnis. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Ein Filter. |\n| `unified` | `Boolean` | no | `false` | Verwendet `/` unter Windows. |\n\nReturns: `Promise|undefined` Ein Promise, wenn kein Callback übergeben wird.\n\n`callback(files, directories)` erhält Arrays mit absoluten Pfaden. Ohne Callback gibt die Methode ein Promise von `{ files, directories }` zurück. `filter` ist ein String (Teil des Namens, ohne Beachtung der Groß- und Kleinschreibung), ein RegExp oder `function(path, isDirectory)`, die `true` zurückgibt, um ein Element zu behalten; die String- und RegExp-Filter gelten nur für Dateien. Ist `unified` auf `true` gesetzt, verwenden Pfade unter Windows `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nListet Dateien mit ihren Statistiken auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Das Verzeichnis. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Ein Filter. |\n| `unified` | `Boolean` | no | `false` | Verwendet `/` unter Windows. |\n\nReturns: `Promise|undefined` Ein Promise, wenn kein Callback übergeben wird.\n\nFunktioniert wie `U.ls()`, aber jede Datei ist `{ filename, stats }`, wobei `stats` das `fs.Stats`-Objekt ist (Größe, Datumsangaben). Verzeichnisse bleiben Pfade.\n\nExample: Gesamtgröße\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nKodiert HTML-Sonderzeichen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `String`\n\n`null` und `undefined` ergeben einen leeren String; andere Werte werden zuerst in einen String konvertiert. Es ruft `String.encode()` auf.\n\nExample: Sicheres HTML\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDekodiert HTML-Entitäten zurück in Zeichen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `String`\n\nDas Gegenteil von `U.encode()`. `null` und `undefined` ergeben einen leeren String.\n\nExample: Reiner Text\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nKodiert einen String oder einen Buffer in Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Der Wert. |\n\nReturns: `String`\n\n`U.atob(value)` dekodiert Base64 zurück in einen UTF-8-String.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nParst XML in ein flaches Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | Das XML. |\n| `replace` | `Boolean` | no | `false` | Ersetzt Sonderzeichen in Schlüsseln. |\n\nReturns: `Object`\n\nJeder Schlüssel ist der mit Punkten verbundene Pfad eines Elements, zum Beispiel `root.item`; wiederholte Elemente ergeben ein Array von Werten. Attribute werden unter dem Schlüssel mit `[]` gespeichert, zum Beispiel `root.item[]`. Ist `replace` auf `true` gesetzt, werden die Zeichen `[`, `]`, `:`, `.` und `_` in Schlüsseln zu `_`. CDATA wird als Text gelesen.\n\nExample: XML lesen\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nKonvertiert einen beliebigen Wert in eine Ganzzahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n| `def` | `Number` | no | `0` | Wert für leere oder ungültige Eingaben. |\n\nReturns: `Number`\n\n`null`, `undefined` und ein leerer String ergeben `def`. Eine Zahl wird unverändert zurückgegeben. `U.parseFloat(value, [def])` und `U.parseBoolean(value, [def])` funktionieren genauso für Dezimalzahlen und boolesche Werte (`def` ist bei booleschen Werten `false`; eine Zahl ist `true`, wenn sie größer als 0 ist).\n\nExample: Query-Werte\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nGibt die Entfernung zwischen zwei GPS-Koordinaten in Kilometern zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Breitengrad des ersten Punktes. |\n| `lon1` | `Number` | yes |  | Längengrad des ersten Punktes. |\n| `lat2` | `Number` | yes |  | Breitengrad des zweiten Punktes. |\n| `lon2` | `Number` | yes |  | Längengrad des zweiten Punktes. |\n\nReturns: `Number` Kilometer.\n\nVerwendet die Haversine-Formel auf einer Kugel mit einem Radius von 6371 km; das Ergebnis hat höchstens 3 Dezimalstellen.\n\nExample: Bratislava nach Prag\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifiziert CSS mit dem eingebauten Compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | CSS-Code. |\n\nReturns: `String`\n\nDerselbe Compiler, den das Framework für statische `.css`-Dateien verwendet.\n\nExample: Minifizieren\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifiziert JavaScript mit dem eingebauten Compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | JavaScript-Code. |\n\nReturns: `String`\n\nEntfernt Kommentare und Leerraum. Derselbe Compiler, den das Framework für statische `.js`-Dateien verwendet.\n\nExample: Minifizieren\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifiziert HTML mit dem eingebauten Compiler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML-Code. |\n\nReturns: `String`\n\nEntfernt Leerraum zwischen Tags.\n\nExample: Minifizieren\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nSpeichert einen benannten Status deiner App und übergibt ihn an `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | Der Name des Status oder ein `$`-Objekt. |\n| `data` | `Object` | yes |  | Ein beliebiger Wert. |\n| `timeout` | `Number` | no |  | Verzögert die Aktualisierung und fasst Aufrufe in dieser Zeit zusammen, in Millisekunden. |\n\nReturns: `undefined` Nichts.\n\nJede `id` hat ein Statusobjekt `{ id, data, date }`. `STATUS()` ersetzt dessen `data`, setzt `date` und ruft `DEF.onStatus(meta)` auf, wenn du es definierst. Statt einer `id` kannst du ein `$`-Objekt übergeben; dessen `ID` (oder `name`) ist die ID.\n\nMit `timeout` (in Millisekunden) wird die Aktualisierung verzögert: Der erste Aufruf startet den Timer, spätere Aufrufe ändern nur `data`, und `DEF.onStatus()` läuft einmal mit den letzten Daten, wenn der Timer abläuft. Verwende es für Werte, die sich oft ändern, etwa einen Fortschritt.\n\nMit `CONF.allow_stats_status` (standardmäßig `true`) werden alle Status als `status` zum Statistik-Snapshot hinzugefügt, den Total.js in `<main script>.json` schreibt (`CONF.allow_stats_snapshot`).\n\nExample: Fortschritt eines Imports\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nVerschlüsselt einen String mit einem Schlüssel und einer zufälligen Maske.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Der zu verschlüsselnde Text. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `encode` | `String` | no | `base64` | Eine Buffer-Kodierung oder `buffer`. |\n\nReturns: `String|Buffer` Der verschlüsselte Wert.\n\nDie Ausgabe ändert sich bei jedem Aufruf wegen einer zufälligen 4-Byte-Maske. `encode` ist eine Buffer-Kodierung (standardmäßig `base64`); `buffer` gibt den rohen Buffer zurück. Lies es mit `U.decrypt_data()` und demselben Schlüssel zurück. Das ist eine leichte Verschleierung, kein Ersatz für `U.encrypt_crypto()`.\n\nExample: Einen JSON-String verschlüsseln\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nEntschlüsselt einen mit `U.encrypt_data()` erstellten Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Der verschlüsselte Wert. |\n| `key` | `String` | yes |  | Der für die Verschlüsselung verwendete Schlüssel. |\n| `encode` | `String` | no | `base64` | Die Kodierung von `value`. |\n\nReturns: `String` Der entschlüsselte Text oder `null`.\n\n`value` ist ein String in der Kodierung `encode` (standardmäßig `base64`) oder ein Buffer. Gibt `null` zurück, wenn der Wert nicht gelesen werden kann. Ein falscher Schlüssel ergibt einen falschen String, nicht `null`, also prüfe das Ergebnis (zum Beispiel mit `parseJSON()`).\n\nExample: Ein Token entschlüsseln\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nVerschlüsselt Daten mit einer Node.js-Chiffre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Ein Chiffrenname, zum Beispiel `aes-256-cbc`. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `String|Buffer` | yes |  | Die Daten. |\n\nReturns: `Buffer` Die verschlüsselten Daten.\n\nVerwendet `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. Die Schlüssellänge muss zur Chiffre passen (32 Zeichen für `aes-256-cbc`). `CONF.default_crypto_iv` wird standardmäßig aus der App erzeugt, also setz es in der Konfiguration, wenn andere Apps die Daten entschlüsseln müssen.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nEntschlüsselt mit `U.encrypt_crypto()` erstellte Daten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Der Chiffrenname. |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `Buffer` | yes |  | Die verschlüsselten Daten. |\n\nReturns: `Buffer` Die entschlüsselten Daten oder `undefined`.\n\nVerwendet `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Gibt `undefined` zurück, wenn die Daten nicht entschlüsselt werden können.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nKonvertiert eine Zahl in einen Base-62-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Eine positive Zahl. |\n\nReturns: `String`\n\nDas Alphabet besteht aus Ziffern, dann Groß- und Kleinbuchstaben. Dezimalstellen werden abgerundet. Lies es mit `U.from62()` zurück.\n\nExample: Kurzer Code\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nKonvertiert einen Base-62-String aus `U.convert62()` zurück in eine Zahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Ein Base-62-String. |\n\nReturns: `Number`\n\nExample: Zurück in eine Zahl\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nGibt eine numerische Gruppe fester Länge für einen Bezeichner zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Ein Bezeichner. |\n| `count` | `Number` | no | `4` | Die Anzahl der Ziffern. |\n\nReturns: `String` Ein String aus Ziffern.\n\nDer Wert ist `HASH(id, true)` modulo `10^count`, mit Nullen auf `count` Ziffern aufgefüllt. Dieselbe ID ergibt immer dieselbe Gruppe, daher ist es nützlich, um Dateien auf Unterverzeichnisse zu verteilen.\n\nExample: Unterverzeichnisse\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nKonvertiert einen beliebigen Wert in einen booleschen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ein Wert. |\n| `def` | `Boolean` | no | `false` | Der Standardwert. |\n\nReturns: `Boolean`\n\nEin boolescher Wert wird unverändert zurückgegeben, eine Zahl ist `true`, wenn sie größer als `0` ist, andere Werte werden in einen String konvertiert und mit `String.parseBoolean()` geparst. `null` und `undefined` geben `def` zurück.\n\nExample: Query-Wert\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nKonvertiert einen beliebigen Wert in eine Dezimalzahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ein Wert. |\n| `def` | `Number` | no | `0` | Der Standardwert. |\n\nReturns: `Number`\n\nEine Zahl wird unverändert zurückgegeben, andere Werte werden in einen String konvertiert und mit `String.parseFloat()` geparst. `null`, `undefined` und ein leerer String geben `def` zurück.\n\nExample: Preis\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nPrüft, ob ein Wert ein gültiges `Date` ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Ein Wert. |\n\nReturns: `Boolean`\n\nGibt `false` für ein ungültiges Datum wie `new Date('abc')` zurück.\n\nExample: Ein Datum validieren\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nEnglische Namen der Wochentage.\n\nReturns: `String Array`\n\nDas Array beginnt mit `Sunday`, sodass es zu `Date.getDay()` passt.\n\nExample: Tagesname\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nEnglische Namen der Monate.\n\nReturns: `String Array`\n\nDas Array beginnt mit `January`, sodass es zu `Date.getMonth()` passt.\n\nExample: Monatsname\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nGibt den Text eines HTTP-Statuscodes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Ein HTTP-Statuscode. |\n| `addCode` | `Boolean` | no | `true` | Fügt den Code zum Text hinzu. |\n\nReturns: `String`\n\nDer Text stammt aus `http.STATUS_CODES`. Mit `addCode` (standardmäßig `true`) wird der Code vorangestellt.\n\nExample: Statustext\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSerialisiert ein Objekt in einen URL-kodierten Query String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Ein Objekt. |\n\nReturns: `String` Zum Beispiel `q=total&page=2`.\n\nStrings werden mit `encodeURIComponent()` kodiert, Zahlen und boolesche Werte werden unverändert hinzugefügt, Arrays werden mit `,` verbunden. `null`, `undefined`, leere Strings und andere Objekte (einschließlich Datumsangaben) werden übersprungen. Gibt einen leeren String zurück, wenn nichts hinzugefügt wird.\n\nExample: Query String\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDekodiert einen Base64-String in einen UTF-8-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Ein Base64-String. |\n\nReturns: `String`\n\nDie Umkehrung von `U.btoa()`.\n\nExample: Dekodieren\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nPrüft, ob eine URL relativ ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Eine URL. |\n\nReturns: `Boolean`\n\nGibt `false` zurück, wenn die URL mit `//` beginnt oder `http://` bzw. `https://` enthält.\n\nExample: Sichere Weiterleitung\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nPrüft, ob eine URL wie eine Datei aussieht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Ein URL-Pfad. |\n\nReturns: `Boolean`\n\nGibt `true` zurück, wenn die letzten 8 Zeichen der URL einen Punkt enthalten, zum Beispiel `/img/logo.png`.\n\nExample: Datei oder Route\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nLöst die IPv4-Adresse einer URL auf und cacht sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Eine URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | Ein Wert, der an den Callback übergeben wird. |\n\nReturns: `Array|undefined` Die gecachten Adressen, wenn kein Callback übergeben wird.\n\n`callback(err, uri, param, addresses)` erhält die geparste URL, wobei `uri.host` durch die erste Adresse ersetzt ist. Die Adressen werden pro Host gecacht; ohne Callback gibt die Methode die gecachten Adressen (oder `undefined`) zurück. Eine fehlgeschlagene Auflösung wird noch einmal versucht. Der Befehl `clear_dnscache` leert den Cache.\n\nExample: DNS-Abfrage\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nVerbindet URL-Teile mit genau einem `/` dazwischen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein oder mehrere URL-Teile. |\n\nReturns: `String`\n\nAnders als `U.join()` fügt es kein führendes `/` hinzu und lässt die Teile unverändert.\n\nExample: Eine URL bauen\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nFügt am Anfang und am Ende eines Pfades `/` hinzu, wenn es fehlt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein Pfad. |\n\nReturns: `String`\n\nExample: Normalisieren\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nFügt einem Pfad ein abschließendes Trennzeichen hinzu, wenn es fehlt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein Pfad. |\n| `delimiter` | `String` | no | `/` | Das Trennzeichen. |\n\nReturns: `String`\n\nEin leerer Pfad gibt das Trennzeichen zurück.\n\nExample: Verzeichnispfad\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nGibt die Dateiendung eines Content-Types zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | Ein Content-Type. |\n\nReturns: `String`\n\nDurchsucht die Content-Types, die `U.getContentType()` kennt (einschließlich der mit `U.setContentType()` hinzugefügten). Gibt den ersten Treffer ohne Punkt zurück oder `undefined`.\n\nExample: Endung\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nKonvertiert ein Objekt in ein Array von `{ key, value }`-Elementen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Ein Objekt. |\n\nReturns: `Array`\n\n`null` oder `undefined` gibt `EMPTYARRAY` zurück.\n\nExample: Schlüssel-Wert-Liste\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nKurzform für `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | Die Daten. |\n| `encoding` | `String` | no | `utf8` | Die Kodierung eines Strings. |\n\nReturns: `Buffer`\n\nExample: Aus Base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nKurzform für `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | Die Größe in Bytes. |\n\nReturns: `Buffer` Ein mit Nullen gefüllter Buffer.\n\nExample: Leerer Buffer\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nEin Replacer für `JSON.stringify()`, der `null`- und `undefined`-Werte entfernt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel. |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `Object`\n\nExample: Kleineres JSON\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nDer Zustand der mit `U.queue()` erstellten Queues.\n\nReturns: `Object`\n\nEin Objekt mit dem Namen der Queue als Schlüssel. Jedes Element hat `limit`, `running` und `pending` (die wartenden Callbacks). Lies es nur zur Überwachung.\n\nExample: Wartende Elemente\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nEin kleiner Event-Emitter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Ein zu erweiterndes Objekt. |\n\nReturns: `EventEmitter2`\n\n`new U.EventEmitter2()` erstellt einen Emitter. `U.EventEmitter2(obj)` (ohne `new`) fügt einem vorhandenen Objekt `emit()`, `on()`, `once()`, `off()`, `removeListener()` und `removeAllListeners()` hinzu und gibt es zurück; `U.EventEmitter2.extend(obj)` macht dasselbe. Listener werden in `$events` gehalten. `emit()` übergibt bis zu 7 Argumente, und `this` ist der Emitter.\n\nExample: Ein Objekt erweitern\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nEntfernt einen Listener oder alle Listener eines Events.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events. |\n| `fn` | `Function` | no |  | Der Listener. |\n\nReturns: `EventEmitter2` Der Emitter.\n\nOhne `fn` werden alle Listener von `name` entfernt. `removeListener()` ist ein Alias. `removeAllListeners([name])` entfernt die Listener eines Events oder aller Events.\n\nExample: Einen Listener entfernen\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nRuft einen Callback auf, nachdem `next()` `count`-mal aufgerufen wurde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Auf wie viele `next()`-Aufrufe gewartet wird. |\n| `callback` | `Function` | no |  | Die aufzurufende Funktion. |\n\nReturns: `Callback` Eine Instanz mit `next()` und `done(fn)`.\n\nGibt eine Instanz mit `next()` und `done(callback)` zurück. Der Callback läuft einmal, wenn der ausstehende Zähler null erreicht. Die Klasse ist auch als globales `Callback` verfügbar.\n\nExample: Auf 3 Aufgaben warten\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nSpeichert viele Elemente seitenweise in temporären Dateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ein eindeutiger Name, der in den Dateinamen verwendet wird. |\n| `max` | `Number` | no | `50` | Die Anzahl der Elemente pro Datei. |\n\nReturns: `Chunker`\n\nJe `max` mit `write()` geschriebene Elemente landen in einer Datei `{name}-{index}.chunker` im temporären Verzeichnis, komprimiert mit Deflate. Lies sie seitenweise mit `each()` oder `read()` zurück. Eigenschaften: `compress` (standardmäßig `true`), `autoremove` (standardmäßig `true`, entfernt jede Datei, nachdem sie gelesen wurde), `count`, `pages` und `percentage` (Fortschritt von `each()`). Die Klasse ist als `U.Chunker` verfügbar.\n\nExample: Seitenweise exportieren\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nFügt ein Element hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Ein Element, das nach JSON serialisiert werden kann. |\n\nReturns: `Chunker`\n\nWarten `max` Elemente, werden sie in eine neue Datei geschrieben. `append()` ist ein Alias. Ruf nach dem letzten Element `end()` auf.\n\nExample: Schreiben\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nSchreibt die verbleibenden Elemente in die letzte Datei.\n\nReturns: `Chunker`\n\nExample: Schreiben abschließen\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nLiest alle Seiten nacheinander.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | Läuft nach der letzten Seite. |\n\nReturns: `Chunker`\n\n`onItem(items, next, index)` erhält die Elemente einer Seite; ruf `next()` auf, um die nächste Seite zu lesen. `onEnd()` läuft nach der letzten Seite. `percentage` zeigt den Fortschritt.\n\nExample: Seiten verarbeiten\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nLiest eine Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | Der Seitenindex ab `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`callback(err, items)` erhält die Elemente der Seite oder ein leeres Array, wenn die Datei nicht existiert. Es wartet, solange noch Dateien geschrieben werden.\n\nExample: Erste Seite\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nEntfernt alle Dateien des Chunkers.\n\nReturns: `Chunker`\n\n`destroy()` entfernt ebenfalls die Dateien und gibt die Instanz frei.\n\nExample: Aufräumen\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nFragt ein Array von Objekten mit dem NoSQL-Query-Builder ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | Die Elemente oder eine URL. |\n\nReturns: `Reader`\n\n`items` ist ein Array (oder ein einzelnes Objekt) oder eine URL mit TextDB-Inhalt, der heruntergeladen und gestreamt wird. Ohne `items` fügst du Daten mit `reader.push(items)` hinzu und schließt mit `reader.push(null)` ab, oder du verwendest `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` und `stats(groupfield, datefield, key, [type])` geben einen NoSQL-Query-Builder zurück (`where()`, `sort()`, `take()`, `callback()`...). `list()` gibt `{ page, pages, limit, count, items }` zurück. `assign(data)` erstellt eine Abfrage aus einem serialisierten Abfrageobjekt.\n\nExample: Ein Array filtern\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nFügt dem Reader Elemente hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | Die Daten oder `null` am Ende. |\n\nReturns: `undefined`\n\nÜbergib für jeden Datenblock ein Array oder ein einzelnes Objekt, dann `null`, um abzuschließen und die Ergebnisse zu erhalten.\n\nExample: Daten hinzufügen\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nTeilt einen Stream von Chunks anhand von Begrenzern in Teile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Der Begrenzer oder der Anfang eines Teils. |\n| `end` | `String|Buffer` | no |  | Das Ende eines Teils. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | Die Anzahl der zu überspringenden Teile. |\n| `stream` | `Stream` | no |  | Ein Stream für das Event `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nGibt `function(chunk)` zurück, an die du jeden Chunk übergibst. Ohne `end` endet jeder Teil mit `beg` (und enthält es), zum Beispiel eine Zeile, die mit `\\n` endet. Mit `end` beginnt jeder Teil mit `beg` und endet mit `end`. `callback(value, index)` erhält jeden Teil als String; gib `false` zurück, um abzubrechen. `skip` überspringt die ersten Teile. Mit `stream` werden die verbleibenden Daten beim Event `end` des Streams verarbeitet. `U.streamer2()` ist dasselbe, liefert aber Buffer.\n\nExample: Zeilen lesen\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDasselbe wie `U.streamer()`, aber die Teile sind Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Der Begrenzer oder der Anfang eines Teils. |\n| `end` | `String|Buffer` | no |  | Das Ende eines Teils. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | Die Anzahl der zu überspringenden Teile. |\n| `stream` | `Stream` | no |  | Ein Stream für das Event `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Binäre Teile\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nLiest eine Textdatei zeilenweise in Batches.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die Datei. |\n\nReturns: `Object` Ein Stream-Reader.\n\nGibt einen TextDB-Stream-Reader zurück. Setz `ondocuments` (wird mit `this.docs` aufgerufen, den durch `,` verbundenen Zeilen eines Batches; gib `false` zurück, um abzubrechen) und `$callback` (wird am Ende aufgerufen) und ruf dann `openread()` auf. Setz `array = true`, um `docs` als Array von Zeilen zu erhalten. Zeilen, die mit `-` beginnen, werden übersprungen.\n\nExample: Eine JSON-Lines-Datei lesen\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias für `path.join()` von Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein oder mehrere Teile des Pfades. |\n\nReturns: `String`\n\nExample: Verbinden\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nPrüft, ob eine Datei oder ein Verzeichnis existiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Ein Pfad. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Eine Datei prüfen\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nErstellt ein App-Verzeichnis, wenn es nicht existiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Verzeichnisses. |\n\nReturns: `undefined`\n\n`name` ist der Name einer Einstellung `CONF.directory_{name}`, zum Beispiel `databases`. Die Prüfung läuft einmal pro Name.\n\nExample: Sicherstellen, dass das Verzeichnis existiert\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias für `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Das Verzeichnis. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` ist ein Alias für `U.ls2()`.\n\nExample: Dateien auflisten\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nEntfernt Dateien nacheinander.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | Die Dateien. |\n| `callback` | `Function` | no |  | Läuft am Ende. |\n\nReturns: `undefined`\n\nFehler werden ignoriert.\n\nExample: Dateien entfernen\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nEntfernt Verzeichnisse mit ihrem gesamten Inhalt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | Die Verzeichnisse. |\n| `callback` | `Function` | no |  | Läuft am Ende. |\n\nReturns: `undefined`\n\nFehler werden ignoriert.\n\nExample: Ein Verzeichnis entfernen\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nGibt einen Pfad im privaten Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_private` (standardmäßig `/private/`).\n\nExample: Pfad\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nGibt einen Pfad im Models-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_models` (standardmäßig `/models/`).\n\nExample: Pfad\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nGibt einen Pfad im Builds-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_builds` (standardmäßig `/builds/`).\n\nExample: Pfad\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nGibt einen Pfad im Views-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_views` (standardmäßig `/views/`).\n\nExample: Pfad\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nGibt einen Pfad im Updates-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_updates` (standardmäßig `/updates/`).\n\nExample: Pfad\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nGibt einen Pfad im Modulverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_modules` (standardmäßig `/modules/`).\n\nExample: Pfad\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nGibt einen Pfad im Schemaverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_schemas` (standardmäßig `/schemas/`).\n\nExample: Pfad\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nGibt einen Pfad im Extensions-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_extensions` (standardmäßig `/extensions/`).\n\nExample: Pfad\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nGibt einen Pfad im Operationsverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_operations` (standardmäßig `/operations/`).\n\nExample: Pfad\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nGibt einen Pfad im Tasks-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_tasks` (standardmäßig `/tasks/`).\n\nExample: Pfad\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nGibt einen Pfad im Controller-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_controllers` (standardmäßig `/controllers/`).\n\nExample: Pfad\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nGibt einen Pfad im Definitionsverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_definitions` (standardmäßig `/definitions/`).\n\nExample: Pfad\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nGibt einen Pfad im Testverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_tests` (standardmäßig `/tests/`).\n\nExample: Pfad\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nGibt einen Pfad im Services-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_services` (standardmäßig `/services/`).\n\nExample: Pfad\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nGibt einen Pfad im Paketverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_packages` (standardmäßig `/packages/`).\n\nExample: Pfad\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nGibt einen Pfad im Themes-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_themes` (standardmäßig `/themes/`).\n\nExample: Pfad\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nGibt einen Pfad im Komponentenverzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_components` (standardmäßig `/components/`).\n\nExample: Pfad\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nGibt einen Pfad im Templates-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_templates` (standardmäßig `/templates/`).\n\nExample: Pfad\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nGibt einen Pfad im Plugin-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_plugins` (standardmäßig `/plugins/`).\n\nExample: Pfad\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nGibt einen Pfad im FlowStreams-Verzeichnis zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname. |\n\nReturns: `String` Ein absoluter Pfad.\n\nDas Verzeichnis ist `CONF.directory_flowstreams` (standardmäßig `/flowstreams/`).\n\nExample: Pfad\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nGibt eine Warnung zu veraltetem Code aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Was veraltet ist. |\n| `message` | `String` | yes |  | Was stattdessen zu verwenden ist. |\n\nEs schreibt das Datum, den Namen und die Nachricht in die Konsole und erhöht `F.stats.other.obsolete`. Nichts wird ausgegeben, wenn `CONF.nowarnings` gleich `true` ist (das Framework setzt es, wenn der Watcher die Anwendung mit `--restart` neu startet).\n\nExample: Warnen\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nErzeugt eine eindeutige Kennung mit einem dezimalen Zeitanteil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Ein Name für einen separaten Zähler. |\n| `date` | `Date` | no | `NOW` | Der Zeitpunkt der Kennung. |\n\nReturns: `String` Die Kennung.\n\nWie `UID()`, aber der Zeitanteil ist die Anzahl der Minuten seit 2020-01-31 23:00 UTC in Dezimalziffern. Kennungen enden mit dem Versionsbuchstaben `b`. Mit `type` hat jeder Typ einen eigenen Zähler. `date` erzeugt die Kennung für einen anderen Zeitpunkt.\n\nExample: Kennung\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Utilidades","summary":"Las funciones de U (utils.js) y las utilidades y objetos globales del framework.","markdown":"---\ntitle: Utilidades\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilidades\n\n> Las funciones de U (utils.js) y las utilidades y objetos globales del framework.\n\nTotal.js define utilidades en el ámbito global y en el objeto `U` (`Utils`), así que cualquier archivo de una aplicación puede usarlas sin `require()`. La guía [Utilidades](../../guides/utilities/) explica cómo usarlas con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### U\n\nType: `property`\n\nLa biblioteca de utilidades del framework (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` y `utils` son el mismo objeto. Es global, así que lo usas en controladores, esquemas, módulos y plugins sin `require()`.\n\nExample: Usar una utilidad\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nUn alias global de la instancia del framework `F`.\n\nReturns: `Framework`\n\n`Total`, `F` y `framework` hacen referencia al mismo objeto.\n\nExample: El mismo objeto\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\nUn `Date` que el framework actualiza periódicamente.\n\nReturns: `Date`\n\nLeer `NOW` es más barato que `new Date()`. El framework lo vuelve a definir en sus intervalos internos (aproximadamente cada minuto) y en algunas llamadas, como `LOGGER()`. Úsalo cuando baste con una precisión de un minuto; usa `new Date()` para una hora exacta. `F.datetime` lee y escribe el mismo valor.\n\nExample: Marca de tiempo de un registro\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn objeto vacío congelado.\n\nReturns: `Object`\n\nÚsalo como valor predeterminado que nunca se modifica. Está congelado, así que las asignaciones no tienen efecto.\n\nExample: Opciones predeterminadas\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nUn array vacío congelado.\n\nReturns: `Array`\n\nÚsalo como valor predeterminado que nunca se modifica. Está congelado, así que `push()` lanza un error.\n\nExample: Lista predeterminada\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nUna función vacía.\n\nReturns: `undefined`\n\nPásala donde se requiere un callback y no necesitas el resultado.\n\nExample: Ignorar un callback\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nUn objeto global vacío para tus propios datos compartidos.\n\nReturns: `Object`\n\nEl framework crea `MAIN = {}` y no lo usa. Guarda en él valores de toda la aplicación, por ejemplo datos cargados al arrancar.\n\nExample: Ajustes compartidos\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nUn objeto global vacío para tu propio repositorio de valores.\n\nReturns: `Object`\n\nEl framework crea `REPO = {}` y no lo usa. Es un segundo espacio de nombres como `MAIN`.\n\nExample: Guardar una lista en caché\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nUn objeto global vacío para tus propias funciones compartidas.\n\nReturns: `Object`\n\nEl framework crea `FUNC = {}`. Pon ahí las utilidades que llaman varios archivos de la aplicación.\n\nExample: Función compartida\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn objeto global para datos temporales que el framework vacía.\n\nReturns: `Object`\n\nEl framework reemplaza `TEMP` por un nuevo objeto vacío en su limpieza periódica (cada `CONF.default_interval_clear_cache` minutos, 10 por defecto). No guardes ahí nada que necesites más tarde.\n\nExample: Valor de corta duración\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nTodos los módulos cargados, por su nombre.\n\nReturns: `Object`\n\nEl mismo objeto que `F.modules`. Una clave es el nombre del archivo en `/modules/` (o el `id` que exporta el módulo).\n\nExample: Listar módulos\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nDevuelve un módulo cargado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del módulo. |\n\nReturns: `Object` El módulo, o `null`.\n\nLee `F.modules[name]`. El resultado son los `exports` del archivo del módulo, o `null` cuando no hay ningún módulo cargado con ese nombre.\n\nExample: Llamar a un módulo\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nAñade una línea a un archivo de log en el directorio `/logs/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del archivo de log sin `.log`. |\n| `value` | `Object` | yes |  | Uno o varios valores que se escriben. |\n\nReturns: `undefined`\n\nLa línea es `yyyy-MM-dd HH:mm:ss | values` en el archivo `{name}.log`. Los valores se separan con un espacio; los objetos se formatean con `util.inspect()`. El directorio se crea cuando no existe, y las escrituras pasan por `U.queue()` con como máximo 5 escrituras a la vez.\n\nExample: Registrar un pago\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nLlama a una función de estilo callback y devuelve una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una función que recibe un callback como último argumento. |\n| `a` | `Object` | no |  | Primer argumento. |\n| `b` | `Object` | no |  | Segundo argumento. |\n| `c` | `Object` | no |  | Tercer argumento. |\n\nReturns: `Promise`\n\n`fn` se llama con los argumentos dados y un callback `function(err, response)` como último argumento. La Promise se rechaza con `err` o se resuelve con `response`. Se admiten hasta tres argumentos; los argumentos que son `undefined` no se pasan.\n\nExample: Leer un archivo\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Tu propia función\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nEspera hasta que una condición sea verdadera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Devuelve `true` cuando la espera ha terminado. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Tiempo máximo en ms. |\n| `interval` | `Number` | no | `500` | Tiempo entre comprobaciones en ms. |\n\nReturns: `undefined`\n\n`validator()` se comprueba de inmediato y después cada `interval` ms. Cuando devuelve `true`, se llama a `callback(null, true)`. Cuando pasan antes `timeout` ms, se llama a `callback(Error('Timeout'), false)`.\n\nExample: Esperar a una conexión\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nCrea un identificador único corto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Un nombre de contador independiente. |\n| `date` | `Date` | no | `NOW` | El momento codificado en el ID. |\n\nReturns: `String`\n\nEl ID es una cadena basada en el tiempo, por ejemplo `24j0y001xn51d`, que se ordena por el momento en que se creó. Es único dentro de la instancia en ejecución (el framework añade una clave aleatoria de instancia). `type` mantiene un contador independiente para cada tipo, así que los IDs de colecciones distintas no comparten secuencia. `date` crea el ID para otro momento. `CONF.default_uid` elige la versión: `r` da un ID aleatorio (`UIDR()`), `f` una variante en base 62; la predeterminada es la versión `d`.\n\nExample: Un nuevo registro\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Contador por tipo\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nCrea un identificador único con la parte del tiempo en base 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Un nombre de contador independiente. |\n| `date` | `Date` | no | `NOW` | El momento codificado en el ID. |\n\nReturns: `String`\n\nFunciona como `UID()` pero codifica el tiempo en hexadecimal, así que el ID es algo más largo (versión `c`). Ignora `CONF.default_uid`.\n\nExample: ID en hexadecimal\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nCrea un GUID o una cadena aleatoria de una longitud dada.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Longitud de una cadena aleatoria. |\n\nReturns: `String`\n\nSin `length` devuelve una cadena con la forma UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` creada a partir de la hora actual y números aleatorios. Con `length` devuelve letras minúsculas y dígitos aleatorios de esa longitud. También está disponible como `U.GUID()`.\n\nExample: Forma UUID\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Token aleatorio\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nCrea una copia profunda de un objeto o un array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto o array que se copia. |\n| `skip` | `Object` | no |  | Claves que se omiten, como `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Omite las funciones. |\n\nReturns: `Object` Un nuevo objeto.\n\nSe copian los objetos y arrays anidados; los valores `Date` y `Error` se mantienen por referencia, y los Buffers se copian. `skip` es un objeto con las claves que se omiten (`{ password: 1 }`) en el primer nivel de los objetos. También está disponible como `U.clone()`.\n\nExample: Copiar sin una clave\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nCopia todas las propiedades de `source` a `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objeto que se lee. |\n| `target` | `Object` | no |  | Objeto en el que se escribe. |\n\nReturns: `Object` El destino.\n\nCada clave de `source` se clona en `target`, también las claves que `target` no tiene. Sin `target` devuelve una nueva copia de `source`. Es `U.copy(source, target, true)`.\n\nExample: Combinar\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCrea un hash de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto. |\n| `type` | `String` | no |  | Un algoritmo de hash. |\n\nReturns: `Number|String`\n\nSin `type` devuelve un hash numérico rápido (32 bits sin signo). `type` puede ser `md5`, `sha1`, `sha256`, `sha512`, `crc32` o `crc32unsigned`. Llama a `value.hash()`.\n\nExample: Numérico y MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nAñade un objeto a una URL como query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La URL. |\n| `obj` | `Object` | yes |  | Valores de la query string. |\n\nReturns: `String`\n\nLos valores `null` o `undefined` se omiten; las fechas se convierten en cadenas ISO y los arrays se unen con comas. Las claves y los valores se codifican. La URL puede empezar con un método (`GET /api/`); la query se añade a la ruta. Sin URL devuelve solo `?key=value`.\n\nExample: Construir una URL\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompara dos arrays de objetos por una clave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Nombre de la clave, por ejemplo `id`. |\n| `db` | `Object[]` | yes |  | Los elementos guardados. |\n| `form` | `Object[]` | yes |  | Los elementos nuevos. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nDevuelve `{ add, upd, rem }`: `add` contiene los elementos de `form` que no están en `db`, `upd` contiene pares `{ db, form }` que existen en ambos, y `rem` contiene los valores de clave de los elementos de `db` que faltan en `form`. Úsalo para guardar una lista que ha editado un usuario.\n\nExample: Sincronizar una lista\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio raíz de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Una ruta relativa. |\n\nReturns: `String`\n\nEl resultado siempre usa `/` como separador.\n\nExample: Un archivo en la raíz\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio temporal y crea el directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String`\n\nEl directorio es `CONF.directory_temp`. `PATH.tmp()` y `PATH.temporary()` son alias.\n\nExample: Archivo temporal\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de bases de datos y crea el directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String`\n\nEl directorio es `CONF.directory_databases`.\n\nExample: Un archivo de datos\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de logs y crea el directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String`\n\nEl directorio es `CONF.directory_logs`. `LOGGER()` escribe ahí.\n\nExample: Leer un log\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nCrea un directorio con todos los directorios padre que faltan.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta absoluta. |\n| `cache` | `Boolean` | no | `false` | Omite las rutas creadas antes. |\n\nReturns: `undefined`\n\nFunciona de forma síncrona. Con `cache` en `true`, una ruta que ya se creó no se vuelve a comprobar hasta que el framework vacía su caché.\n\nExample: Directorio para subidas\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nDevuelve un entero aleatorio entre `min` y `max`, ambos incluidos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | El valor más alto. |\n| `min` | `Number` | no | `0` | El valor más bajo. |\n\nReturns: `Number`\n\nExample: Un dado\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nDevuelve una cadena aleatoria de letras y dígitos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Número de caracteres. |\n\nReturns: `String`\n\nLos caracteres son `0-9`, `A-Z` y `a-z`.\n\nExample: Un código\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nDevuelve una cadena aleatoria de letras.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Número de caracteres. |\n\nReturns: `String`\n\nLos caracteres son `A-Z` y `a-z`, sin dígitos.\n\nExample: Solo letras\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nDevuelve una cadena de dígitos aleatorios.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Número de dígitos. |\n\nReturns: `String`\n\nEl primer dígito nunca es `0`, así que `+value` tiene el mismo número de dígitos. El resultado es una cadena.\n\nExample: Un PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nFirma un ID para que el cliente no pueda modificarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | El ID. |\n| `key` | `String` | no | `CONF.secret` | Una clave secreta. |\n\nReturns: `String`\n\nEl resultado contiene el ID y una suma de control del ID y la clave, por ejemplo `n3ck9tg6x123`. El valor no se oculta; se protege contra cambios. Usa `U.decrypt_uid()` para leerlo de nuevo.\n\nExample: Enlace con un ID firmado\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nLee un ID firmado por `U.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El ID firmado. |\n| `key` | `String` | no | `CONF.secret` | La clave secreta usada para firmarlo. |\n\nReturns: `String|Number` El ID, o `null`.\n\nDevuelve el ID original (un número cuando se firmó un número), o `null` cuando la suma de control no coincide.\n\nExample: Verificar un ID de una URL\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nCopia los valores de `source` a las claves que `target` ya tiene.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objeto que se lee. |\n| `target` | `Object` | no |  | Objeto en el que se escribe. |\n\nReturns: `Object` El destino.\n\nSolo se escriben las claves que existen en `target` (con un valor distinto de `undefined`); los valores se clonan. Sin `target` devuelve una nueva copia de `source`. Para copiar todas las claves, usa `COPY()`.\n\nExample: Actualizar los campos conocidos\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nAñade las propiedades de `source` a `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Objeto en el que se escribe. |\n| `source` | `Object` | yes |  | Objeto que se lee. |\n| `rewrite` | `Boolean` | no | `true` | Sobrescribe los valores existentes. |\n\nReturns: `Object` El destino.\n\nLos valores se clonan. Con `rewrite` en `false`, se conservan las claves que ya tienen un valor en `target`, así que `source` actúa como un conjunto de valores predeterminados.\n\nExample: Valores predeterminados\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nConserva solo algunas propiedades de un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | El objeto o el array de objetos. |\n| `props` | `String[]|Object` | yes |  | Claves que se conservan. |\n| `reverse` | `Boolean` | no | `false` | Elimina las claves indicadas en su lugar. |\n\nReturns: `Object|Object[]`\n\n`props` es un array de claves o un objeto cuyas claves se usan. Con `reverse` en `true`, las claves indicadas se eliminan en su lugar. Con un array como `source`, se reduce cada elemento. El resultado es un nuevo objeto.\n\nExample: Campos públicos\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLee un valor por una ruta como `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto. |\n| `path` | `String` | yes |  | La ruta con puntos. |\n\nReturns: `Object` El valor.\n\nDevuelve `undefined` cuando una parte de la ruta no existe. Los índices se escriben como `items[0].name`. Las rutas que contienen caracteres propios de código (espacios, paréntesis de llamadas, `__proto__` y similares) devuelven `undefined`.\n\nExample: Valor anidado\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nEscribe un valor por una ruta como `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto. |\n| `path` | `String` | yes |  | La ruta con puntos. |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `Object` El valor.\n\nSe crean los objetos que faltan en la ruta. Una ruta que termina en `[]` añade el valor a un array. Las rutas que contienen caracteres propios de código se ignoran.\n\nExample: Construir un objeto\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nRecorta todos los valores de cadena de un objeto o un array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | El valor que se recorta. |\n| `clean` | `Boolean` | no | `false` | Reemplaza las cadenas vacías por `undefined`. |\n\nReturns: `Object` El mismo valor.\n\nTambién se recortan los objetos y arrays anidados; el objeto se modifica en el mismo lugar. Con `clean` en `true`, las cadenas vacías se convierten en `undefined`.\n\nExample: Limpiar un formulario\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrae palabras clave de un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | El texto. |\n| `forSearch` | `Boolean` | no | `true` | Normaliza las palabras para la búsqueda. |\n| `alternative` | `Boolean` | no | `false` | Acorta las palabras. |\n| `max_count` | `Number` | no | `200` | Número máximo de palabras leídas. |\n| `max_length` | `Number` | no | `20` | Se omiten las palabras más largas. |\n| `min_length` | `Number` | no | `2` | Se omiten las palabras más cortas. |\n\nReturns: `String[]`\n\nEl texto se pasa a minúsculas y se divide en palabras; el resultado es una lista de palabras únicas, primero las más frecuentes. Con `forSearch` (el valor predeterminado), se eliminan los diacríticos y la `y` se reemplaza por `i`, así las mismas palabras coinciden en una búsqueda. `alternative` acorta cada palabra al 80 % de su longitud para que coincidan las distintas formas de una palabra. `content` puede ser un array de textos.\n\nExample: Índice de búsqueda\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nEjecuta funciones con un límite de cuántas se ejecutan a la vez.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la cola. |\n| `max` | `Number` | yes |  | Número máximo de funciones en ejecución. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | Un valor que se pasa a `fn`. |\n\nReturns: `Boolean`\n\nCada llamada añade `fn(next, param)` a la cola `name`. Como máximo se ejecutan a la vez `max` funciones de esa cola; cada una debe llamar a `next()` cuando termina. Devuelve `true` cuando `fn` empieza de inmediato, y `false` cuando espera.\n\nExample: Tres descargas a la vez\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nCrea una función de comparación para `Array.sort()` a partir de un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La definición de la ordenación. |\n\nReturns: `Function` `function(a, b)`\n\n`sort` es una lista de campos separados por comas, cada uno con un sufijo opcional `_asc` o `_desc`, por ejemplo `price_desc,name`. Se admiten campos anidados como `address.city`. Las cadenas, los números, los booleanos y las fechas se comparan según su tipo.\n\nExample: Ordenar productos\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nUne rutas relativas al directorio raíz de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o varias partes de la ruta. |\n\nReturns: `String` Una ruta absoluta.\n\nUna parte que empieza con `~` es una ruta absoluta y reemplaza lo que había antes. En Windows el resultado usa `/`.\n\nExample: Rutas en la aplicación\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nUne partes de una ruta con `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o varias partes. |\n\nReturns: `String`\n\nSe eliminan las barras al principio y al final de cada parte, y el resultado empieza con `/`. Las partes vacías se omiten.\n\nExample: Unir\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nDevuelve la extensión de un nombre de archivo sin el punto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El nombre de archivo o la URL. |\n| `raw` | `Boolean` | no | `false` | Conserva las mayúsculas y minúsculas originales. |\n\nReturns: `String`\n\nLa extensión se pasa a minúsculas salvo que `raw` sea `true`. Se ignora una query string después de `?`. Devuelve una cadena vacía cuando no hay extensión.\n\nExample: Extensión\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nDevuelve la última parte de una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La ruta. |\n\nReturns: `String`\n\nFunciona con los separadores `/` y `\\`; se ignora un separador final.\n\nExample: Nombre de archivo\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nDevuelve el tipo de contenido (tipo MIME) de una extensión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | La extensión. |\n\nReturns: `String`\n\nLa extensión puede empezar con un punto. Una extensión desconocida da `application/octet-stream`.\n\nExample: Tipo MIME\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nRegistra o cambia el tipo de contenido de una extensión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | La extensión, con o sin punto. |\n| `type` | `String` | yes |  | El tipo de contenido. |\n\nReturns: `Boolean` `true`\n\nEl framework usa la tabla para servir archivos estáticos, así que una nueva extensión también pasa a ser un archivo estático conocido.\n\nExample: Una nueva extensión\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nLista todos los archivos y directorios de un directorio y sus subdirectorios.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | El directorio. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtro. |\n| `unified` | `Boolean` | no | `false` | Usa `/` en Windows. |\n\nReturns: `Promise|undefined` Una Promise cuando no hay callback.\n\n`callback(files, directories)` recibe arrays de rutas absolutas. Sin callback, el método devuelve una Promise de `{ files, directories }`. `filter` es una cadena (parte del nombre, sin distinguir mayúsculas de minúsculas), una RegExp o `function(path, isDirectory)` que devuelve `true` para conservar un elemento; los filtros de cadena y RegExp solo se aplican a los archivos. Con `unified` en `true`, las rutas en Windows usan `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nLista los archivos con sus estadísticas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | El directorio. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtro. |\n| `unified` | `Boolean` | no | `false` | Usa `/` en Windows. |\n\nReturns: `Promise|undefined` Una Promise cuando no hay callback.\n\nFunciona como `U.ls()`, pero cada archivo es `{ filename, stats }`, donde `stats` es el objeto `fs.Stats` (tamaño, fechas). Los directorios siguen siendo rutas.\n\nExample: Tamaño total\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nCodifica los caracteres especiales de HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `String`\n\n`null` y `undefined` dan una cadena vacía; los demás valores se convierten primero en cadena. Llama a `String.encode()`.\n\nExample: HTML seguro\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDecodifica entidades HTML y las convierte de nuevo en caracteres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `String`\n\nLo contrario de `U.encode()`. `null` y `undefined` dan una cadena vacía.\n\nExample: Texto plano\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nCodifica una cadena o un Buffer en Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | El valor. |\n\nReturns: `String`\n\n`U.atob(value)` decodifica Base64 de nuevo a una cadena UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nAnaliza XML y lo convierte en un objeto plano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | El XML. |\n| `replace` | `Boolean` | no | `false` | Reemplaza los caracteres especiales de las claves. |\n\nReturns: `Object`\n\nCada clave es la ruta de un elemento unida con puntos, por ejemplo `root.item`; los elementos repetidos dan un array de valores. Los atributos se guardan bajo la clave con `[]`, por ejemplo `root.item[]`. Con `replace` en `true`, los caracteres `[`, `]`, `:`, `.` y `_` de las claves se convierten en `_`. CDATA se lee como texto.\n\nExample: Leer XML\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConvierte cualquier valor en un entero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n| `def` | `Number` | no | `0` | Valor para una entrada vacía o no válida. |\n\nReturns: `Number`\n\n`null`, `undefined` y una cadena vacía dan `def`. Un número se devuelve tal cual. `U.parseFloat(value, [def])` y `U.parseBoolean(value, [def])` funcionan igual para decimales y booleanos (`def` es `false` para los booleanos; un número es `true` cuando es mayor que 0).\n\nExample: Valores de la query string\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nDevuelve la distancia entre dos coordenadas GPS en kilómetros.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Latitud del primer punto. |\n| `lon1` | `Number` | yes |  | Longitud del primer punto. |\n| `lat2` | `Number` | yes |  | Latitud del segundo punto. |\n| `lon2` | `Number` | yes |  | Longitud del segundo punto. |\n\nReturns: `Number` Kilómetros.\n\nUsa la fórmula del haversine sobre una esfera con un radio de 6371 km; el resultado tiene como máximo 3 decimales.\n\nExample: De Bratislava a Praga\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifica CSS con el compilador integrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Código CSS. |\n\nReturns: `String`\n\nEl mismo compilador que usa el framework para los archivos `.css` estáticos.\n\nExample: Minificar\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifica JavaScript con el compilador integrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Código JavaScript. |\n\nReturns: `String`\n\nElimina los comentarios y los espacios en blanco. El mismo compilador que usa el framework para los archivos `.js` estáticos.\n\nExample: Minificar\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifica HTML con el compilador integrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Código HTML. |\n\nReturns: `String`\n\nElimina los espacios en blanco entre etiquetas.\n\nExample: Minificar\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nGuarda un estado con nombre de tu aplicación y lo pasa a `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | El nombre del estado, o un objeto `$`. |\n| `data` | `Object` | yes |  | Cualquier valor. |\n| `timeout` | `Number` | no |  | Retrasa la actualización y combina las llamadas durante este tiempo, en milisegundos. |\n\nReturns: `undefined` Nada.\n\nCada `id` tiene un objeto de estado `{ id, data, date }`. `STATUS()` reemplaza su `data`, define `date` y llama a `DEF.onStatus(meta)` cuando lo defines. En lugar de un `id` puedes pasar un objeto `$`; su `ID` (o `name`) es el id.\n\nCon `timeout` (en milisegundos), la actualización se retrasa: la primera llamada inicia el temporizador, las llamadas posteriores solo cambian `data`, y `DEF.onStatus()` se ejecuta una vez con los últimos datos cuando termina el temporizador. Úsalo para valores que cambian a menudo, como un progreso.\n\nCon `CONF.allow_stats_status` (por defecto `true`), todos los estados se añaden como `status` a la instantánea de estadísticas que Total.js escribe en `<main script>.json` (`CONF.allow_stats_snapshot`).\n\nExample: Progreso de una importación\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nCifra una cadena con una clave y una máscara aleatoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | El texto que se cifra. |\n| `key` | `String` | yes |  | La clave. |\n| `encode` | `String` | no | `base64` | Una codificación de Buffer o `buffer`. |\n\nReturns: `String|Buffer` El valor cifrado.\n\nLa salida cambia en cada llamada debido a una máscara aleatoria de 4 bytes. `encode` es una codificación de Buffer (por defecto `base64`); `buffer` devuelve el Buffer sin procesar. Léelo de nuevo con `U.decrypt_data()` y la misma clave. Es una ofuscación ligera, no un sustituto de `U.encrypt_crypto()`.\n\nExample: Cifrar una cadena JSON\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nDescifra un valor creado por `U.encrypt_data()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | El valor cifrado. |\n| `key` | `String` | yes |  | La clave usada para el cifrado. |\n| `encode` | `String` | no | `base64` | La codificación de `value`. |\n\nReturns: `String` El texto descifrado o `null`.\n\n`value` es una cadena en la codificación `encode` (por defecto `base64`) o un Buffer. Devuelve `null` cuando el valor no se puede leer. Una clave incorrecta da una cadena incorrecta, no `null`, así que comprueba el resultado (por ejemplo con `parseJSON()`).\n\nExample: Descifrar un token\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nCifra datos con un cifrador de Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Un nombre de cifrador, por ejemplo `aes-256-cbc`. |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `String|Buffer` | yes |  | Los datos. |\n\nReturns: `Buffer` Los datos cifrados.\n\nUsa `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. La longitud de la clave debe corresponder al cifrador (32 caracteres para `aes-256-cbc`). `CONF.default_crypto_iv` se crea a partir de la aplicación por defecto, así que defínelo en la configuración cuando otras aplicaciones deban descifrar los datos.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nDescifra datos creados por `U.encrypt_crypto()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El nombre del cifrador. |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `Buffer` | yes |  | Los datos cifrados. |\n\nReturns: `Buffer` Los datos descifrados o `undefined`.\n\nUsa `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Devuelve `undefined` cuando los datos no se pueden descifrar.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nConvierte un número en una cadena en base 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Un número positivo. |\n\nReturns: `String`\n\nEl alfabeto son los dígitos, después las letras mayúsculas y las minúsculas. Los decimales se redondean hacia abajo. Léelo de nuevo con `U.from62()`.\n\nExample: Código corto\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nConvierte de nuevo en número una cadena en base 62 de `U.convert62()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una cadena en base 62. |\n\nReturns: `Number`\n\nExample: De vuelta a número\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nDevuelve un grupo numérico de longitud fija para un identificador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Un identificador. |\n| `count` | `Number` | no | `4` | El número de dígitos. |\n\nReturns: `String` Una cadena de dígitos.\n\nEl valor es `HASH(id, true)` módulo `10^count`, rellenado con ceros hasta `count` dígitos. El mismo id siempre da el mismo grupo, así que es útil para repartir archivos en subdirectorios.\n\nExample: Subdirectorios\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nConvierte cualquier valor en un booleano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valor. |\n| `def` | `Boolean` | no | `false` | El valor predeterminado. |\n\nReturns: `Boolean`\n\nUn booleano se devuelve tal cual, un número es `true` cuando es mayor que `0`, y los demás valores se convierten en cadena y se analizan con `String.parseBoolean()`. `null` y `undefined` devuelven `def`.\n\nExample: Valor de la query string\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nConvierte cualquier valor en un número decimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valor. |\n| `def` | `Number` | no | `0` | El valor predeterminado. |\n\nReturns: `Number`\n\nUn número se devuelve tal cual, y los demás valores se convierten en cadena y se analizan con `String.parseFloat()`. `null`, `undefined` y una cadena vacía devuelven `def`.\n\nExample: Precio\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nComprueba que un valor es un `Date` válido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valor. |\n\nReturns: `Boolean`\n\nDevuelve `false` para una fecha no válida como `new Date('abc')`.\n\nExample: Validar una fecha\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nNombres en inglés de los días de la semana.\n\nReturns: `String Array`\n\nEl array empieza con `Sunday`, así que coincide con `Date.getDay()`.\n\nExample: Nombre del día\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nNombres en inglés de los meses.\n\nReturns: `String Array`\n\nEl array empieza con `January`, así que coincide con `Date.getMonth()`.\n\nExample: Nombre del mes\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nDevuelve el texto de un código de estado HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Un código de estado HTTP. |\n| `addCode` | `Boolean` | no | `true` | Añade el código al texto. |\n\nReturns: `String`\n\nEl texto viene de `http.STATUS_CODES`. Con `addCode` (por defecto `true`) se añade el código delante.\n\nExample: Texto del estado\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSerializa un objeto en una query string codificada para URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un objeto. |\n\nReturns: `String` Por ejemplo `q=total&page=2`.\n\nLas cadenas se codifican con `encodeURIComponent()`, los números y los booleanos se añaden tal cual, y los arrays se unen con `,`. Se omiten `null`, `undefined`, las cadenas vacías y otros objetos (incluidas las fechas). Devuelve una cadena vacía cuando no se añade nada.\n\nExample: Query string\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDecodifica una cadena base64 a una cadena UTF-8.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una cadena base64. |\n\nReturns: `String`\n\nLo contrario de `U.btoa()`.\n\nExample: Decodificar\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nComprueba que una URL es relativa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una URL. |\n\nReturns: `Boolean`\n\nDevuelve `false` cuando la URL empieza con `//` o contiene `http://` o `https://`.\n\nExample: Redirección segura\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nComprueba que una URL parece un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una ruta de URL. |\n\nReturns: `Boolean`\n\nDevuelve `true` cuando los últimos 8 caracteres de la URL contienen un punto, por ejemplo `/img/logo.png`.\n\nExample: Archivo o ruta\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nResuelve la dirección IPv4 de una URL y la guarda en caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Una URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | Un valor que se pasa al callback. |\n\nReturns: `Array|undefined` Las direcciones en caché cuando no se da ningún callback.\n\n`callback(err, uri, param, addresses)` recibe la URL analizada con `uri.host` reemplazado por la primera dirección. Las direcciones se guardan en caché por host; sin callback, el método devuelve las direcciones en caché (o `undefined`). Una búsqueda fallida se intenta una vez más. El comando `clear_dnscache` vacía la caché.\n\nExample: Búsqueda DNS\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nUne partes de una URL con exactamente una `/` entre ellas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o varias partes de la URL. |\n\nReturns: `String`\n\nA diferencia de `U.join()`, no añade una `/` inicial y conserva las partes tal cual.\n\nExample: Construir una URL\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nAñade `/` al principio y al final de una ruta cuando falta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta. |\n\nReturns: `String`\n\nExample: Normalizar\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nAñade un delimitador final a una ruta cuando falta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta. |\n| `delimiter` | `String` | no | `/` | El delimitador. |\n\nReturns: `String`\n\nUna ruta vacía devuelve el delimitador.\n\nExample: Ruta de directorio\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nDevuelve la extensión de archivo de un tipo de contenido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | Un tipo de contenido. |\n\nReturns: `String`\n\nBusca en los tipos de contenido que conoce `U.getContentType()` (incluidos los añadidos con `U.setContentType()`). Devuelve la primera coincidencia sin punto, o `undefined`.\n\nExample: Extensión\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nConvierte un objeto en un array de elementos `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un objeto. |\n\nReturns: `Array`\n\n`null` o `undefined` devuelven `EMPTYARRAY`.\n\nExample: Lista de clave-valor\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nAtajo para `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | Los datos. |\n| `encoding` | `String` | no | `utf8` | La codificación de una cadena. |\n\nReturns: `Buffer`\n\nExample: Desde base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nAtajo para `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | El tamaño en bytes. |\n\nReturns: `Buffer` Un buffer lleno de ceros.\n\nExample: Buffer vacío\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nUn replacer de `JSON.stringify()` que elimina los valores `null` y `undefined`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave. |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `Object`\n\nExample: JSON más pequeño\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nEl estado de las colas creadas por `U.queue()`.\n\nReturns: `Object`\n\nUn objeto con el nombre de la cola como clave. Cada elemento tiene `limit`, `running` y `pending` (los callbacks en espera). Léelo solo para monitorización.\n\nExample: Elementos en espera\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nUn pequeño emisor de eventos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Un objeto que se extiende. |\n\nReturns: `EventEmitter2`\n\n`new U.EventEmitter2()` crea un emisor. `U.EventEmitter2(obj)` (sin `new`) añade `emit()`, `on()`, `once()`, `off()`, `removeListener()` y `removeAllListeners()` a un objeto existente y lo devuelve; `U.EventEmitter2.extend(obj)` hace lo mismo. Los listeners se guardan en `$events`. `emit()` pasa hasta 7 argumentos y `this` es el emisor.\n\nExample: Extender un objeto\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nElimina un listener o todos los listeners de un evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento. |\n| `fn` | `Function` | no |  | El listener. |\n\nReturns: `EventEmitter2` El emisor.\n\nSin `fn` se eliminan todos los listeners de `name`. `removeListener()` es un alias. `removeAllListeners([name])` elimina los listeners de un evento o de todos los eventos.\n\nExample: Eliminar un listener\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nLlama a un callback después de que se haya llamado a `next()` `count` veces.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Cuántas llamadas a `next()` hay que esperar. |\n| `callback` | `Function` | no |  | La función que se llama. |\n\nReturns: `Callback` Una instancia con `next()` y `done(fn)`.\n\nDevuelve una instancia con `next()` y `done(callback)`. El callback se ejecuta una vez, cuando el contador pendiente llega a cero. La clase también está disponible como el global `Callback`.\n\nExample: Esperar a 3 tareas\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nGuarda muchos elementos en archivos temporales, página a página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nombre único, que se usa en los nombres de archivo. |\n| `max` | `Number` | no | `50` | El número de elementos por archivo. |\n\nReturns: `Chunker`\n\nCada `max` elementos escritos con `write()` van a un archivo `{name}-{index}.chunker` en el directorio temporal, comprimido con deflate. Léelos de nuevo página a página con `each()` o `read()`. Propiedades: `compress` (por defecto `true`), `autoremove` (por defecto `true`, elimina cada archivo después de leerlo), `count`, `pages` y `percentage` (progreso de `each()`). La clase está disponible como `U.Chunker`.\n\nExample: Exportar por páginas\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nAñade un elemento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Un elemento que se puede serializar a JSON. |\n\nReturns: `Chunker`\n\nCuando hay `max` elementos en espera, se escriben en un nuevo archivo. `append()` es un alias. Llama a `end()` después del último elemento.\n\nExample: Escribir\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nEscribe los elementos restantes en el último archivo.\n\nReturns: `Chunker`\n\nExample: Terminar la escritura\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nLee todas las páginas una a una.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | Se ejecuta después de la última página. |\n\nReturns: `Chunker`\n\n`onItem(items, next, index)` recibe los elementos de una página; llama a `next()` para leer la página siguiente. `onEnd()` se ejecuta después de la última página. `percentage` muestra el progreso.\n\nExample: Procesar páginas\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nLee una página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | El índice de página desde `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`callback(err, items)` recibe los elementos de la página, o un array vacío cuando el archivo no existe. Espera mientras todavía se están escribiendo archivos.\n\nExample: Primera página\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nElimina todos los archivos del chunker.\n\nReturns: `Chunker`\n\n`destroy()` también elimina los archivos y libera la instancia.\n\nExample: Limpiar\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nConsulta un array de objetos con el query builder de NoSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | Los elementos o una URL. |\n\nReturns: `Reader`\n\n`items` es un array (o un objeto), o una URL de contenido TextDB que se descarga y se procesa como stream. Sin `items`, añade datos con `reader.push(items)` y termina con `reader.push(null)`, o usa `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` y `stats(groupfield, datefield, key, [type])` devuelven un query builder de NoSQL (`where()`, `sort()`, `take()`, `callback()`...). `list()` devuelve `{ page, pages, limit, count, items }`. `assign(data)` crea una consulta a partir de un objeto de consulta serializado.\n\nExample: Filtrar un array\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nAñade elementos al lector.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | Los datos, o `null` al final. |\n\nReturns: `undefined`\n\nPasa un array o un objeto por cada bloque de datos, y después `null` para terminar y obtener los resultados.\n\nExample: Añadir datos\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDivide un stream de bloques en partes según delimitadores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | El delimitador o el inicio de una parte. |\n| `end` | `String|Buffer` | no |  | El final de una parte. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | El número de partes que se omiten. |\n| `stream` | `Stream` | no |  | Un stream para el evento `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nDevuelve `function(chunk)`, a la que pasas cada bloque. Sin `end`, cada parte termina con `beg` (y lo incluye), por ejemplo una línea que termina en `\\n`. Con `end`, cada parte empieza con `beg` y termina con `end`. `callback(value, index)` recibe cada parte como cadena; devuelve `false` para detener. `skip` omite las primeras partes. Con `stream`, los datos restantes se procesan en el evento `end` del stream. `U.streamer2()` es igual pero da Buffers.\n\nExample: Leer líneas\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nIgual que `U.streamer()`, pero las partes son Buffers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | El delimitador o el inicio de una parte. |\n| `end` | `String|Buffer` | no |  | El final de una parte. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | El número de partes que se omiten. |\n| `stream` | `Stream` | no |  | Un stream para el evento `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Partes binarias\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nLee un archivo de texto línea a línea por lotes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo. |\n\nReturns: `Object` Un lector de stream.\n\nDevuelve un lector de stream de TextDB. Define `ondocuments` (se llama con `this.docs`, las líneas de un lote unidas con `,`; devuelve `false` para detener) y `$callback` (se llama al final), y después llama a `openread()`. Define `array = true` para obtener `docs` como un array de líneas. Se omiten las líneas que empiezan con `-`.\n\nExample: Leer un archivo JSON-lines\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias de `path.join()` de Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o varias partes de la ruta. |\n\nReturns: `String`\n\nExample: Unir\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nComprueba que existe un archivo o un directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una ruta. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Comprobar un archivo\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nCrea un directorio de la aplicación si no existe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del directorio. |\n\nReturns: `undefined`\n\n`name` es el nombre de un ajuste `CONF.directory_{name}`, por ejemplo `databases`. La comprobación se ejecuta una vez por nombre.\n\nExample: Asegurarse de que el directorio existe\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias de `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | El directorio. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` es un alias de `U.ls2()`.\n\nExample: Listar archivos\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nElimina archivos uno a uno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | Los archivos. |\n| `callback` | `Function` | no |  | Se ejecuta al final. |\n\nReturns: `undefined`\n\nLos errores se ignoran.\n\nExample: Eliminar archivos\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nElimina directorios con todo su contenido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | Los directorios. |\n| `callback` | `Function` | no |  | Se ejecuta al final. |\n\nReturns: `undefined`\n\nLos errores se ignoran.\n\nExample: Eliminar un directorio\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de privado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_private` (por defecto `/private/`).\n\nExample: Ruta\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de modelos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_models` (por defecto `/models/`).\n\nExample: Ruta\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de builds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_builds` (por defecto `/builds/`).\n\nExample: Ruta\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de vistas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_views` (por defecto `/views/`).\n\nExample: Ruta\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de actualizaciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_updates` (por defecto `/updates/`).\n\nExample: Ruta\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de módulos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_modules` (por defecto `/modules/`).\n\nExample: Ruta\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de esquemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_schemas` (por defecto `/schemas/`).\n\nExample: Ruta\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de extensiones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_extensions` (por defecto `/extensions/`).\n\nExample: Ruta\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de operaciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_operations` (por defecto `/operations/`).\n\nExample: Ruta\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de tareas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_tasks` (por defecto `/tasks/`).\n\nExample: Ruta\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de controladores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_controllers` (por defecto `/controllers/`).\n\nExample: Ruta\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de definiciones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_definitions` (por defecto `/definitions/`).\n\nExample: Ruta\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de pruebas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_tests` (por defecto `/tests/`).\n\nExample: Ruta\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de servicios.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_services` (por defecto `/services/`).\n\nExample: Ruta\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de paquetes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_packages` (por defecto `/packages/`).\n\nExample: Ruta\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de temas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_themes` (por defecto `/themes/`).\n\nExample: Ruta\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de componentes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_components` (por defecto `/components/`).\n\nExample: Ruta\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de plantillas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_templates` (por defecto `/templates/`).\n\nExample: Ruta\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nDevuelve una ruta en el directorio de plugins.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_plugins` (por defecto `/plugins/`).\n\nExample: Ruta\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nDevuelve una ruta en el directorio de flowstreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo. |\n\nReturns: `String` Una ruta absoluta.\n\nEl directorio es `CONF.directory_flowstreams` (por defecto `/flowstreams/`).\n\nExample: Ruta\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nImprime un aviso sobre código obsoleto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Qué está obsoleto. |\n| `message` | `String` | yes |  | Qué usar en su lugar. |\n\nEscribe en la consola la fecha, el nombre y el mensaje, e incrementa `F.stats.other.obsolete`. No se imprime nada cuando `CONF.nowarnings` es `true` (el framework lo define cuando el watcher reinicia la aplicación con `--restart`).\n\nExample: Avisar\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nGenera un identificador único con una parte de tiempo decimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | El nombre de un contador separado. |\n| `date` | `Date` | no | `NOW` | El momento del identificador. |\n\nReturns: `String` El identificador.\n\nComo `UID()`, pero la parte de tiempo es el número de minutos desde 2020-01-31 23:00 UTC escrito con dígitos decimales. Los identificadores terminan con la letra de versión `b`. Con `type`, cada tipo tiene su propio contador. `date` genera el identificador para otro momento.\n\nExample: Identificador\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Utilitaires","summary":"Les fonctions de U (utils.js) ainsi que les utilitaires et objets globaux du framework.","markdown":"---\ntitle: Utilitaires\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilitaires\n\n> Les fonctions de U (utils.js) ainsi que les utilitaires et objets globaux du framework.\n\nTotal.js définit des utilitaires dans la portée globale et dans l'objet `U` (`Utils`), afin que chaque fichier d'une application puisse les utiliser sans `require()`. Le guide [Utilitaires](../../guides/utilities/) explique comment les utiliser, avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### U\n\nType: `property`\n\nLa bibliothèque d'utilitaires du framework (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` et `utils` sont le même objet. Il est global, tu l'utilises donc dans les contrôleurs, les schémas, les modules et les plugins sans `require()`.\n\nExample: Utiliser un utilitaire\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nUn alias global de l'instance du framework `F`.\n\nReturns: `Framework`\n\n`Total`, `F` et `framework` désignent le même objet.\n\nExample: Même objet\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\nUne `Date` que le framework actualise régulièrement.\n\nReturns: `Date`\n\nLire `NOW` coûte moins cher que `new Date()`. Le framework la redéfinit dans ses intervalles internes (environ chaque minute) et lors de certains appels, comme `LOGGER()`. Utilise-la lorsqu'une précision à la minute suffit ; utilise `new Date()` pour une heure exacte. `F.datetime` lit et écrit la même valeur.\n\nExample: Horodatage d'un enregistrement\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn objet vide gelé.\n\nReturns: `Object`\n\nUtilise-le comme valeur par défaut qui n'est jamais modifiée. Il est gelé, les affectations n'ont donc aucun effet.\n\nExample: Options par défaut\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nUn tableau vide gelé.\n\nReturns: `Array`\n\nUtilise-le comme valeur par défaut qui n'est jamais modifiée. Il est gelé, `push()` lève donc une erreur.\n\nExample: Liste par défaut\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nUne fonction vide.\n\nReturns: `undefined`\n\nPasse-la là où un callback est requis et où tu n'as pas besoin du résultat.\n\nExample: Ignorer un callback\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nUn objet global vide pour tes propres données partagées.\n\nReturns: `Object`\n\nLe framework crée `MAIN = {}` et ne l'utilise pas. Stockes-y les valeurs propres à toute l'application, par exemple des données chargées au démarrage.\n\nExample: Paramètres partagés\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nUn objet global vide pour ton propre dépôt de valeurs.\n\nReturns: `Object`\n\nLe framework crée `REPO = {}` et ne l'utilise pas. C'est un second espace de noms comme `MAIN`.\n\nExample: Mettre une liste en cache\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nUn objet global vide pour tes propres fonctions partagées.\n\nReturns: `Object`\n\nLe framework crée `FUNC = {}`. Places-y les utilitaires que plusieurs fichiers de l'application appellent.\n\nExample: Fonction partagée\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn objet global pour des données temporaires que le framework vide.\n\nReturns: `Object`\n\nLe framework remplace `TEMP` par un nouvel objet vide lors de son nettoyage périodique (toutes les `CONF.default_interval_clear_cache` minutes, 10 par défaut). N'y conserve rien dont tu auras besoin plus tard.\n\nExample: Valeur de courte durée\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nTous les modules chargés, par nom.\n\nReturns: `Object`\n\nLe même objet que `F.modules`. Une clé est le nom du fichier dans `/modules/` (ou l'`id` que le module exporte).\n\nExample: Lister les modules\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nRenvoie un module chargé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du module. |\n\nReturns: `Object` Le module, ou `null`.\n\nLit `F.modules[name]`. Le résultat est l'objet `exports` du fichier du module, ou `null` quand aucun module de ce nom n'est chargé.\n\nExample: Appeler un module\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nAjoute une ligne à un fichier journal du répertoire `/logs/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du fichier journal sans `.log`. |\n| `value` | `Object` | yes |  | Une ou plusieurs valeurs à écrire. |\n\nReturns: `undefined`\n\nLa ligne est `yyyy-MM-dd HH:mm:ss | values` dans le fichier `{name}.log`. Les valeurs sont séparées par une espace ; les objets sont formatés avec `util.inspect()`. Le répertoire est créé s'il n'existe pas, et les écritures passent par `U.queue()` avec au plus 5 écritures simultanées.\n\nExample: Journaliser un paiement\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nAppelle une fonction de style callback et renvoie une Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Une fonction qui prend un callback en dernier argument. |\n| `a` | `Object` | no |  | Premier argument. |\n| `b` | `Object` | no |  | Deuxième argument. |\n| `c` | `Object` | no |  | Troisième argument. |\n\nReturns: `Promise`\n\n`fn` est appelée avec les arguments donnés et un callback `function(err, response)` en dernier argument. La Promise est rejetée avec `err` ou résolue avec `response`. Jusqu'à trois arguments sont pris en charge ; les arguments `undefined` ne sont pas transmis.\n\nExample: Lire un fichier\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Ta propre fonction\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nAttend qu'une condition soit vraie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Renvoie `true` quand l'attente est terminée. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Durée maximale en ms. |\n| `interval` | `Number` | no | `500` | Délai entre les vérifications en ms. |\n\nReturns: `undefined`\n\n`validator()` est vérifié immédiatement, puis toutes les `interval` ms. Quand il renvoie `true`, `callback(null, true)` est appelé. Si `timeout` ms s'écoulent avant, `callback(Error('Timeout'), false)` est appelé.\n\nExample: Attendre une connexion\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nCrée un identifiant unique court.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Le nom d'un compteur indépendant. |\n| `date` | `Date` | no | `NOW` | Le moment encodé dans l'identifiant. |\n\nReturns: `String`\n\nL'identifiant est une chaîne basée sur le temps, par exemple `24j0y001xn51d`, qui se trie selon son moment de création. Il est unique au sein de l'instance en cours d'exécution (le framework ajoute une clé d'instance aléatoire). `type` conserve un compteur distinct pour chaque type, afin que les identifiants de collections différentes ne partagent pas une même séquence. `date` crée l'identifiant pour un autre moment. `CONF.default_uid` choisit la version : `r` donne un identifiant aléatoire (`UIDR()`), `f` une variante en base 62 ; la version par défaut est `d`.\n\nExample: Un nouvel enregistrement\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Compteur par type\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nCrée un identifiant unique dont la partie temporelle est en base 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Le nom d'un compteur indépendant. |\n| `date` | `Date` | no | `NOW` | Le moment encodé dans l'identifiant. |\n\nReturns: `String`\n\nFonctionne comme `UID()` mais encode le temps en hexadécimal, l'identifiant est donc un peu plus long (version `c`). Il ignore `CONF.default_uid`.\n\nExample: Identifiant hexadécimal\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nCrée un GUID ou une chaîne aléatoire d'une longueur donnée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Longueur d'une chaîne aléatoire. |\n\nReturns: `String`\n\nSans `length`, elle renvoie une chaîne au format UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` construite à partir de l'heure actuelle et de nombres aléatoires. Avec `length`, elle renvoie des lettres minuscules et des chiffres aléatoires de cette longueur. Également disponible sous `U.GUID()`.\n\nExample: Format UUID\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Jeton aléatoire\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nCrée une copie profonde d'un objet ou d'un tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet ou le tableau à copier. |\n| `skip` | `Object` | no |  | Les clés à exclure, sous la forme `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Exclut les fonctions. |\n\nReturns: `Object` Un nouvel objet.\n\nLes objets et tableaux imbriqués sont copiés ; les valeurs `Date` et `Error` sont conservées par référence, et les Buffers sont copiés. `skip` est un objet des clés à exclure (`{ password: 1 }`) au premier niveau des objets. Également disponible sous `U.clone()`.\n\nExample: Copier sans une clé\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nCopie toutes les propriétés de `source` vers `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objet à lire. |\n| `target` | `Object` | no |  | Objet à écrire. |\n\nReturns: `Object` La cible.\n\nChaque clé de `source` est clonée dans `target`, y compris les clés que `target` ne possède pas. Sans `target`, elle renvoie une nouvelle copie de `source`. Elle équivaut à `U.copy(source, target, true)`.\n\nExample: Fusionner\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCrée un hachage d'une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte. |\n| `type` | `String` | no |  | Un algorithme de hachage. |\n\nReturns: `Number|String`\n\nSans `type`, elle renvoie un hachage numérique rapide (32 bits non signé). `type` peut être `md5`, `sha1`, `sha256`, `sha512`, `crc32` ou `crc32unsigned`. Elle appelle `value.hash()`.\n\nExample: Numérique et MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nAjoute un objet à une URL sous forme de query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'URL. |\n| `obj` | `Object` | yes |  | Les valeurs de la query string. |\n\nReturns: `String`\n\nLes valeurs `null` ou `undefined` sont exclues ; les dates deviennent des chaînes ISO et les tableaux sont joints par des virgules. Les clés et les valeurs sont encodées. L'URL peut commencer par une méthode (`GET /api/`) ; la query est ajoutée au chemin. Sans URL, elle renvoie uniquement `?key=value`.\n\nExample: Construire une URL\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nCompare deux tableaux d'objets selon une clé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Nom de la clé, par exemple `id`. |\n| `db` | `Object[]` | yes |  | Les éléments stockés. |\n| `form` | `Object[]` | yes |  | Les nouveaux éléments. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nRenvoie `{ add, upd, rem }` : `add` contient les éléments de `form` absents de `db`, `upd` contient les paires `{ db, form }` présentes dans les deux, et `rem` contient les valeurs de clé des éléments de `db` absents de `form`. Utilise-la pour enregistrer une liste qu'un utilisateur a modifiée.\n\nExample: Synchroniser une liste\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire racine de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un chemin relatif. |\n\nReturns: `String`\n\nLe résultat utilise toujours `/` comme séparateur.\n\nExample: Un fichier à la racine\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire temporaire et crée le répertoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String`\n\nLe répertoire est `CONF.directory_temp`. `PATH.tmp()` et `PATH.temporary()` sont des alias.\n\nExample: Fichier temporaire\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des bases de données et crée le répertoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String`\n\nLe répertoire est `CONF.directory_databases`.\n\nExample: Un fichier de données\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des journaux et crée le répertoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String`\n\nLe répertoire est `CONF.directory_logs`. `LOGGER()` y écrit.\n\nExample: Lire un journal\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nCrée un répertoire avec tous les répertoires parents manquants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin absolu. |\n| `cache` | `Boolean` | no | `false` | Ignore les chemins créés auparavant. |\n\nReturns: `undefined`\n\nElle fonctionne de façon synchrone. Avec `cache` à `true`, un chemin déjà créé n'est pas revérifié tant que le framework n'a pas vidé son cache.\n\nExample: Répertoire pour les fichiers envoyés\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nRenvoie un entier aléatoire compris entre `min` et `max`, bornes incluses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | La valeur la plus haute. |\n| `min` | `Number` | no | `0` | La valeur la plus basse. |\n\nReturns: `Number`\n\nExample: Un dé\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nRenvoie une chaîne aléatoire de lettres et de chiffres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Nombre de caractères. |\n\nReturns: `String`\n\nLes caractères sont `0-9`, `A-Z` et `a-z`.\n\nExample: Un code\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nRenvoie une chaîne aléatoire de lettres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Nombre de caractères. |\n\nReturns: `String`\n\nLes caractères sont `A-Z` et `a-z`, sans chiffres.\n\nExample: Lettres uniquement\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nRenvoie une chaîne de chiffres aléatoires.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Nombre de chiffres. |\n\nReturns: `String`\n\nLe premier chiffre n'est jamais `0`, ainsi `+value` a le même nombre de chiffres. Le résultat est une chaîne.\n\nExample: Un code PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nSigne un identifiant afin que le client ne puisse pas le modifier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | L'identifiant. |\n| `key` | `String` | no | `CONF.secret` | Une clé secrète. |\n\nReturns: `String`\n\nLe résultat contient l'identifiant et une somme de contrôle de l'identifiant et de la clé, par exemple `n3ck9tg6x123`. La valeur n'est pas cachée ; elle est protégée contre les modifications. Utilise `U.decrypt_uid()` pour la relire.\n\nExample: Lien avec un identifiant signé\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nLit un identifiant signé par `U.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | L'identifiant signé. |\n| `key` | `String` | no | `CONF.secret` | La clé secrète utilisée pour le signer. |\n\nReturns: `String|Number` L'identifiant, ou `null`.\n\nRenvoie l'identifiant d'origine (un nombre si un nombre a été signé), ou `null` quand la somme de contrôle ne correspond pas.\n\nExample: Vérifier un identifiant issu d'une URL\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nCopie les valeurs de `source` vers les clés que `target` possède déjà.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objet à lire. |\n| `target` | `Object` | no |  | Objet à écrire. |\n\nReturns: `Object` La cible.\n\nSeules les clés qui existent dans `target` (avec une valeur autre que `undefined`) sont écrites ; les valeurs sont clonées. Sans `target`, elle renvoie une nouvelle copie de `source`. Pour copier toutes les clés, utilise `COPY()`.\n\nExample: Mettre à jour les champs connus\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nAjoute les propriétés de `source` à `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Objet à écrire. |\n| `source` | `Object` | yes |  | Objet à lire. |\n| `rewrite` | `Boolean` | no | `true` | Écrase les valeurs existantes. |\n\nReturns: `Object` La cible.\n\nLes valeurs sont clonées. Avec `rewrite` à `false`, les clés qui ont déjà une valeur dans `target` sont conservées, `source` sert donc d'ensemble de valeurs par défaut.\n\nExample: Valeurs par défaut\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nNe conserve que certaines propriétés d'un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | L'objet ou le tableau d'objets. |\n| `props` | `String[]|Object` | yes |  | Les clés à conserver. |\n| `reverse` | `Boolean` | no | `false` | Supprime plutôt les clés listées. |\n\nReturns: `Object|Object[]`\n\n`props` est un tableau de clés ou un objet dont les clés sont utilisées. Avec `reverse` à `true`, les clés listées sont au contraire supprimées. Un tableau passé comme `source` réduit chaque élément. Le résultat est un nouvel objet.\n\nExample: Champs publics\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLit une valeur par un chemin comme `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet. |\n| `path` | `String` | yes |  | Le chemin avec des points. |\n\nReturns: `Object` La valeur.\n\nRenvoie `undefined` quand une partie du chemin n'existe pas. Les indices s'écrivent `items[0].name`. Les chemins qui contiennent des caractères ressemblant à du code (espaces, parenthèses d'appel, `__proto__` et similaires) renvoient `undefined`.\n\nExample: Valeur imbriquée\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nÉcrit une valeur par un chemin comme `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet. |\n| `path` | `String` | yes |  | Le chemin avec des points. |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `Object` La valeur.\n\nLes objets manquants sur le chemin sont créés. Un chemin qui se termine par `[]` ajoute la valeur à un tableau. Les chemins qui contiennent des caractères ressemblant à du code sont ignorés.\n\nExample: Construire un objet\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nSupprime les espaces superflus de toutes les valeurs texte d'un objet ou d'un tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | La valeur à nettoyer. |\n| `clean` | `Boolean` | no | `false` | Remplace les chaînes vides par `undefined`. |\n\nReturns: `Object` La même valeur.\n\nLes objets et tableaux imbriqués sont également traités ; l'objet est modifié sur place. Avec `clean` à `true`, les chaînes vides deviennent `undefined`.\n\nExample: Nettoyer un formulaire\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrait les mots-clés d'un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | Le texte. |\n| `forSearch` | `Boolean` | no | `true` | Normalise les mots pour la recherche. |\n| `alternative` | `Boolean` | no | `false` | Raccourcit les mots. |\n| `max_count` | `Number` | no | `200` | Nombre maximal de mots lus. |\n| `max_length` | `Number` | no | `20` | Les mots plus longs sont ignorés. |\n| `min_length` | `Number` | no | `2` | Les mots plus courts sont ignorés. |\n\nReturns: `String[]`\n\nLe texte est mis en minuscules et découpé en mots ; le résultat est une liste de mots uniques, les plus fréquents en premier. Avec `forSearch` (par défaut), les signes diacritiques sont supprimés et `y` est remplacé par `i`, afin que les mêmes mots correspondent lors d'une recherche. `alternative` raccourcit chaque mot à 80 % de sa longueur pour faire correspondre les formes des mots. `content` peut être un tableau de textes.\n\nExample: Index de recherche\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nExécute des fonctions en limitant le nombre d'exécutions simultanées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de la file d'attente. |\n| `max` | `Number` | yes |  | Nombre maximal de fonctions en cours d'exécution. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | Une valeur transmise à `fn`. |\n\nReturns: `Boolean`\n\nChaque appel ajoute `fn(next, param)` à la file d'attente `name`. Au plus `max` fonctions de cette file s'exécutent en même temps ; chacune doit appeler `next()` quand elle se termine. Renvoie `true` quand `fn` démarre immédiatement, `false` quand elle attend.\n\nExample: Trois téléchargements à la fois\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nCrée une fonction de comparaison pour `Array.sort()` à partir d'un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La définition du tri. |\n\nReturns: `Function` `function(a, b)`\n\n`sort` est une liste de champs séparés par des virgules, chacun avec un suffixe facultatif `_asc` ou `_desc`, par exemple `price_desc,name`. Les champs imbriqués comme `address.city` sont pris en charge. Les chaînes, nombres, booléens et dates sont comparés selon leur type.\n\nExample: Trier des produits\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nJoint des chemins relatifs au répertoire racine de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Une ou plusieurs parties du chemin. |\n\nReturns: `String` Un chemin absolu.\n\nUne partie qui commence par `~` est un chemin absolu et remplace ce qui précède. Sous Windows, le résultat utilise `/`.\n\nExample: Chemins dans l'application\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nJoint les parties d'un chemin avec `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Une ou plusieurs parties. |\n\nReturns: `String`\n\nLes barres obliques au début et à la fin de chaque partie sont supprimées, et le résultat commence par `/`. Les parties vides sont ignorées.\n\nExample: Joindre\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nRenvoie l'extension d'un nom de fichier sans le point.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le nom de fichier ou l'URL. |\n| `raw` | `Boolean` | no | `false` | Conserve la casse d'origine. |\n\nReturns: `String`\n\nL'extension est mise en minuscules sauf si `raw` vaut `true`. Une query string après `?` est ignorée. Renvoie une chaîne vide quand il n'y a pas d'extension.\n\nExample: Extension\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nRenvoie la dernière partie d'un chemin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le chemin. |\n\nReturns: `String`\n\nFonctionne avec les séparateurs `/` et `\\` ; un séparateur final est ignoré.\n\nExample: Nom de fichier\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nRenvoie le type de contenu (type MIME) d'une extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | L'extension. |\n\nReturns: `String`\n\nL'extension peut commencer par un point. Une extension inconnue donne `application/octet-stream`.\n\nExample: Type MIME\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nEnregistre ou modifie le type de contenu d'une extension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | L'extension, avec ou sans point. |\n| `type` | `String` | yes |  | Le type de contenu. |\n\nReturns: `Boolean` `true`\n\nLe framework utilise cette table pour servir les fichiers statiques, une nouvelle extension devient donc aussi un fichier statique connu.\n\nExample: Une nouvelle extension\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nListe tous les fichiers et répertoires d'un répertoire et de ses sous-répertoires.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le répertoire. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtre. |\n| `unified` | `Boolean` | no | `false` | Utilise `/` sous Windows. |\n\nReturns: `Promise|undefined` Une Promise sans callback.\n\n`callback(files, directories)` reçoit des tableaux de chemins absolus. Sans callback, la méthode renvoie une Promise de `{ files, directories }`. `filter` est une chaîne (une partie du nom, insensible à la casse), une RegExp, ou `function(path, isDirectory)` qui renvoie `true` pour conserver un élément ; les filtres de type chaîne et RegExp ne s'appliquent qu'aux fichiers. Avec `unified` à `true`, les chemins sous Windows utilisent `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nListe les fichiers avec leurs statistiques.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le répertoire. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtre. |\n| `unified` | `Boolean` | no | `false` | Utilise `/` sous Windows. |\n\nReturns: `Promise|undefined` Une Promise sans callback.\n\nFonctionne comme `U.ls()`, mais chaque fichier est `{ filename, stats }`, où `stats` est l'objet `fs.Stats` (taille, dates). Les répertoires restent des chemins.\n\nExample: Taille totale\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nEncode les caractères spéciaux HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `String`\n\n`null` et `undefined` donnent une chaîne vide ; les autres valeurs sont d'abord converties en chaîne. Elle appelle `String.encode()`.\n\nExample: HTML sûr\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDécode les entités HTML en caractères.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `String`\n\nL'inverse de `U.encode()`. `null` et `undefined` donnent une chaîne vide.\n\nExample: Texte brut\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nEncode une chaîne ou un Buffer en Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | La valeur. |\n\nReturns: `String`\n\n`U.atob(value)` décode le Base64 en une chaîne UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nAnalyse du XML en un objet plat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | Le XML. |\n| `replace` | `Boolean` | no | `false` | Remplace les caractères spéciaux des clés. |\n\nReturns: `Object`\n\nChaque clé est le chemin d'un élément joint par des points, par exemple `root.item` ; les éléments répétés donnent un tableau de valeurs. Les attributs sont stockés sous la clé suivie de `[]`, par exemple `root.item[]`. Avec `replace` à `true`, les caractères `[`, `]`, `:`, `.` et `_` des clés deviennent `_`. Les CDATA sont lues comme du texte.\n\nExample: Lire du XML\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConvertit n'importe quelle valeur en entier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n| `def` | `Number` | no | `0` | Valeur pour une entrée vide ou invalide. |\n\nReturns: `Number`\n\n`null`, `undefined` et une chaîne vide donnent `def`. Un nombre est renvoyé tel quel. `U.parseFloat(value, [def])` et `U.parseBoolean(value, [def])` fonctionnent de la même façon pour les décimaux et les booléens (`def` vaut `false` pour les booléens ; un nombre vaut `true` lorsqu'il est supérieur à 0).\n\nExample: Valeurs de query\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nRenvoie la distance entre deux coordonnées GPS en kilomètres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Latitude du premier point. |\n| `lon1` | `Number` | yes |  | Longitude du premier point. |\n| `lat2` | `Number` | yes |  | Latitude du second point. |\n| `lon2` | `Number` | yes |  | Longitude du second point. |\n\nReturns: `Number` Kilomètres.\n\nUtilise la formule de haversine sur une sphère de 6371 km de rayon ; le résultat a au plus 3 décimales.\n\nExample: De Bratislava à Prague\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifie du CSS avec le compilateur intégré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Code CSS. |\n\nReturns: `String`\n\nLe même compilateur que celui utilisé par le framework pour les fichiers `.css` statiques.\n\nExample: Minifier\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifie du JavaScript avec le compilateur intégré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Code JavaScript. |\n\nReturns: `String`\n\nSupprime les commentaires et les espaces blancs. Le même compilateur que celui utilisé par le framework pour les fichiers `.js` statiques.\n\nExample: Minifier\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifie du HTML avec le compilateur intégré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Code HTML. |\n\nReturns: `String`\n\nSupprime les espaces blancs entre les balises.\n\nExample: Minifier\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nStocke un statut nommé de ton application et le transmet à `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | Le nom du statut, ou un objet `$`. |\n| `data` | `Object` | yes |  | N'importe quelle valeur. |\n| `timeout` | `Number` | no |  | Diffère la mise à jour et fusionne les appels pendant ce délai, en millisecondes. |\n\nReturns: `undefined` Rien.\n\nChaque `id` possède un objet de statut `{ id, data, date }`. `STATUS()` remplace son `data`, définit `date` et appelle `DEF.onStatus(meta)` si tu l'as défini. À la place d'un `id`, tu peux passer un objet `$` ; son `ID` (ou `name`) sert d'id.\n\nAvec `timeout` (en millisecondes), la mise à jour est différée : le premier appel démarre le minuteur, les appels suivants ne modifient que `data`, et `DEF.onStatus()` s'exécute une seule fois avec les dernières données à la fin du minuteur. Utilise-le pour des valeurs qui changent souvent, comme une progression.\n\nAvec `CONF.allow_stats_status` (par défaut `true`), tous les statuts sont ajoutés sous `status` à l'instantané de statistiques que Total.js écrit dans `<main script>.json` (`CONF.allow_stats_snapshot`).\n\nExample: Progression d'une importation\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nChiffre une chaîne avec une clé et un masque aléatoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Le texte à chiffrer. |\n| `key` | `String` | yes |  | La clé. |\n| `encode` | `String` | no | `base64` | Un encodage de Buffer ou `buffer`. |\n\nReturns: `String|Buffer` La valeur chiffrée.\n\nLe résultat change à chaque appel à cause d'un masque aléatoire de 4 octets. `encode` est un encodage de Buffer (par défaut `base64`) ; `buffer` renvoie le Buffer brut. Relis-le avec `U.decrypt_data()` et la même clé. Il s'agit d'une obfuscation légère, pas d'un remplacement de `U.encrypt_crypto()`.\n\nExample: Chiffrer une chaîne JSON\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nDéchiffre une valeur produite par `U.encrypt_data()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | La valeur chiffrée. |\n| `key` | `String` | yes |  | La clé utilisée pour le chiffrement. |\n| `encode` | `String` | no | `base64` | L'encodage de `value`. |\n\nReturns: `String` Le texte déchiffré ou `null`.\n\n`value` est une chaîne dans l'encodage `encode` (par défaut `base64`) ou un Buffer. Renvoie `null` quand la valeur ne peut pas être lue. Une mauvaise clé donne une chaîne incorrecte, pas `null`, vérifie donc le résultat (par exemple avec `parseJSON()`).\n\nExample: Déchiffrer un jeton\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nChiffre des données avec un algorithme de chiffrement Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Un nom d'algorithme de chiffrement, par exemple `aes-256-cbc`. |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `String|Buffer` | yes |  | Les données. |\n\nReturns: `Buffer` Les données chiffrées.\n\nUtilise `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. La longueur de la clé doit correspondre à l'algorithme (32 caractères pour `aes-256-cbc`). `CONF.default_crypto_iv` est créé par défaut à partir de l'application, définis-le donc dans la configuration lorsque d'autres applications doivent déchiffrer les données.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nDéchiffre des données produites par `U.encrypt_crypto()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le nom de l'algorithme de chiffrement. |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `Buffer` | yes |  | Les données chiffrées. |\n\nReturns: `Buffer` Les données déchiffrées ou `undefined`.\n\nUtilise `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Renvoie `undefined` quand les données ne peuvent pas être déchiffrées.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nConvertit un nombre en chaîne en base 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Un nombre positif. |\n\nReturns: `String`\n\nL'alphabet est composé des chiffres, puis des lettres majuscules et minuscules. Les décimales sont arrondies vers le bas. Relis-le avec `U.from62()`.\n\nExample: Code court\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nReconvertit en nombre une chaîne en base 62 issue de `U.convert62()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Une chaîne en base 62. |\n\nReturns: `Number`\n\nExample: Retour à un nombre\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nRenvoie un groupe numérique de longueur fixe pour un identifiant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Un identifiant. |\n| `count` | `Number` | no | `4` | Le nombre de chiffres. |\n\nReturns: `String` Une chaîne de chiffres.\n\nLa valeur est `HASH(id, true)` modulo `10^count`, complétée par des zéros jusqu'à `count` chiffres. Le même id donne toujours le même groupe, ce qui est utile pour répartir des fichiers dans des sous-répertoires.\n\nExample: Sous-répertoires\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nConvertit n'importe quelle valeur en booléen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Une valeur. |\n| `def` | `Boolean` | no | `false` | La valeur par défaut. |\n\nReturns: `Boolean`\n\nUn booléen est renvoyé tel quel, un nombre vaut `true` lorsqu'il est supérieur à `0`, les autres valeurs sont converties en chaîne et analysées avec `String.parseBoolean()`. `null` et `undefined` renvoient `def`.\n\nExample: Valeur de query\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nConvertit n'importe quelle valeur en nombre décimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Une valeur. |\n| `def` | `Number` | no | `0` | La valeur par défaut. |\n\nReturns: `Number`\n\nUn nombre est renvoyé tel quel, les autres valeurs sont converties en chaîne et analysées avec `String.parseFloat()`. `null`, `undefined` et une chaîne vide renvoient `def`.\n\nExample: Prix\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nVérifie qu'une valeur est une `Date` valide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Une valeur. |\n\nReturns: `Boolean`\n\nRenvoie `false` pour une date invalide comme `new Date('abc')`.\n\nExample: Valider une date\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nLes noms anglais des jours de la semaine.\n\nReturns: `String Array`\n\nLe tableau commence par `Sunday`, il correspond donc à `Date.getDay()`.\n\nExample: Nom du jour\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nLes noms anglais des mois.\n\nReturns: `String Array`\n\nLe tableau commence par `January`, il correspond donc à `Date.getMonth()`.\n\nExample: Nom du mois\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nRenvoie le texte d'un code de statut HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Un code de statut HTTP. |\n| `addCode` | `Boolean` | no | `true` | Ajoute le code au texte. |\n\nReturns: `String`\n\nLe texte provient de `http.STATUS_CODES`. Avec `addCode` (par défaut `true`), le code est ajouté devant.\n\nExample: Texte du statut\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSérialise un objet en query string encodée pour URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un objet. |\n\nReturns: `String` Par exemple `q=total&page=2`.\n\nLes chaînes sont encodées avec `encodeURIComponent()`, les nombres et les booléens sont ajoutés tels quels, les tableaux sont joints par `,`. `null`, `undefined`, les chaînes vides et les autres objets (y compris les dates) sont ignorés. Renvoie une chaîne vide quand rien n'est ajouté.\n\nExample: Query string\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDécode une chaîne base64 en une chaîne UTF-8.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Une chaîne base64. |\n\nReturns: `String`\n\nL'inverse de `U.btoa()`.\n\nExample: Décoder\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nVérifie qu'une URL est relative.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Une URL. |\n\nReturns: `Boolean`\n\nRenvoie `false` quand l'URL commence par `//` ou contient `http://` ou `https://`.\n\nExample: Redirection sûre\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nVérifie qu'une URL ressemble à un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un chemin d'URL. |\n\nReturns: `Boolean`\n\nRenvoie `true` quand les 8 derniers caractères de l'URL contiennent un point, par exemple `/img/logo.png`.\n\nExample: Fichier ou route\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nRésout l'adresse IPv4 d'une URL et la met en cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Une URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | Une valeur transmise au callback. |\n\nReturns: `Array|undefined` Les adresses en cache quand aucun callback n'est fourni.\n\n`callback(err, uri, param, addresses)` reçoit l'URL analysée avec `uri.host` remplacé par la première adresse. Les adresses sont mises en cache par hôte ; sans callback, la méthode renvoie les adresses en cache (ou `undefined`). Une résolution échouée est retentée une fois. La commande `clear_dnscache` vide le cache.\n\nExample: Résolution DNS\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nJoint des parties d'URL avec exactement un `/` entre elles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Une ou plusieurs parties d'URL. |\n\nReturns: `String`\n\nContrairement à `U.join()`, elle n'ajoute pas de `/` initial et conserve les parties telles quelles.\n\nExample: Construire une URL\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nAjoute `/` au début et à la fin d'un chemin lorsqu'il manque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin. |\n\nReturns: `String`\n\nExample: Normaliser\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nAjoute un délimiteur final à un chemin lorsqu'il manque.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin. |\n| `delimiter` | `String` | no | `/` | Le délimiteur. |\n\nReturns: `String`\n\nUn chemin vide renvoie le délimiteur.\n\nExample: Chemin de répertoire\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nRenvoie l'extension de fichier d'un type de contenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | Un type de contenu. |\n\nReturns: `String`\n\nRecherche parmi les types de contenu connus de `U.getContentType()` (y compris ceux ajoutés avec `U.setContentType()`). Renvoie la première correspondance sans point, ou `undefined`.\n\nExample: Extension\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nConvertit un objet en tableau d'éléments `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un objet. |\n\nReturns: `Array`\n\n`null` ou `undefined` renvoie `EMPTYARRAY`.\n\nExample: Liste clé-valeur\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nRaccourci pour `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | Les données. |\n| `encoding` | `String` | no | `utf8` | L'encodage d'une chaîne. |\n\nReturns: `Buffer`\n\nExample: Depuis du base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nRaccourci pour `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | La taille en octets. |\n\nReturns: `Buffer` Un buffer rempli de zéros.\n\nExample: Buffer vide\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nUn replacer pour `JSON.stringify()` qui supprime les valeurs `null` et `undefined`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé. |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `Object`\n\nExample: Un JSON plus compact\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nL'état des files d'attente créées par `U.queue()`.\n\nReturns: `Object`\n\nUn objet indexé par le nom de la file d'attente. Chaque élément contient `limit`, `running` et `pending` (les callbacks en attente). Lis-le uniquement à des fins de surveillance.\n\nExample: Éléments en attente\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nUn petit émetteur d'événements.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Un objet à étendre. |\n\nReturns: `EventEmitter2`\n\n`new U.EventEmitter2()` crée un émetteur. `U.EventEmitter2(obj)` (sans `new`) ajoute `emit()`, `on()`, `once()`, `off()`, `removeListener()` et `removeAllListeners()` à un objet existant et le renvoie ; `U.EventEmitter2.extend(obj)` fait la même chose. Les écouteurs sont conservés dans `$events`. `emit()` transmet jusqu'à 7 arguments et `this` est l'émetteur.\n\nExample: Étendre un objet\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nSupprime un écouteur ou tous les écouteurs d'un événement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement. |\n| `fn` | `Function` | no |  | L'écouteur. |\n\nReturns: `EventEmitter2` L'émetteur.\n\nSans `fn`, tous les écouteurs de `name` sont supprimés. `removeListener()` est un alias. `removeAllListeners([name])` supprime les écouteurs d'un événement ou de tous les événements.\n\nExample: Supprimer un écouteur\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nAppelle un callback après que `next()` a été appelé `count` fois.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre d'appels à `next()` à attendre. |\n| `callback` | `Function` | no |  | La fonction à appeler. |\n\nReturns: `Callback` Une instance avec `next()` et `done(fn)`.\n\nRenvoie une instance avec `next()` et `done(callback)`. Le callback s'exécute une seule fois, quand le compteur en attente atteint zéro. La classe est également disponible sous le nom global `Callback`.\n\nExample: Attendre 3 tâches\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nStocke de nombreux éléments dans des fichiers temporaires, page par page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nom unique, utilisé dans les noms de fichiers. |\n| `max` | `Number` | no | `50` | Le nombre d'éléments par fichier. |\n\nReturns: `Chunker`\n\nChaque groupe de `max` éléments écrits avec `write()` va dans un fichier `{name}-{index}.chunker` du répertoire temporaire, compressé avec deflate. Relis-les page par page avec `each()` ou `read()`. Propriétés : `compress` (par défaut `true`), `autoremove` (par défaut `true`, supprime chaque fichier après sa lecture), `count`, `pages` et `percentage` (progression de `each()`). La classe est disponible sous `U.Chunker`.\n\nExample: Exporter par pages\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nAjoute un élément.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Un élément sérialisable en JSON. |\n\nReturns: `Chunker`\n\nQuand `max` éléments sont en attente, ils sont écrits dans un nouveau fichier. `append()` est un alias. Appelle `end()` après le dernier élément.\n\nExample: Écrire\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nÉcrit les éléments restants dans le dernier fichier.\n\nReturns: `Chunker`\n\nExample: Terminer l'écriture\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nLit toutes les pages une par une.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | S'exécute après la dernière page. |\n\nReturns: `Chunker`\n\n`onItem(items, next, index)` reçoit les éléments d'une page ; appelle `next()` pour lire la page suivante. `onEnd()` s'exécute après la dernière page. `percentage` indique la progression.\n\nExample: Traiter les pages\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nLit une page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | L'indice de la page à partir de `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`callback(err, items)` reçoit les éléments de la page, ou un tableau vide quand le fichier n'existe pas. Elle attend tant que des fichiers sont encore en cours d'écriture.\n\nExample: Première page\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nSupprime tous les fichiers du chunker.\n\nReturns: `Chunker`\n\n`destroy()` supprime également les fichiers et libère l'instance.\n\nExample: Nettoyer\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nInterroge un tableau d'objets avec le query builder NoSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | Les éléments ou une URL. |\n\nReturns: `Reader`\n\n`items` est un tableau (ou un seul objet), ou l'URL d'un contenu TextDB qui est téléchargé et lu en flux. Sans `items`, ajoute les données avec `reader.push(items)` et termine avec `reader.push(null)`, ou utilise `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` et `stats(groupfield, datefield, key, [type])` renvoient un query builder NoSQL (`where()`, `sort()`, `take()`, `callback()`...). `list()` renvoie `{ page, pages, limit, count, items }`. `assign(data)` crée une requête à partir d'un objet de requête sérialisé.\n\nExample: Filtrer un tableau\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nAjoute des éléments au reader.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | Les données, ou `null` à la fin. |\n\nReturns: `undefined`\n\nPasse un tableau ou un objet pour chaque bloc de données, puis `null` pour terminer et obtenir les résultats.\n\nExample: Ajouter des données\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDécoupe un flux de blocs en parties selon des délimiteurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Le délimiteur ou le début d'une partie. |\n| `end` | `String|Buffer` | no |  | La fin d'une partie. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | Le nombre de parties à ignorer. |\n| `stream` | `Stream` | no |  | Un flux pour l'événement `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nRenvoie `function(chunk)` à laquelle tu passes chaque bloc. Sans `end`, chaque partie se termine par `beg` (et l'inclut), par exemple une ligne terminée par `\\n`. Avec `end`, chaque partie commence par `beg` et se termine par `end`. `callback(value, index)` reçoit chaque partie sous forme de chaîne ; renvoie `false` pour arrêter. `skip` ignore les premières parties. Avec `stream`, les données restantes sont traitées lors de l'événement `end` du flux. `U.streamer2()` est identique mais fournit des Buffers.\n\nExample: Lire des lignes\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nIdentique à `U.streamer()`, mais les parties sont des Buffers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Le délimiteur ou le début d'une partie. |\n| `end` | `String|Buffer` | no |  | La fin d'une partie. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | Le nombre de parties à ignorer. |\n| `stream` | `Stream` | no |  | Un flux pour l'événement `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Parties binaires\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nLit un fichier texte ligne par ligne, par lots.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier. |\n\nReturns: `Object` Un lecteur de flux.\n\nRenvoie un lecteur de flux TextDB. Définis `ondocuments` (appelé avec `this.docs`, les lignes d'un lot jointes par `,` ; renvoie `false` pour arrêter) et `$callback` (appelé à la fin), puis appelle `openread()`. Définis `array = true` pour obtenir `docs` sous forme de tableau de lignes. Les lignes qui commencent par `-` sont ignorées.\n\nExample: Lire un fichier JSON-lines\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias de `path.join()` de Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Une ou plusieurs parties du chemin. |\n\nReturns: `String`\n\nExample: Joindre\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nVérifie qu'un fichier ou un répertoire existe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un chemin. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Vérifier un fichier\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nCrée un répertoire de l'application s'il n'existe pas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du répertoire. |\n\nReturns: `undefined`\n\n`name` est le nom d'un paramètre `CONF.directory_{name}`, par exemple `databases`. La vérification s'exécute une fois par nom.\n\nExample: S'assurer que le répertoire existe\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias de `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le répertoire. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` est un alias de `U.ls2()`.\n\nExample: Lister des fichiers\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nSupprime des fichiers un par un.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | Les fichiers. |\n| `callback` | `Function` | no |  | S'exécute à la fin. |\n\nReturns: `undefined`\n\nLes erreurs sont ignorées.\n\nExample: Supprimer des fichiers\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nSupprime des répertoires avec tout leur contenu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | Les répertoires. |\n| `callback` | `Function` | no |  | S'exécute à la fin. |\n\nReturns: `undefined`\n\nLes erreurs sont ignorées.\n\nExample: Supprimer un répertoire\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire privé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_private` (par défaut `/private/`).\n\nExample: Chemin\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des modèles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_models` (par défaut `/models/`).\n\nExample: Chemin\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des builds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_builds` (par défaut `/builds/`).\n\nExample: Chemin\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des vues.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_views` (par défaut `/views/`).\n\nExample: Chemin\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des mises à jour.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_updates` (par défaut `/updates/`).\n\nExample: Chemin\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des modules.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_modules` (par défaut `/modules/`).\n\nExample: Chemin\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des schémas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_schemas` (par défaut `/schemas/`).\n\nExample: Chemin\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des extensions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_extensions` (par défaut `/extensions/`).\n\nExample: Chemin\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des opérations.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_operations` (par défaut `/operations/`).\n\nExample: Chemin\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des tâches.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_tasks` (par défaut `/tasks/`).\n\nExample: Chemin\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des contrôleurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_controllers` (par défaut `/controllers/`).\n\nExample: Chemin\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des définitions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_definitions` (par défaut `/definitions/`).\n\nExample: Chemin\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des tests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_tests` (par défaut `/tests/`).\n\nExample: Chemin\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des services.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_services` (par défaut `/services/`).\n\nExample: Chemin\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des paquets.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_packages` (par défaut `/packages/`).\n\nExample: Chemin\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des thèmes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_themes` (par défaut `/themes/`).\n\nExample: Chemin\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des composants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_components` (par défaut `/components/`).\n\nExample: Chemin\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des templates.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_templates` (par défaut `/templates/`).\n\nExample: Chemin\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nRenvoie un chemin dans le répertoire des plugins.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_plugins` (par défaut `/plugins/`).\n\nExample: Chemin\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nRenvoie un chemin dans le répertoire des flowstreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier. |\n\nReturns: `String` Un chemin absolu.\n\nLe répertoire est `CONF.directory_flowstreams` (par défaut `/flowstreams/`).\n\nExample: Chemin\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nAffiche un avertissement sur du code obsolète.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Ce qui est obsolète. |\n| `message` | `String` | yes |  | Ce qu'il faut utiliser à la place. |\n\nElle écrit la date, le nom et le message dans la console et incrémente `F.stats.other.obsolete`. Rien n'est affiché lorsque `CONF.nowarnings` vaut `true` (le framework le définit lorsque le watcher redémarre l'application avec `--restart`).\n\nExample: Avertir\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nGénère un identifiant unique avec une partie temporelle décimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Le nom d'un compteur séparé. |\n| `date` | `Date` | no | `NOW` | Le moment de l'identifiant. |\n\nReturns: `String` L'identifiant.\n\nComme `UID()`, mais la partie temporelle est le nombre de minutes depuis le 2020-01-31 23:00 UTC écrit en chiffres décimaux. Les identifiants se terminent par la lettre de version `b`. Avec `type`, chaque type a son propre compteur. `date` construit l'identifiant pour un autre moment.\n\nExample: Identifiant\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Utilità","summary":"Le funzioni di U (utils.js) e le funzioni di supporto e gli oggetti globali del framework.","markdown":"---\ntitle: \"Utilità\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utilità\n\n> Le funzioni di U (utils.js) e le funzioni di supporto e gli oggetti globali del framework.\n\nTotal.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.\n\n## API\n\n### U\n\nType: `property`\n\nLa libreria di utilità del framework (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` e `utils` sono lo stesso oggetto. È globale, quindi lo usi in controller, schemi, moduli e plugin senza `require()`.\n\nExample: Usare una funzione di supporto\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nUn alias globale dell'istanza del framework `F`.\n\nReturns: `Framework`\n\n`Total`, `F` e `framework` fanno riferimento allo stesso oggetto.\n\nExample: Stesso oggetto\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\nUn `Date` che il framework aggiorna regolarmente.\n\nReturns: `Date`\n\nLeggere `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.\n\nExample: Timestamp di un record\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nUn oggetto vuoto congelato.\n\nReturns: `Object`\n\nUsalo come valore predefinito che non viene mai modificato. È congelato, quindi le assegnazioni non hanno effetto.\n\nExample: Opzioni predefinite\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nUn array vuoto congelato.\n\nReturns: `Array`\n\nUsalo come valore predefinito che non viene mai modificato. È congelato, quindi `push()` solleva un errore.\n\nExample: Elenco predefinito\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nUna funzione vuota.\n\nReturns: `undefined`\n\nPassala dove è richiesta una callback e non ti serve il risultato.\n\nExample: Ignorare una callback\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nUn oggetto globale vuoto per i tuoi dati condivisi.\n\nReturns: `Object`\n\nIl framework crea `MAIN = {}` e non lo usa. Salvaci i valori validi per tutta l'applicazione, per esempio i dati caricati all'avvio.\n\nExample: Impostazioni condivise\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nUn oggetto globale vuoto per il tuo repository di valori.\n\nReturns: `Object`\n\nIl framework crea `REPO = {}` e non lo usa. È un secondo namespace come `MAIN`.\n\nExample: Mettere in cache un elenco\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nUn oggetto globale vuoto per le tue funzioni condivise.\n\nReturns: `Object`\n\nIl framework crea `FUNC = {}`. Mettici le funzioni di supporto che più file dell'app chiamano.\n\nExample: Funzione condivisa\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nUn oggetto globale per dati temporanei che il framework svuota.\n\nReturns: `Object`\n\nIl 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.\n\nExample: Valore di breve durata\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nTutti i moduli caricati, per nome.\n\nReturns: `Object`\n\nLo stesso oggetto di `F.modules`. Una chiave è il nome del file in `/modules/` (o l'`id` esportato dal modulo).\n\nExample: Elencare i moduli\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nRestituisce un modulo caricato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del modulo. |\n\nReturns: `Object` Il modulo, oppure `null`.\n\nLegge `F.modules[name]`. Il risultato è l'`exports` del file del modulo, oppure `null` quando non è caricato alcun modulo con quel nome.\n\nExample: Chiamare un modulo\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nAggiunge una riga a un file di log nella directory `/logs/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del file di log senza `.log`. |\n| `value` | `Object` | yes |  | Uno o più valori da scrivere. |\n\nReturns: `undefined`\n\nLa 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.\n\nExample: Registrare un pagamento\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nChiama una funzione in stile callback e restituisce una Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Una funzione che accetta una callback come ultimo argomento. |\n| `a` | `Object` | no |  | Primo argomento. |\n| `b` | `Object` | no |  | Secondo argomento. |\n| `c` | `Object` | no |  | Terzo argomento. |\n\nReturns: `Promise`\n\n`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.\n\nExample: Leggere un file\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Una tua funzione\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nAttende finché una condizione è vera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Restituisce `true` quando l'attesa è finita. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Tempo massimo in ms. |\n| `interval` | `Number` | no | `500` | Tempo tra un controllo e l'altro in ms. |\n\nReturns: `undefined`\n\n`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)`.\n\nExample: Attendere una connessione\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nCrea un identificatore univoco breve.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Il nome di un contatore indipendente. |\n| `date` | `Date` | no | `NOW` | Il tempo codificato nell'ID. |\n\nReturns: `String`\n\nL'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`.\n\nExample: Un nuovo record\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Contatore per tipo\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nCrea un identificatore univoco con la parte temporale in base 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Il nome di un contatore indipendente. |\n| `date` | `Date` | no | `NOW` | Il tempo codificato nell'ID. |\n\nReturns: `String`\n\nFunziona come `UID()` ma codifica il tempo in esadecimale, quindi l'ID è un po' più lungo (versione `c`). Ignora `CONF.default_uid`.\n\nExample: ID esadecimale\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nCrea un GUID o una stringa casuale di una lunghezza data.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Lunghezza di una stringa casuale. |\n\nReturns: `String`\n\nSenza `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()`.\n\nExample: Forma UUID\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Token casuale\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nCrea una copia profonda di un oggetto o di un array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto o l'array da copiare. |\n| `skip` | `Object` | no |  | Chiavi da escludere, come `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Esclude le funzioni. |\n\nReturns: `Object` Un nuovo oggetto.\n\nGli 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()`.\n\nExample: Copiare senza una chiave\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nCopia tutte le proprietà di `source` in `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Oggetto da leggere. |\n| `target` | `Object` | no |  | Oggetto da scrivere. |\n\nReturns: `Object` L'oggetto di destinazione.\n\nOgni 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)`.\n\nExample: Unire\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nCrea un hash di una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo. |\n| `type` | `String` | no |  | Un algoritmo di hash. |\n\nReturns: `Number|String`\n\nSenza `type` restituisce un hash numerico veloce (a 32 bit senza segno). `type` può essere `md5`, `sha1`, `sha256`, `sha512`, `crc32` o `crc32unsigned`. Chiama `value.hash()`.\n\nExample: Numerico e MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nAggiunge un oggetto a un URL come query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | L'URL. |\n| `obj` | `Object` | yes |  | Valori della query string. |\n\nReturns: `String`\n\nI 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`.\n\nExample: Costruire un URL\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nConfronta due array di oggetti in base a una chiave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Nome della chiave, per esempio `id`. |\n| `db` | `Object[]` | yes |  | Gli elementi salvati. |\n| `form` | `Object[]` | yes |  | I nuovi elementi. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nRestituisce `{ 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.\n\nExample: Sincronizzare un elenco\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory radice dell'app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un percorso relativo. |\n\nReturns: `String`\n\nIl risultato usa sempre `/` come separatore.\n\nExample: Un file nella radice\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory temporanea e crea la directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String`\n\nLa directory è `CONF.directory_temp`. `PATH.tmp()` e `PATH.temporary()` sono alias.\n\nExample: File temporaneo\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei database e crea la directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String`\n\nLa directory è `CONF.directory_databases`.\n\nExample: Un file di dati\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei log e crea la directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String`\n\nLa directory è `CONF.directory_logs`. `LOGGER()` scrive lì.\n\nExample: Leggere un log\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nCrea una directory con tutte le directory padre mancanti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso assoluto. |\n| `cache` | `Boolean` | no | `false` | Salta i percorsi creati in precedenza. |\n\nReturns: `undefined`\n\nFunziona 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.\n\nExample: Directory per gli upload\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nRestituisce un intero casuale tra `min` e `max`, entrambi inclusi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Il valore più alto. |\n| `min` | `Number` | no | `0` | Il valore più basso. |\n\nReturns: `Number`\n\nExample: Un dado\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nRestituisce una stringa casuale di lettere e cifre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Numero di caratteri. |\n\nReturns: `String`\n\nI caratteri sono `0-9`, `A-Z` e `a-z`.\n\nExample: Un codice\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nRestituisce una stringa casuale di lettere.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Numero di caratteri. |\n\nReturns: `String`\n\nI caratteri sono `A-Z` e `a-z`, senza cifre.\n\nExample: Solo lettere\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nRestituisce una stringa di cifre casuali.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Numero di cifre. |\n\nReturns: `String`\n\nLa prima cifra non è mai `0`, quindi `+value` ha lo stesso numero di cifre. Il risultato è una stringa.\n\nExample: Un PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nFirma un ID in modo che il client non possa modificarlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | L'ID. |\n| `key` | `String` | no | `CONF.secret` | Una chiave segreta. |\n\nReturns: `String`\n\nIl 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.\n\nExample: Link con un ID firmato\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nLegge un ID firmato da `U.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | L'ID firmato. |\n| `key` | `String` | no | `CONF.secret` | La chiave segreta usata per firmarlo. |\n\nReturns: `String|Number` L'ID, oppure `null`.\n\nRestituisce l'ID originale (un numero quando è stato firmato un numero), oppure `null` quando il checksum non corrisponde.\n\nExample: Verificare un ID da un URL\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nCopia i valori di `source` nelle chiavi che `target` ha già.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Oggetto da leggere. |\n| `target` | `Object` | no |  | Oggetto da scrivere. |\n\nReturns: `Object` L'oggetto di destinazione.\n\nVengono 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()`.\n\nExample: Aggiornare i campi noti\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nAggiunge le proprietà di `source` a `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Oggetto da scrivere. |\n| `source` | `Object` | yes |  | Oggetto da leggere. |\n| `rewrite` | `Boolean` | no | `true` | Sovrascrive i valori esistenti. |\n\nReturns: `Object` L'oggetto di destinazione.\n\nI 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.\n\nExample: Valori predefiniti\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nMantiene solo alcune proprietà di un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | L'oggetto o l'array di oggetti. |\n| `props` | `String[]|Object` | yes |  | Chiavi da mantenere. |\n| `reverse` | `Boolean` | no | `false` | Rimuove invece le chiavi elencate. |\n\nReturns: `Object|Object[]`\n\n`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.\n\nExample: Campi pubblici\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nLegge un valore tramite un percorso come `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto. |\n| `path` | `String` | yes |  | Il percorso con i punti. |\n\nReturns: `Object` Il valore.\n\nRestituisce `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`.\n\nExample: Valore annidato\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nScrive un valore tramite un percorso come `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto. |\n| `path` | `String` | yes |  | Il percorso con i punti. |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `Object` Il valore.\n\nGli 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.\n\nExample: Costruire un oggetto\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nRimuove gli spazi esterni da tutti i valori stringa di un oggetto o di un array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | Il valore da elaborare. |\n| `clean` | `Boolean` | no | `false` | Sostituisce le stringhe vuote con `undefined`. |\n\nReturns: `Object` Lo stesso valore.\n\nVengono elaborati anche gli oggetti e gli array annidati; l'oggetto viene modificato sul posto. Con `clean` impostato su `true`, le stringhe vuote diventano `undefined`.\n\nExample: Pulire un form\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nEstrae le parole chiave da un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | Il testo. |\n| `forSearch` | `Boolean` | no | `true` | Normalizza le parole per la ricerca. |\n| `alternative` | `Boolean` | no | `false` | Accorcia le parole. |\n| `max_count` | `Number` | no | `200` | Numero massimo di parole lette. |\n| `max_length` | `Number` | no | `20` | Le parole più lunghe vengono saltate. |\n| `min_length` | `Number` | no | `2` | Le parole più corte vengono saltate. |\n\nReturns: `String[]`\n\nIl 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.\n\nExample: Indice di ricerca\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nEsegue funzioni con un limite al numero di esecuzioni contemporanee.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della coda. |\n| `max` | `Number` | yes |  | Numero massimo di funzioni in esecuzione. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | Un valore passato a `fn`. |\n\nReturns: `Boolean`\n\nOgni 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.\n\nExample: Tre download alla volta\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nCrea una funzione di confronto per `Array.sort()` a partire da un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | La definizione dell'ordinamento. |\n\nReturns: `Function` `function(a, b)`\n\n`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.\n\nExample: Ordinare i prodotti\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nUnisce percorsi relativi alla directory radice dell'app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o più parti del percorso. |\n\nReturns: `String` Un percorso assoluto.\n\nUna parte che inizia con `~` è un percorso assoluto e sostituisce ciò che la precede. Su Windows il risultato usa `/`.\n\nExample: Percorsi nell'app\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nUnisce parti di un percorso con `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o più parti. |\n\nReturns: `String`\n\nGli slash all'inizio e alla fine di ogni parte vengono rimossi, e il risultato inizia con `/`. Le parti vuote vengono saltate.\n\nExample: Unire\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nRestituisce l'estensione di un nome di file senza il punto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il nome del file o l'URL. |\n| `raw` | `Boolean` | no | `false` | Mantiene maiuscole e minuscole originali. |\n\nReturns: `String`\n\nL'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.\n\nExample: Estensione\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nRestituisce l'ultima parte di un percorso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Il percorso. |\n\nReturns: `String`\n\nFunziona con i separatori `/` e `\\`; un separatore finale viene ignorato.\n\nExample: Nome del file\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nRestituisce il content type (tipo MIME) per un'estensione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | L'estensione. |\n\nReturns: `String`\n\nL'estensione può iniziare con un punto. Un'estensione sconosciuta restituisce `application/octet-stream`.\n\nExample: Tipo MIME\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nRegistra o modifica il content type di un'estensione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | L'estensione, con o senza punto. |\n| `type` | `String` | yes |  | Il content type. |\n\nReturns: `Boolean` `true`\n\nIl framework usa la tabella per servire i file statici, quindi una nuova estensione diventa anche un file statico noto.\n\nExample: Una nuova estensione\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nElenca tutti i file e le directory in una directory e nelle sue sottodirectory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtro. |\n| `unified` | `Boolean` | no | `false` | Usa `/` su Windows. |\n\nReturns: `Promise|undefined` Una Promise, senza callback.\n\n`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 `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nElenca i file con le loro statistiche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Un filtro. |\n| `unified` | `Boolean` | no | `false` | Usa `/` su Windows. |\n\nReturns: `Promise|undefined` Una Promise, senza callback.\n\nFunziona come `U.ls()`, ma ogni file è `{ filename, stats }`, dove `stats` è l'oggetto `fs.Stats` (dimensione, date). Le directory restano percorsi.\n\nExample: Dimensione totale\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nCodifica i caratteri speciali HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `String`\n\n`null` e `undefined` restituiscono una stringa vuota; gli altri valori vengono prima convertiti in stringa. Chiama `String.encode()`.\n\nExample: HTML sicuro\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDecodifica le entità HTML riportandole a caratteri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `String`\n\nL'opposto di `U.encode()`. `null` e `undefined` restituiscono una stringa vuota.\n\nExample: Testo semplice\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nCodifica una stringa o un Buffer in Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Il valore. |\n\nReturns: `String`\n\n`U.atob(value)` decodifica il Base64 riportandolo a una stringa UTF-8.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nAnalizza un XML e lo trasforma in un oggetto piatto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | L'XML. |\n| `replace` | `Boolean` | no | `false` | Sostituisce i caratteri speciali nelle chiavi. |\n\nReturns: `Object`\n\nOgni 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.\n\nExample: Leggere un XML\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nConverte qualsiasi valore in un intero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n| `def` | `Number` | no | `0` | Valore per un input vuoto o non valido. |\n\nReturns: `Number`\n\n`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).\n\nExample: Valori della query\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nRestituisce la distanza tra due coordinate GPS in chilometri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Latitudine del primo punto. |\n| `lon1` | `Number` | yes |  | Longitudine del primo punto. |\n| `lat2` | `Number` | yes |  | Latitudine del secondo punto. |\n| `lon2` | `Number` | yes |  | Longitudine del secondo punto. |\n\nReturns: `Number` Chilometri.\n\nUsa la formula dell'emisenoverso (haversine) su una sfera con raggio di 6371 km; il risultato ha al massimo 3 cifre decimali.\n\nExample: Da Bratislava a Praga\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifica il CSS con il compilatore integrato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Codice CSS. |\n\nReturns: `String`\n\nLo stesso compilatore che il framework usa per i file `.css` statici.\n\nExample: Minificare\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifica il JavaScript con il compilatore integrato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Codice JavaScript. |\n\nReturns: `String`\n\nRimuove commenti e spazi bianchi. Lo stesso compilatore che il framework usa per i file `.js` statici.\n\nExample: Minificare\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifica l'HTML con il compilatore integrato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Codice HTML. |\n\nReturns: `String`\n\nRimuove gli spazi bianchi tra i tag.\n\nExample: Minificare\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nSalva uno stato con nome della tua app e lo passa a `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | Il nome dello stato, oppure un oggetto `$`. |\n| `data` | `Object` | yes |  | Qualsiasi valore. |\n| `timeout` | `Number` | no |  | Ritarda l'aggiornamento e unisce le chiamate in questo intervallo, in millisecondi. |\n\nReturns: `undefined` Niente.\n\nOgni `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.\n\nCon `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.\n\nCon `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`).\n\nExample: Avanzamento di un'importazione\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nCifra una stringa con una chiave e una maschera casuale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Il testo da cifrare. |\n| `key` | `String` | yes |  | La chiave. |\n| `encode` | `String` | no | `base64` | Una codifica di Buffer oppure `buffer`. |\n\nReturns: `String|Buffer` Il valore cifrato.\n\nL'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()`.\n\nExample: Cifrare una stringa JSON\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nDecifra un valore creato da `U.encrypt_data()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Il valore cifrato. |\n| `key` | `String` | yes |  | La chiave usata per la cifratura. |\n| `encode` | `String` | no | `base64` | La codifica di `value`. |\n\nReturns: `String` Il testo decifrato oppure `null`.\n\n`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()`).\n\nExample: Decifrare un token\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nCifra i dati con un cifrario di Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il nome di un cifrario, per esempio `aes-256-cbc`. |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `String|Buffer` | yes |  | I dati. |\n\nReturns: `Buffer` I dati cifrati.\n\nUsa `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.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nDecifra i dati creati da `U.encrypt_crypto()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il nome del cifrario. |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `Buffer` | yes |  | I dati cifrati. |\n\nReturns: `Buffer` I dati decifrati oppure `undefined`.\n\nUsa `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Restituisce `undefined` quando i dati non possono essere decifrati.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nConverte un numero in una stringa in base 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Un numero positivo. |\n\nReturns: `String`\n\nL'alfabeto è composto da cifre, poi lettere maiuscole e minuscole. I decimali vengono arrotondati per difetto. Rileggilo con `U.from62()`.\n\nExample: Codice breve\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nRiconverte in numero una stringa in base 62 prodotta da `U.convert62()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una stringa in base 62. |\n\nReturns: `Number`\n\nExample: Di nuovo in numero\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nRestituisce un gruppo numerico di lunghezza fissa per un identificatore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Un identificatore. |\n| `count` | `Number` | no | `4` | Il numero di cifre. |\n\nReturns: `String` Una stringa di cifre.\n\nIl 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.\n\nExample: Sottodirectory\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nConverte qualsiasi valore in un booleano.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valore. |\n| `def` | `Boolean` | no | `false` | Il valore predefinito. |\n\nReturns: `Boolean`\n\nUn 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`.\n\nExample: Valore della query\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nConverte qualsiasi valore in un numero decimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valore. |\n| `def` | `Number` | no | `0` | Il valore predefinito. |\n\nReturns: `Number`\n\nUn 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`.\n\nExample: Prezzo\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nVerifica che un valore sia un `Date` valido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Un valore. |\n\nReturns: `Boolean`\n\nRestituisce `false` per una data non valida come `new Date('abc')`.\n\nExample: Validare una data\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nNomi inglesi dei giorni della settimana.\n\nReturns: `String Array`\n\nL'array inizia con `Sunday`, quindi corrisponde a `Date.getDay()`.\n\nExample: Nome del giorno\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nNomi inglesi dei mesi.\n\nReturns: `String Array`\n\nL'array inizia con `January`, quindi corrisponde a `Date.getMonth()`.\n\nExample: Nome del mese\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nRestituisce il testo di un codice di stato HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | Un codice di stato HTTP. |\n| `addCode` | `Boolean` | no | `true` | Aggiunge il codice al testo. |\n\nReturns: `String`\n\nIl testo proviene da `http.STATUS_CODES`. Con `addCode` (predefinito `true`) il codice viene aggiunto davanti.\n\nExample: Testo dello stato\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSerializza un oggetto in una query string codificata per URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un oggetto. |\n\nReturns: `String` Per esempio `q=total&page=2`.\n\nLe 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.\n\nExample: Query string\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDecodifica una stringa base64 in una stringa UTF-8.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Una stringa base64. |\n\nReturns: `String`\n\nL'operazione inversa di `U.btoa()`.\n\nExample: Decodificare\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nVerifica che un URL sia relativo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un URL. |\n\nReturns: `Boolean`\n\nRestituisce `false` quando l'URL inizia con `//` o contiene `http://` o `https://`.\n\nExample: Redirect sicuro\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nVerifica che un URL sembri un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un percorso URL. |\n\nReturns: `Boolean`\n\nRestituisce `true` quando gli ultimi 8 caratteri dell'URL contengono un punto, per esempio `/img/logo.png`.\n\nExample: File o route\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nRisolve l'indirizzo IPv4 di un URL e lo mette in cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Un URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | Un valore passato alla callback. |\n\nReturns: `Array|undefined` Gli indirizzi in cache quando non viene fornita alcuna callback.\n\n`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.\n\nExample: Risoluzione DNS\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nUnisce parti di un URL con esattamente un `/` tra di esse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o più parti dell'URL. |\n\nReturns: `String`\n\nA differenza di `U.join()`, non aggiunge un `/` iniziale e mantiene le parti così come sono.\n\nExample: Costruire un URL\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nAggiunge `/` all'inizio e alla fine di un percorso quando manca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso. |\n\nReturns: `String`\n\nExample: Normalizzare\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nAggiunge un delimitatore finale a un percorso quando manca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso. |\n| `delimiter` | `String` | no | `/` | Il delimitatore. |\n\nReturns: `String`\n\nUn percorso vuoto restituisce il delimitatore.\n\nExample: Percorso di una directory\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nRestituisce l'estensione di file di un content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | Un content type. |\n\nReturns: `String`\n\nCerca tra i content type noti a `U.getContentType()` (inclusi quelli aggiunti con `U.setContentType()`). Restituisce la prima corrispondenza senza punto, oppure `undefined`.\n\nExample: Estensione\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nConverte un oggetto in un array di elementi `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Un oggetto. |\n\nReturns: `Array`\n\n`null` o `undefined` restituiscono `EMPTYARRAY`.\n\nExample: Elenco chiave-valore\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nScorciatoia per `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | I dati. |\n| `encoding` | `String` | no | `utf8` | La codifica di una stringa. |\n\nReturns: `Buffer`\n\nExample: Da base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nScorciatoia per `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | La dimensione in byte. |\n\nReturns: `Buffer` Un buffer riempito di zeri.\n\nExample: Buffer vuoto\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nUn replacer per `JSON.stringify()` che rimuove i valori `null` e `undefined`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave. |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `Object`\n\nExample: JSON più piccolo\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nLo stato delle code create da `U.queue()`.\n\nReturns: `Object`\n\nUn 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.\n\nExample: Elementi in attesa\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nUn piccolo emettitore di eventi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Un oggetto da estendere. |\n\nReturns: `EventEmitter2`\n\n`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.\n\nExample: Estendere un oggetto\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nRimuove un listener o tutti i listener di un evento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento. |\n| `fn` | `Function` | no |  | Il listener. |\n\nReturns: `EventEmitter2` L'emettitore.\n\nSenza `fn` vengono rimossi tutti i listener di `name`. `removeListener()` è un alias. `removeAllListeners([name])` rimuove i listener di un evento o di tutti gli eventi.\n\nExample: Rimuovere un listener\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nChiama una callback dopo che `next()` è stato chiamato `count` volte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Quante chiamate a `next()` attendere. |\n| `callback` | `Function` | no |  | La funzione da chiamare. |\n\nReturns: `Callback` Un'istanza con `next()` e `done(fn)`.\n\nRestituisce 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.\n\nExample: Attendere 3 attività\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nSalva molti elementi in file temporanei, pagina per pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Un nome univoco, usato nei nomi dei file. |\n| `max` | `Number` | no | `50` | Il numero di elementi per file. |\n\nReturns: `Chunker`\n\nOgni `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`.\n\nExample: Esportare a pagine\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nAggiunge un elemento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Un elemento che può essere serializzato in JSON. |\n\nReturns: `Chunker`\n\nQuando ci sono `max` elementi in attesa, vengono scritti in un nuovo file. `append()` è un alias. Chiama `end()` dopo l'ultimo elemento.\n\nExample: Scrivere\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nScrive gli elementi rimanenti nell'ultimo file.\n\nReturns: `Chunker`\n\nExample: Terminare la scrittura\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nLegge tutte le pagine una alla volta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | Eseguita dopo l'ultima pagina. |\n\nReturns: `Chunker`\n\n`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.\n\nExample: Elaborare le pagine\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nLegge una pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | L'indice della pagina a partire da `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`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.\n\nExample: Prima pagina\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nRimuove tutti i file del chunker.\n\nReturns: `Chunker`\n\nAnche `destroy()` rimuove i file e rilascia l'istanza.\n\nExample: Pulizia\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nInterroga un array di oggetti con il query builder NoSQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | Gli elementi o un URL. |\n\nReturns: `Reader`\n\n`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.\n\nExample: Filtrare un array\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nAggiunge elementi al reader.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | I dati, oppure `null` alla fine. |\n\nReturns: `undefined`\n\nPassa un array o un singolo oggetto per ogni blocco di dati, poi `null` per terminare e ottenere i risultati.\n\nExample: Inserire dati\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nDivide uno stream di blocchi in parti tramite delimitatori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Il delimitatore o l'inizio di una parte. |\n| `end` | `String|Buffer` | no |  | La fine di una parte. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | Il numero di parti da saltare. |\n| `stream` | `Stream` | no |  | Uno stream per l'evento `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nRestituisce `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.\n\nExample: Leggere righe\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nUguale a `U.streamer()`, ma le parti sono Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Il delimitatore o l'inizio di una parte. |\n| `end` | `String|Buffer` | no |  | La fine di una parte. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | Il numero di parti da saltare. |\n| `stream` | `Stream` | no |  | Uno stream per l'evento `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Parti binarie\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nLegge un file di testo riga per riga, a gruppi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file. |\n\nReturns: `Object` Uno stream reader.\n\nRestituisce 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.\n\nExample: Leggere un file JSON-lines\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias di `path.join()` di Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Una o più parti del percorso. |\n\nReturns: `String`\n\nExample: Unire\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nVerifica che un file o una directory esista.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Un percorso. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Verificare un file\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nCrea una directory dell'app se non esiste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della directory. |\n\nReturns: `undefined`\n\n`name` è il nome di un'impostazione `CONF.directory_{name}`, per esempio `databases`. Il controllo viene eseguito una volta per nome.\n\nExample: Assicurarsi che la directory esista\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias di `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La directory. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` è un alias di `U.ls2()`.\n\nExample: Elencare i file\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nRimuove i file uno alla volta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | I file. |\n| `callback` | `Function` | no |  | Eseguita alla fine. |\n\nReturns: `undefined`\n\nGli errori vengono ignorati.\n\nExample: Rimuovere file\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nRimuove le directory con tutto il loro contenuto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | Le directory. |\n| `callback` | `Function` | no |  | Eseguita alla fine. |\n\nReturns: `undefined`\n\nGli errori vengono ignorati.\n\nExample: Rimuovere una directory\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory privata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_private` (predefinita `/private/`).\n\nExample: Percorso\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei modelli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_models` (predefinita `/models/`).\n\nExample: Percorso\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle build.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_builds` (predefinita `/builds/`).\n\nExample: Percorso\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle viste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_views` (predefinita `/views/`).\n\nExample: Percorso\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory degli aggiornamenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_updates` (predefinita `/updates/`).\n\nExample: Percorso\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei moduli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_modules` (predefinita `/modules/`).\n\nExample: Percorso\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory degli schemi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_schemas` (predefinita `/schemas/`).\n\nExample: Percorso\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle estensioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_extensions` (predefinita `/extensions/`).\n\nExample: Percorso\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle operazioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_operations` (predefinita `/operations/`).\n\nExample: Percorso\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle attività.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_tasks` (predefinita `/tasks/`).\n\nExample: Percorso\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_controllers` (predefinita `/controllers/`).\n\nExample: Percorso\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory delle definizioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_definitions` (predefinita `/definitions/`).\n\nExample: Percorso\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_tests` (predefinita `/tests/`).\n\nExample: Percorso\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei servizi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_services` (predefinita `/services/`).\n\nExample: Percorso\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei pacchetti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_packages` (predefinita `/packages/`).\n\nExample: Percorso\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei temi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_themes` (predefinita `/themes/`).\n\nExample: Percorso\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei componenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_components` (predefinita `/components/`).\n\nExample: Percorso\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei template.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_templates` (predefinita `/templates/`).\n\nExample: Percorso\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nRestituisce un percorso nella directory dei plugin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_plugins` (predefinita `/plugins/`).\n\nExample: Percorso\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nRestituisce un percorso nella directory dei flowstream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file. |\n\nReturns: `String` Un percorso assoluto.\n\nLa directory è `CONF.directory_flowstreams` (predefinita `/flowstreams/`).\n\nExample: Percorso\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nStampa un avviso su codice obsoleto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Cosa è obsoleto. |\n| `message` | `String` | yes |  | Cosa usare al suo posto. |\n\nScrive 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`).\n\nExample: Avvisare\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nGenera un identificatore univoco con una parte temporale decimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Il nome di un contatore separato. |\n| `date` | `Date` | no | `NOW` | Il momento dell'identificatore. |\n\nReturns: `String` L'identificatore.\n\nCome `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.\n\nExample: Identificatore\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabZaH78Y61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/utilities/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Utility","summary":"Funkcie U (utils.js) a globálni pomocníci a objekty frameworku.","markdown":"---\ntitle: Utility\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/utilities/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Utility\n\n> Funkcie U (utils.js) a globálni pomocníci a objekty frameworku.\n\nTotal.js definuje pomocníkov v globálnom rozsahu a v objekte `U` (`Utils`), takže ich môže používať každý súbor aplikácie bez `require()`. Návod [Utility](../../guides/utilities/) vysvetľuje, ako ich používať, s príkladmi; táto stránka je presná referencia.\n\n## API\n\n### U\n\nType: `property`\n\nKnižnica utilít frameworku (`utils.js`).\n\nReturns: `Object`\n\n`U`, `Utils` a `utils` sú ten istý objekt. Je globálny, takže ho používaš v kontroléroch, schémach, moduloch a pluginoch bez `require()`.\n\nExample: Použitie pomocníka\n```js\nvar ext = U.getExtension('photo.JPG'); // 'jpg'\n```\n\n### Total\n\nType: `property` · Since: `0.0.96`\n\nGlobálny alias inštancie frameworku `F`.\n\nReturns: `Framework`\n\n`Total`, `F` a `framework` odkazujú na ten istý objekt.\n\nExample: Ten istý objekt\n```js\nconsole.log(Total === F); // true\n```\n\n### NOW\n\nType: `property`\n\n`Date`, ktorý framework pravidelne obnovuje.\n\nReturns: `Date`\n\nČítanie `NOW` je lacnejšie ako `new Date()`. Framework ho znova nastavuje vo svojich interných intervaloch (približne každú minútu) a pri niektorých volaniach, napríklad `LOGGER()`. Použi ho tam, kde stačí presnosť na minútu; pre presný čas použi `new Date()`. `F.datetime` číta a zapisuje tú istú hodnotu.\n\nExample: Časová značka záznamu\n```js\nvar model = { id: UID(), dtcreated: NOW };\n```\n\n### EMPTYOBJECT\n\nType: `property`\n\nZmrazený prázdny objekt.\n\nReturns: `Object`\n\nPouži ho ako predvolenú hodnotu, ktorá sa nikdy nemení. Je zmrazený, takže priradenia doň nemajú žiadny efekt.\n\nExample: Predvolené voľby\n```js\nfunction send(options) {\n\toptions = options || EMPTYOBJECT;\n\treturn options.timeout || 5000;\n}\n```\n\n### EMPTYARRAY\n\nType: `property`\n\nZmrazené prázdne pole.\n\nReturns: `Array`\n\nPouži ho ako predvolenú hodnotu, ktorá sa nikdy nemení. Je zmrazené, takže `push()` vyhodí chybu.\n\nExample: Predvolený zoznam\n```js\nvar items = response.items || EMPTYARRAY;\n```\n\n### NOOP()\n\nType: `method`\n\nPrázdna funkcia.\n\nReturns: `undefined`\n\nOdovzdaj ju tam, kde sa vyžaduje callback a výsledok nepotrebuješ.\n\nExample: Ignorovanie callbacku\n```js\nFs.unlink(PATH.temp('export.csv'), NOOP);\n```\n\n### MAIN\n\nType: `property`\n\nPrázdny globálny objekt pre tvoje vlastné zdieľané dáta.\n\nReturns: `Object`\n\nFramework vytvorí `MAIN = {}` a nepoužíva ho. Ukladaj doň hodnoty pre celú aplikáciu, napríklad dáta načítané pri štarte.\n\nExample: Zdieľané nastavenia\n```js\n// definitions/init.js\nMAIN.settings = { currency: 'EUR' };\n\n// any other file\nvar currency = MAIN.settings.currency;\n```\n\n### REPO\n\nType: `property`\n\nPrázdny globálny objekt pre tvoj vlastný repozitár hodnôt.\n\nReturns: `Object`\n\nFramework vytvorí `REPO = {}` a nepoužíva ho. Je to druhý menný priestor ako `MAIN`.\n\nExample: Cache zoznamu\n```js\nREPO.countries = ['SK', 'CZ', 'AT'];\n```\n\n### FUNC\n\nType: `property`\n\nPrázdny globálny objekt pre tvoje vlastné zdieľané funkcie.\n\nReturns: `Object`\n\nFramework vytvorí `FUNC = {}`. Vlož doň pomocníkov, ktorých volá viac súborov aplikácie.\n\nExample: Zdieľaná funkcia\n```js\n// definitions/func.js\nFUNC.price = function(value) {\n\treturn value.format(2) + ' EUR';\n};\n\n// a controller or a schema\nvar text = FUNC.price(12.5);\n```\n\n### TEMP\n\nType: `property`\n\nGlobálny objekt pre dočasné dáta, ktorý framework maže.\n\nReturns: `Object`\n\nFramework nahrádza `TEMP` novým prázdnym objektom pri svojom pravidelnom čistení (každých `CONF.default_interval_clear_cache` minút, predvolene 10). Nenechávaj tam nič, čo budeš neskôr potrebovať.\n\nExample: Krátkodobá hodnota\n```js\nif (!TEMP.stats)\n\tTEMP.stats = compute();\n```\n\n### MODS\n\nType: `property`\n\nVšetky načítané moduly podľa ich názvu.\n\nReturns: `Object`\n\nTen istý objekt ako `F.modules`. Kľúčom je názov súboru v `/modules/` (alebo `id`, ktoré modul exportuje).\n\nExample: Výpis modulov\n```js\nObject.keys(MODS).forEach(function(name) {\n\tconsole.log(name);\n});\n```\n\n### MODULE(name)\n\nType: `method`\n\nVráti načítaný modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modulu. |\n\nReturns: `Object` Modul, alebo `null`.\n\nČíta `F.modules[name]`. Výsledkom je `exports` súboru modulu, alebo `null`, keď modul s týmto názvom nie je načítaný.\n\nExample: Volanie modulu\n```js\n// modules/mailer.js\nexports.send = function(email) { /* ... */ };\n\n// anywhere\nMODULE('mailer').send('info@example.com');\n```\n\n### LOGGER(name, value1, [value2], [...])\n\nType: `method`\n\nPripojí riadok do log súboru v adresári `/logs/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov log súboru bez `.log`. |\n| `value` | `Object` | yes |  | Jedna alebo viac hodnôt na zápis. |\n\nReturns: `undefined`\n\nRiadok je `yyyy-MM-dd HH:mm:ss | values` v súbore `{name}.log`. Hodnoty sú oddelené medzerou; objekty sa formátujú cez `util.inspect()`. Adresár sa vytvorí, keď neexistuje, a zápisy idú cez `U.queue()` s najviac 5 zápismi naraz.\n\nExample: Zalogovanie platby\n```js\nLOGGER('payments', 'order', order.id, 'paid', order.price);\n// logs/payments.log:\n// 2021-03-01 10:22:05 | order 1a2b3c paid 39.9\n```\n\n### PROMISIFY(fn, [a], [b], [c])\n\nType: `method` · Since: `0.0.97`\n\nZavolá funkciu v štýle callbacku a vráti Promise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia, ktorá ako posledný argument berie callback. |\n| `a` | `Object` | no |  | Prvý argument. |\n| `b` | `Object` | no |  | Druhý argument. |\n| `c` | `Object` | no |  | Tretí argument. |\n\nReturns: `Promise`\n\n`fn` sa zavolá so zadanými argumentmi a callbackom `function(err, response)` ako posledným argumentom. Promise sa zamietne s `err` alebo vyrieši s `response`. Podporujú sa až tri argumenty; argumenty, ktoré sú `undefined`, sa neodovzdávajú.\n\nExample: Čítanie súboru\n```js\nvar Fs = require('fs');\nvar content = await PROMISIFY(Fs.readFile, PATH.root('readme.md'), 'utf8');\n```\n\nExample: Vlastná funkcia\n```js\nfunction load(id, callback) {\n\tcallback(null, { id: id });\n}\n\nvar item = await PROMISIFY(load, '123');\n```\n\n### WAIT(validator, callback, [timeout], [interval])\n\nType: `method`\n\nČaká, kým nie je podmienka splnená.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `validator` | `Function` | yes |  | Vráti `true`, keď čakanie skončilo. |\n| `callback` | `Function` | yes |  | `function(err, success)`. |\n| `timeout` | `Number` | no | `5000` | Maximálny čas v ms. |\n| `interval` | `Number` | no | `500` | Čas medzi kontrolami v ms. |\n\nReturns: `undefined`\n\n`validator()` sa skontroluje hneď a potom každých `interval` ms. Keď vráti `true`, zavolá sa `callback(null, true)`. Keď skôr uplynie `timeout` ms, zavolá sa `callback(Error('Timeout'), false)`.\n\nExample: Čakanie na spojenie\n```js\nWAIT(function() {\n\treturn MAIN.db != null;\n}, function(err) {\n\tif (err)\n\t\tconsole.log('Database is not ready');\n\telse\n\t\tconsole.log('Ready');\n}, 10000);\n```\n\n### UID([type], [date])\n\nType: `method`\n\nVytvorí krátky unikátny identifikátor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Názov nezávislého počítadla. |\n| `date` | `Date` | no | `NOW` | Čas zakódovaný v ID. |\n\nReturns: `String`\n\nID je reťazec založený na čase, napríklad `24j0y001xn51d`, ktorý sa triedi podľa času vytvorenia. Je unikátny v rámci bežiacej inštancie (framework pridáva náhodný kľúč inštancie). `type` udržiava samostatné počítadlo pre každý typ, takže ID rôznych kolekcií nezdieľajú sekvenciu. `date` vytvorí ID pre iný čas. `CONF.default_uid` vyberá verziu: `r` dá náhodné ID (`UIDR()`), `f` variant v sústave 62; predvolená je verzia `d`.\n\nExample: Nový záznam\n```js\nvar model = {};\nmodel.id = UID();\nmodel.dtcreated = NOW;\n```\n\nExample: Počítadlo pre typ\n```js\nvar orderid = UID('orders');\nvar invoiceid = UID('invoices');\n```\n\n### UID16([type], [date])\n\nType: `method`\n\nVytvorí unikátny identifikátor s časovou časťou v sústave 16.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Názov nezávislého počítadla. |\n| `date` | `Date` | no | `NOW` | Čas zakódovaný v ID. |\n\nReturns: `String`\n\nFunguje ako `UID()`, ale čas kóduje hexadecimálne, takže ID je o niečo dlhšie (verzia `c`). Ignoruje `CONF.default_uid`.\n\nExample: ID založené na hex\n```js\nvar id = UID16(); // e.g. '367b52002xn60c'\n```\n\n### GUID([length])\n\nType: `method`\n\nVytvorí GUID alebo náhodný reťazec zadanej dĺžky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Dĺžka náhodného reťazca. |\n\nReturns: `String`\n\nBez `length` vráti reťazec v tvare UUID `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx` zostavený z aktuálneho času a náhodných čísel. S `length` vráti náhodné malé písmená a číslice tejto dĺžky. Dostupné aj ako `U.GUID()`.\n\nExample: Tvar UUID\n```js\nvar id = GUID(); // '1a1defc8-efc8-2c86-8d36-938350b51dfd'\n```\n\nExample: Náhodný token\n```js\nvar token = GUID(30);\n```\n\n### CLONE(obj, [skip], [skipFunctions])\n\nType: `method`\n\nVytvorí hlbokú kópiu objektu alebo poľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt alebo pole na skopírovanie. |\n| `skip` | `Object` | no |  | Kľúče na vynechanie, ako `{ key: true }`. |\n| `skipFunctions` | `Boolean` | no | `false` | Vynechá funkcie. |\n\nReturns: `Object` Nový objekt.\n\nVnorené objekty a polia sa kopírujú; hodnoty `Date` a `Error` sa ponechajú ako referencie a Buffery sa kopírujú. `skip` je objekt kľúčov, ktoré sa vynechajú (`{ password: 1 }`) na prvej úrovni objektov. Dostupné aj ako `U.clone()`.\n\nExample: Kópia bez kľúča\n```js\nvar copy = CLONE(user, { password: 1 });\ncopy.name = 'Peter'; // user.name is unchanged\n```\n\n### COPY(source, [target])\n\nType: `method`\n\nSkopíruje všetky vlastnosti zo `source` do `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objekt na čítanie. |\n| `target` | `Object` | no |  | Objekt na zápis. |\n\nReturns: `Object` Cieľ.\n\nKaždý kľúč zo `source` sa naklonuje do `target`, aj kľúče, ktoré `target` nemá. Bez `target` vráti novú kópiu `source`. Je to `U.copy(source, target, true)`.\n\nExample: Zlúčenie\n```js\nvar target = { a: 0 };\nCOPY({ a: 1, z: 9 }, target);\n// target: { a: 1, z: 9 }\n```\n\n### HASH(value, [type])\n\nType: `method`\n\nVytvorí hash reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text. |\n| `type` | `String` | no |  | Hashovací algoritmus. |\n\nReturns: `Number|String`\n\nBez `type` vráti rýchly číselný hash (32-bitový bez znamienka). `type` môže byť `md5`, `sha1`, `sha256`, `sha512`, `crc32` alebo `crc32unsigned`. Volá `value.hash()`.\n\nExample: Číselný a MD5\n```js\nHASH('abc');        // 96354\nHASH('abc', 'md5'); // '900150983cd24fb0d6963f7d28e17f72'\n```\n\n### QUERIFY([url], obj)\n\nType: `method`\n\nPridá objekt k URL ako query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | URL. |\n| `obj` | `Object` | yes |  | Hodnoty query stringu. |\n\nReturns: `String`\n\nHodnoty `null` alebo `undefined` sa vynechajú; dátumy sa zmenia na ISO reťazce a polia sa spoja čiarkami. Kľúče a hodnoty sa zakódujú. URL môže začínať metódou (`GET /api/`); query sa pridá k ceste. Bez URL vráti iba `?key=value`.\n\nExample: Zostavenie URL\n```js\nQUERIFY('GET /api/products/', { page: 2, q: 'a b' });\n// 'GET /api/products/?page=2&q=a%20b'\n\nQUERIFY({ page: 1 }); // '?page=1'\n```\n\n### DIFFARR(prop, db, form)\n\nType: `method`\n\nPorovná dve polia objektov podľa kľúča.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prop` | `String` | yes |  | Názov kľúča, napríklad `id`. |\n| `db` | `Object[]` | yes |  | Uložené položky. |\n| `form` | `Object[]` | yes |  | Nové položky. |\n\nReturns: `Object` `{ add: [], upd: [], rem: [] }`\n\nVráti `{ add, upd, rem }`: `add` obsahuje položky z `form`, ktoré nie sú v `db`, `upd` obsahuje páry `{ db, form }`, ktoré existujú v oboch, a `rem` obsahuje hodnoty kľúčov položiek z `db`, ktoré vo `form` chýbajú. Použi ho na uloženie zoznamu, ktorý používateľ upravil.\n\nExample: Synchronizácia zoznamu\n```js\nvar diff = DIFFARR('id', [{ id: 1 }, { id: 2 }], [{ id: 2, name: 'B' }, { id: 3 }]);\n// diff.add: [{ id: 3 }]\n// diff.upd: [{ db: { id: 2 }, form: { id: 2, name: 'B' } }]\n// diff.rem: [1]\n```\n\n### PATH.root([filename])\n\nType: `method`\n\nVráti cestu v koreňovom adresári aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Relatívna cesta. |\n\nReturns: `String`\n\nVýsledok vždy používa `/` ako oddeľovač.\n\nExample: Súbor v koreni\n```js\nvar filename = PATH.root('data/countries.json');\n```\n\n### PATH.temp([filename])\n\nType: `method`\n\nVráti cestu v dočasnom adresári a adresár vytvorí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String`\n\nAdresár je `CONF.directory_temp`. `PATH.tmp()` a `PATH.temporary()` sú aliasy.\n\nExample: Dočasný súbor\n```js\nvar filename = PATH.temp('export-' + UID() + '.csv');\n```\n\n### PATH.databases([filename])\n\nType: `method`\n\nVráti cestu v adresári databáz a adresár vytvorí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String`\n\nAdresár je `CONF.directory_databases`.\n\nExample: Dátový súbor\n```js\nvar filename = PATH.databases('settings.json');\n```\n\n### PATH.logs([filename])\n\nType: `method`\n\nVráti cestu v adresári logov a adresár vytvorí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String`\n\nAdresár je `CONF.directory_logs`. Zapisuje tam `LOGGER()`.\n\nExample: Čítanie logu\n```js\nrequire('fs').readFile(PATH.logs('payments.log'), 'utf8', function(err, text) {\n\tconsole.log(text);\n});\n```\n\n### PATH.mkdir(path, [cache])\n\nType: `method`\n\nVytvorí adresár so všetkými chýbajúcimi nadradenými adresármi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Absolútna cesta. |\n| `cache` | `Boolean` | no | `false` | Preskočí cesty vytvorené predtým. |\n\nReturns: `undefined`\n\nFunguje synchrónne. S `cache` nastaveným na `true` sa cesta, ktorá už bola vytvorená, znova nekontroluje, kým framework nevymaže svoju cache.\n\nExample: Adresár pre nahrané súbory\n```js\nvar dir = PATH.databases('uploads/2021/');\nPATH.mkdir(dir, true);\n```\n\n### U.random([max], [min])\n\nType: `method`\n\nVráti náhodné celé číslo medzi `min` a `max`, vrátane oboch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `100000` | Najvyššia hodnota. |\n| `min` | `Number` | no | `0` | Najnižšia hodnota. |\n\nReturns: `Number`\n\nExample: Hracia kocka\n```js\nvar dice = U.random(6, 1);\n```\n\n### U.random_text(length)\n\nType: `method`\n\nVráti náhodný reťazec písmen a číslic.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Počet znakov. |\n\nReturns: `String`\n\nZnaky sú `0-9`, `A-Z` a `a-z`.\n\nExample: Kód\n```js\nvar code = U.random_text(8); // e.g. '1qrWGUa7'\n```\n\n### U.random_string(length)\n\nType: `method`\n\nVráti náhodný reťazec písmen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Počet znakov. |\n\nReturns: `String`\n\nZnaky sú `A-Z` a `a-z`, bez číslic.\n\nExample: Iba písmená\n```js\nvar name = U.random_string(6);\n```\n\n### U.random_number(length)\n\nType: `method`\n\nVráti reťazec náhodných číslic.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Počet číslic. |\n\nReturns: `String`\n\nPrvá číslica nikdy nie je `0`, takže `+value` má rovnaký počet číslic. Výsledkom je reťazec.\n\nExample: PIN\n```js\nvar pin = U.random_number(6); // e.g. '986081'\n```\n\n### U.encrypt_uid(value, [key])\n\nType: `method`\n\nPodpíše ID, aby ho klient nemohol zmeniť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Number` | yes |  | ID. |\n| `key` | `String` | no | `CONF.secret` | Tajný kľúč. |\n\nReturns: `String`\n\nVýsledok obsahuje ID a kontrolný súčet ID a kľúča, napríklad `n3ck9tg6x123`. Hodnota nie je skrytá; je chránená proti zmenám. Na spätné prečítanie použi `U.decrypt_uid()`.\n\nExample: Odkaz s podpísaným ID\n```js\nvar link = '/download/' + U.encrypt_uid(file.id) + '/';\n```\n\n### U.decrypt_uid(value, [key])\n\nType: `method`\n\nPrečíta ID podpísané cez `U.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Podpísané ID. |\n| `key` | `String` | no | `CONF.secret` | Tajný kľúč použitý na podpis. |\n\nReturns: `String|Number` ID, alebo `null`.\n\nVráti pôvodné ID (číslo, keď bolo podpísané číslo), alebo `null`, keď kontrolný súčet nesedí.\n\nExample: Overenie ID z URL\n```js\nvar id = U.decrypt_uid(this.params.id);\nif (id == null) {\n\tthis.throw404();\n\treturn;\n}\n```\n\n### U.copy(source, [target])\n\nType: `method`\n\nSkopíruje hodnoty zo `source` do kľúčov, ktoré `target` už má.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object` | yes |  | Objekt na čítanie. |\n| `target` | `Object` | no |  | Objekt na zápis. |\n\nReturns: `Object` Cieľ.\n\nZapíšu sa iba kľúče, ktoré existujú v `target` (s inou hodnotou ako `undefined`); hodnoty sa klonujú. Bez `target` vráti novú kópiu `source`. Na skopírovanie všetkých kľúčov použi `COPY()`.\n\nExample: Aktualizácia známych polí\n```js\nvar item = { name: '', price: 0 };\nU.copy({ name: 'Book', price: 9, hack: true }, item);\n// item: { name: 'Book', price: 9 }\n```\n\n### U.extend(target, source, [rewrite])\n\nType: `method`\n\nPridá vlastnosti zo `source` do `target`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `target` | `Object` | yes |  | Objekt na zápis. |\n| `source` | `Object` | yes |  | Objekt na čítanie. |\n| `rewrite` | `Boolean` | no | `true` | Prepíše existujúce hodnoty. |\n\nReturns: `Object` Cieľ.\n\nHodnoty sa klonujú. S `rewrite` nastaveným na `false` sa kľúče, ktoré už majú hodnotu v `target`, ponechajú, takže `source` funguje ako sada predvolených hodnôt.\n\nExample: Predvolené hodnoty\n```js\nvar options = { timeout: 1000 };\nU.extend(options, { timeout: 5000, retry: 3 }, false);\n// options: { timeout: 1000, retry: 3 }\n```\n\n### U.reduce(source, props, [reverse])\n\nType: `method`\n\nPonechá iba niektoré vlastnosti objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `Object|Object[]` | yes |  | Objekt alebo pole objektov. |\n| `props` | `String[]|Object` | yes |  | Kľúče na ponechanie. |\n| `reverse` | `Boolean` | no | `false` | Namiesto toho odstráni uvedené kľúče. |\n\nReturns: `Object|Object[]`\n\n`props` je pole kľúčov alebo objekt, ktorého kľúče sa použijú. S `reverse` nastaveným na `true` sa uvedené kľúče naopak odstránia. Pole ako `source` zredukuje každú položku. Výsledkom je nový objekt.\n\nExample: Verejné polia\n```js\nvar output = U.reduce(user, ['id', 'name']);\nvar safe = U.reduce(user, ['password'], true);\n```\n\n### U.get(obj, path)\n\nType: `method`\n\nPrečíta hodnotu podľa cesty ako `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt. |\n| `path` | `String` | yes |  | Cesta s bodkami. |\n\nReturns: `Object` Hodnota.\n\nVráti `undefined`, keď časť cesty neexistuje. Indexy sa píšu ako `items[0].name`. Cesty, ktoré obsahujú znaky podobné kódu (medzery, zátvorky volaní, `__proto__` a podobne), vrátia `undefined`.\n\nExample: Vnorená hodnota\n```js\nU.get({ address: { city: 'Bratislava' } }, 'address.city'); // 'Bratislava'\nU.get({}, 'address.city'); // undefined\n```\n\n### U.set(obj, path, value)\n\nType: `method`\n\nZapíše hodnotu podľa cesty ako `address.city`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt. |\n| `path` | `String` | yes |  | Cesta s bodkami. |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `Object` Hodnota.\n\nChýbajúce objekty na ceste sa vytvoria. Cesta, ktorá končí `[]`, vloží hodnotu do poľa. Cesty, ktoré obsahujú znaky podobné kódu, sa ignorujú.\n\nExample: Zostavenie objektu\n```js\nvar obj = {};\nU.set(obj, 'address.city', 'Bratislava');\nU.set(obj, 'tags[]', 'new');\n// { address: { city: 'Bratislava' }, tags: ['new'] }\n```\n\n### U.trim(obj, [clean])\n\nType: `method`\n\nOreže všetky reťazcové hodnoty objektu alebo poľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object|Array|String` | yes |  | Hodnota na orezanie. |\n| `clean` | `Boolean` | no | `false` | Nahradí prázdne reťazce hodnotou `undefined`. |\n\nReturns: `Object` Tá istá hodnota.\n\nOrežú sa aj vnorené objekty a polia; objekt sa mení na mieste. S `clean` nastaveným na `true` sa prázdne reťazce zmenia na `undefined`.\n\nExample: Vyčistenie formulára\n```js\nU.trim({ name: ' Peter ', note: '  ' }, true);\n// { name: 'Peter', note: undefined }\n```\n\n### U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrahuje z textu kľúčové slová.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `content` | `String|String[]` | yes |  | Text. |\n| `forSearch` | `Boolean` | no | `true` | Normalizuje slová pre vyhľadávanie. |\n| `alternative` | `Boolean` | no | `false` | Skráti slová. |\n| `max_count` | `Number` | no | `200` | Maximálny počet prečítaných slov. |\n| `max_length` | `Number` | no | `20` | Dlhšie slová sa preskočia. |\n| `min_length` | `Number` | no | `2` | Kratšie slová sa preskočia. |\n\nReturns: `String[]`\n\nText sa prevedie na malé písmená a rozdelí na slová; výsledkom je zoznam unikátnych slov, najčastejšie ako prvé. S `forSearch` (predvolené) sa odstráni diakritika a `y` sa nahradí `i`, takže rovnaké slová sa pri vyhľadávaní zhodujú. `alternative` skráti každé slovo na 80 % jeho dĺžky, aby sa zhodovali tvary slov. `content` môže byť pole textov.\n\nExample: Vyhľadávací index\n```js\nvar keywords = U.keywords(product.name + ' ' + product.description).join(' ');\n```\n\n### U.queue(name, max, fn, [param])\n\nType: `method`\n\nSpúšťa funkcie s limitom, koľko ich beží naraz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov fronty. |\n| `max` | `Number` | yes |  | Maximum bežiacich funkcií. |\n| `fn` | `Function` | yes |  | `function(next, param)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn`. |\n\nReturns: `Boolean`\n\nKaždé volanie pridá `fn(next, param)` do fronty `name`. Naraz beží najviac `max` funkcií tejto fronty; každá musí zavolať `next()`, keď skončí. Vráti `true`, keď `fn` začne hneď, `false`, keď čaká.\n\nExample: Tri sťahovania naraz\n```js\nurls.forEach(function(url) {\n\tU.queue('downloads', 3, function(next, url) {\n\t\tdownload(url, next);\n\t}, url);\n});\n```\n\n### U.sortcomparer(sort)\n\nType: `method`\n\nVytvorí z textu porovnávaciu funkciu pre `Array.sort()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String` | yes |  | Definícia triedenia. |\n\nReturns: `Function` `function(a, b)`\n\n`sort` je zoznam polí oddelených čiarkami, každé s voliteľnou príponou `_asc` alebo `_desc`, napríklad `price_desc,name`. Podporované sú vnorené polia ako `address.city`. Reťazce, čísla, booleany a dátumy sa porovnávajú podľa svojho typu.\n\nExample: Zoradenie produktov\n```js\nproducts.sort(U.sortcomparer('price_desc,name_asc'));\n```\n\n### U.combine(path1, [path2], [...])\n\nType: `method`\n\nSpojí cesty relatívne ku koreňovému adresáru aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Jedna alebo viac častí cesty. |\n\nReturns: `String` Absolútna cesta.\n\nČasť, ktorá začína `~`, je absolútna cesta a nahradí to, čo bolo pred ňou. Na Windows výsledok používa `/`.\n\nExample: Cesty v aplikácii\n```js\nU.combine('/public/', 'img'); // '/www/app/public/img'\nU.combine('~/var/data/', 'file.txt'); // '/var/data/file.txt'\n```\n\n### U.join(path1, [path2], [...])\n\nType: `method`\n\nSpojí časti cesty znakom `/`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Jedna alebo viac častí. |\n\nReturns: `String`\n\nLomky na začiatku a na konci každej časti sa odstránia a výsledok začína `/`. Prázdne časti sa preskočia.\n\nExample: Spojenie\n```js\nU.join('a', '/b/', 'c'); // '/a/b/c'\n```\n\n### U.getExtension(filename, [raw])\n\nType: `method`\n\nVráti príponu názvu súboru bez bodky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Názov súboru alebo URL. |\n| `raw` | `Boolean` | no | `false` | Zachová pôvodnú veľkosť písmen. |\n\nReturns: `String`\n\nPrípona sa prevedie na malé písmená, pokiaľ `raw` nie je `true`. Query string za `?` sa ignoruje. Vráti prázdny reťazec, keď prípona neexistuje.\n\nExample: Prípona\n```js\nU.getExtension('Photo.JPG?width=200'); // 'jpg'\n```\n\n### U.getName(path)\n\nType: `method`\n\nVráti poslednú časť cesty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta. |\n\nReturns: `String`\n\nFunguje s oddeľovačmi `/` aj `\\`; koncový oddeľovač sa ignoruje.\n\nExample: Názov súboru\n```js\nU.getName('/www/app/public/logo.png'); // 'logo.png'\n```\n\n### U.getContentType(ext)\n\nType: `method`\n\nVráti content type (MIME typ) pre príponu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Prípona. |\n\nReturns: `String`\n\nPrípona môže začínať bodkou. Neznáma prípona dá `application/octet-stream`.\n\nExample: MIME typ\n```js\nU.getContentType('json'); // 'application/json'\nU.getContentType(U.getExtension(filename));\n```\n\n### U.setContentType(ext, type)\n\nType: `method`\n\nZaregistruje alebo zmení content type prípony.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ext` | `String` | yes |  | Prípona, s bodkou alebo bez nej. |\n| `type` | `String` | yes |  | Content type. |\n\nReturns: `Boolean` `true`\n\nFramework používa túto tabuľku na poskytovanie statických súborov, takže nová prípona sa stane aj známym statickým súborom.\n\nExample: Nová prípona\n```js\n// definitions/init.js\nU.setContentType('gpx', 'application/gpx+xml');\n```\n\n### U.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nVypíše všetky súbory a adresáre v adresári a jeho podadresároch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Adresár. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Filter. |\n| `unified` | `Boolean` | no | `false` | Na Windows používa `/`. |\n\nReturns: `Promise|undefined` Promise, keď chýba callback.\n\n`callback(files, directories)` dostane polia absolútnych ciest. Bez callbacku metóda vráti Promise s `{ files, directories }`. `filter` je reťazec (časť názvu, bez ohľadu na veľkosť písmen), RegExp, alebo `function(path, isDirectory)`, ktorá vráti `true`, aby sa položka ponechala; filtre reťazcom a RegExp sa vzťahujú iba na súbory. S `unified` nastaveným na `true` cesty na Windows používajú `/`.\n\nExample: Callback\n```js\nU.ls(PATH.public(), function(files, directories) {\n\tconsole.log(files.length, directories.length);\n}, /\\.(jpg|png)$/);\n```\n\nExample: Promise\n```js\nvar response = await U.ls(PATH.databases(), 'backup');\nconsole.log(response.files);\n```\n\n### U.ls2(path, [callback], [filter], [unified])\n\nType: `method`\n\nVypíše súbory s ich štatistikami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Adresár. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n| `filter` | `String|RegExp|Function` | no |  | Filter. |\n| `unified` | `Boolean` | no | `false` | Na Windows používa `/`. |\n\nReturns: `Promise|undefined` Promise, keď chýba callback.\n\nFunguje ako `U.ls()`, ale každý súbor je `{ filename, stats }`, kde `stats` je objekt `fs.Stats` (veľkosť, dátumy). Adresáre sú stále cesty.\n\nExample: Celková veľkosť\n```js\nU.ls2(PATH.temp(), function(files) {\n\tvar size = 0;\n\tfor (var file of files)\n\t\tsize += file.stats.size;\n\tconsole.log(size.filesize());\n});\n```\n\n### U.encode(value)\n\nType: `method`\n\nZakóduje špeciálne HTML znaky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `String`\n\n`null` a `undefined` dajú prázdny reťazec; iné hodnoty sa najprv prevedú na reťazec. Volá `String.encode()`.\n\nExample: Bezpečné HTML\n```js\nU.encode('<b>'); // '&lt;b&gt;'\n```\n\n### U.decode(value)\n\nType: `method`\n\nDekóduje HTML entity späť na znaky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `String`\n\nOpak `U.encode()`. `null` a `undefined` dajú prázdny reťazec.\n\nExample: Čistý text\n```js\nU.decode('&lt;b&gt;'); // '<b>'\n```\n\n### U.btoa(value)\n\nType: `method`\n\nZakóduje reťazec alebo Buffer do Base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Hodnota. |\n\nReturns: `String`\n\n`U.atob(value)` dekóduje Base64 späť na UTF-8 reťazec.\n\nExample: Base64\n```js\nvar encoded = U.btoa('hi'); // 'aGk='\nvar text = U.atob(encoded); // 'hi'\n```\n\n### U.parseXML(xml, [replace])\n\nType: `method`\n\nSpracuje XML do plochého objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `xml` | `String` | yes |  | XML. |\n| `replace` | `Boolean` | no | `false` | Nahradí špeciálne znaky v kľúčoch. |\n\nReturns: `Object`\n\nKaždý kľúč je cesta elementu spojená bodkami, napríklad `root.item`; opakované elementy dajú pole hodnôt. Atribúty sa ukladajú pod kľúčom s `[]`, napríklad `root.item[]`. S `replace` nastaveným na `true` sa znaky `[`, `]`, `:`, `.` a `_` v kľúčoch zmenia na `_`. CDATA sa číta ako text.\n\nExample: Čítanie XML\n```js\nvar obj = U.parseXML('<root><item id=\"1\">A</item><item>B</item></root>');\n// { 'root.item[]': { id: '1' }, 'root.item': ['A', 'B'] }\n```\n\n### U.parseInt(value, [def])\n\nType: `method`\n\nPrevedie ľubovoľnú hodnotu na celé číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `def` | `Number` | no | `0` | Hodnota pre prázdny alebo neplatný vstup. |\n\nReturns: `Number`\n\n`null`, `undefined` a prázdny reťazec dajú `def`. Číslo sa vráti tak, ako je. `U.parseFloat(value, [def])` a `U.parseBoolean(value, [def])` fungujú rovnako pre desatinné čísla a booleany (`def` je pre booleany `false`; číslo je `true`, keď je väčšie ako 0).\n\nExample: Hodnoty z query\n```js\nvar page = U.parseInt(this.query.page, 1);\nvar price = U.parseFloat(this.query.price);\nvar active = U.parseBoolean(this.query.active);\n```\n\n### U.distance(lat1, lon1, lat2, lon2)\n\nType: `method`\n\nVráti vzdialenosť medzi dvoma GPS súradnicami v kilometroch.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `lat1` | `Number` | yes |  | Zemepisná šírka prvého bodu. |\n| `lon1` | `Number` | yes |  | Zemepisná dĺžka prvého bodu. |\n| `lat2` | `Number` | yes |  | Zemepisná šírka druhého bodu. |\n| `lon2` | `Number` | yes |  | Zemepisná dĺžka druhého bodu. |\n\nReturns: `Number` Kilometre.\n\nPoužíva haversinový vzorec na guli s polomerom 6371 km; výsledok má najviac 3 desatinné miesta.\n\nExample: Bratislava – Praha\n```js\nU.distance(48.1486, 17.1077, 50.0755, 14.4378); // 289.225\n```\n\n### U.minify_css(value)\n\nType: `method`\n\nMinifikuje CSS vstavaným kompilátorom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | CSS kód. |\n\nReturns: `String`\n\nTen istý kompilátor, ktorý framework používa pre statické súbory `.css`.\n\nExample: Minifikácia\n```js\nU.minify_css('a { color: red; }'); // 'a{color:red}'\n```\n\n### U.minify_js(value)\n\nType: `method`\n\nMinifikuje JavaScript vstavaným kompilátorom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | JavaScript kód. |\n\nReturns: `String`\n\nOdstráni komentáre a biele znaky. Ten istý kompilátor, ktorý framework používa pre statické súbory `.js`.\n\nExample: Minifikácia\n```js\nU.minify_js('var a = 1;  // note');\n```\n\n### U.minify_html(value)\n\nType: `method`\n\nMinifikuje HTML vstavaným kompilátorom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML kód. |\n\nReturns: `String`\n\nOdstráni biele znaky medzi tagmi.\n\nExample: Minifikácia\n```js\nU.minify_html('<div>  <b>x</b>  </div>'); // '<div><b>x</b></div>'\n```\n\n### STATUS(id, data, [timeout])\n\nType: `method` · Since: `0.0.63`\n\nUloží pomenovaný stav tvojej aplikácie a odovzdá ho do `DEF.onStatus(meta)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Object` | yes |  | Názov stavu, alebo objekt `$`. |\n| `data` | `Object` | yes |  | Ľubovoľná hodnota. |\n| `timeout` | `Number` | no |  | Oneskorí aktualizáciu a zlúči volania počas tohto času, v milisekundách. |\n\nReturns: `undefined` Nič.\n\nKaždé `id` má jeden objekt stavu `{ id, data, date }`. `STATUS()` nahradí jeho `data`, nastaví `date` a zavolá `DEF.onStatus(meta)`, keď ho definuješ. Namiesto `id` môžeš odovzdať objekt `$`; jeho `ID` (alebo `name`) je id.\n\nS `timeout` (v milisekundách) sa aktualizácia oneskorí: prvé volanie spustí časovač, neskoršie volania iba menia `data` a `DEF.onStatus()` sa spustí raz s poslednými dátami, keď časovač skončí. Použi to pre hodnoty, ktoré sa často menia, napríklad priebeh.\n\nS `CONF.allow_stats_status` (predvolene `true`) sa všetky stavy pridajú ako `status` do snapshotu štatistík, ktorý Total.js zapisuje do `<main script>.json` (`CONF.allow_stats_snapshot`).\n\nExample: Priebeh importu\n```js\nDEF.onStatus = function(meta) {\n\tconsole.log(meta.id, meta.data, meta.date);\n};\n\nfor (var i = 0; i < items.length; i++)\n\tSTATUS('import', { done: i + 1, total: items.length }, 1000);\n```\n\n### U.encrypt_data(value, key, [encode])\n\nType: `method`\n\nZašifruje reťazec kľúčom a náhodnou maskou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Text na zašifrovanie. |\n| `key` | `String` | yes |  | Kľúč. |\n| `encode` | `String` | no | `base64` | Kódovanie Buffera alebo `buffer`. |\n\nReturns: `String|Buffer` Zašifrovaná hodnota.\n\nVýstup sa mení pri každom volaní kvôli náhodnej 4-bajtovej maske. `encode` je kódovanie Buffera (predvolene `base64`); `buffer` vráti surový Buffer. Späť ho prečítaš cez `U.decrypt_data()` s rovnakým kľúčom. Je to ľahká obfuskácia, nie náhrada za `U.encrypt_crypto()`.\n\nExample: Zašifrovanie JSON reťazca\n```js\nvar token = U.encrypt_data(JSON.stringify({ id: user.id }), CONF.secret);\n```\n\n### U.decrypt_data(value, key, [encode])\n\nType: `method`\n\nDešifruje hodnotu vytvorenú cez `U.encrypt_data()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Buffer` | yes |  | Zašifrovaná hodnota. |\n| `key` | `String` | yes |  | Kľúč použitý pri šifrovaní. |\n| `encode` | `String` | no | `base64` | Kódovanie `value`. |\n\nReturns: `String` Dešifrovaný text alebo `null`.\n\n`value` je reťazec v kódovaní `encode` (predvolene `base64`) alebo Buffer. Vráti `null`, keď sa hodnota nedá prečítať. Nesprávny kľúč dá nesprávny reťazec, nie `null`, preto výsledok skontroluj (napríklad cez `parseJSON()`).\n\nExample: Dešifrovanie tokenu\n```js\nvar data = (U.decrypt_data(token, CONF.secret) || '').parseJSON();\nif (!data)\n\treturn $.invalid(401);\n```\n\n### U.encrypt_crypto(type, key, value)\n\nType: `method`\n\nZašifruje dáta šifrou Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov šifry, napríklad `aes-256-cbc`. |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `String|Buffer` | yes |  | Dáta. |\n\nReturns: `Buffer` Zašifrované dáta.\n\nPoužíva `Crypto.createCipheriv(type, key, CONF.default_crypto_iv)`. Dĺžka kľúča musí zodpovedať šifre (32 znakov pre `aes-256-cbc`). `CONF.default_crypto_iv` sa predvolene vytvára z aplikácie, preto ho nastav v konfigurácii, keď majú dáta dešifrovať iné aplikácie.\n\nExample: AES\n```js\nvar key = 'a6e4c7d1b9f2038e5a7c1d4b6e8f0a2c';\nvar buffer = U.encrypt_crypto('aes-256-cbc', key, 'Hello');\nvar text = buffer.toString('base64');\n```\n\n### U.decrypt_crypto(type, key, value)\n\nType: `method`\n\nDešifruje dáta vytvorené cez `U.encrypt_crypto()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov šifry. |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `Buffer` | yes |  | Zašifrované dáta. |\n\nReturns: `Buffer` Dešifrované dáta alebo `undefined`.\n\nPoužíva `Crypto.createDecipheriv(type, key, CONF.default_crypto_iv)`. Vráti `undefined`, keď sa dáta nedajú dešifrovať.\n\nExample: AES\n```js\nvar buffer = U.decrypt_crypto('aes-256-cbc', key, Buffer.from(text, 'base64'));\nbuffer && console.log(buffer.toString('utf8'));\n```\n\n### U.convert62(number)\n\nType: `method` · Since: `0.0.85`\n\nPrevedie číslo na reťazec v sústave 62.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `number` | `Number` | yes |  | Kladné číslo. |\n\nReturns: `String`\n\nAbecedu tvoria číslice, potom veľké a malé písmená. Desatinné miesta sa zaokrúhlia nadol. Späť ho prečítaš cez `U.from62()`.\n\nExample: Krátky kód\n```js\nU.convert62(123456789); // '8M0kX'\n```\n\n### U.from62(value)\n\nType: `method` · Since: `0.0.85`\n\nPrevedie reťazec v sústave 62 z `U.convert62()` späť na číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Reťazec v sústave 62. |\n\nReturns: `Number`\n\nExample: Späť na číslo\n```js\nU.from62(U.convert62(1000)); // 1000\n```\n\n### U.groupify(id, [count])\n\nType: `method` · Since: `0.0.88`\n\nVráti číselnú skupinu pevnej dĺžky pre identifikátor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identifikátor. |\n| `count` | `Number` | no | `4` | Počet číslic. |\n\nReturns: `String` Reťazec číslic.\n\nHodnota je `HASH(id, true)` modulo `10^count`, doplnená nulami na `count` číslic. Rovnaké id dá vždy rovnakú skupinu, takže je to užitočné na rozdelenie súborov do podadresárov.\n\nExample: Podadresáre\n```js\nvar id = UID();\nvar filename = PATH.databases('files/' + U.groupify(id) + '/' + id + '.json');\n```\n\n### U.parseBoolean(value, [def])\n\nType: `method`\n\nPrevedie ľubovoľnú hodnotu na boolean.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `def` | `Boolean` | no | `false` | Predvolená hodnota. |\n\nReturns: `Boolean`\n\nBoolean sa vráti tak, ako je, číslo je `true`, keď je väčšie ako `0`, iné hodnoty sa prevedú na reťazec a spracujú cez `String.parseBoolean()`. `null` a `undefined` vrátia `def`.\n\nExample: Hodnota z query\n```js\nvar active = U.parseBoolean($.query.active);\n```\n\n### U.parseFloat(value, [def])\n\nType: `method`\n\nPrevedie ľubovoľnú hodnotu na desatinné číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `def` | `Number` | no | `0` | Predvolená hodnota. |\n\nReturns: `Number`\n\nČíslo sa vráti tak, ako je, iné hodnoty sa prevedú na reťazec a spracujú cez `String.parseFloat()`. `null`, `undefined` a prázdny reťazec vrátia `def`.\n\nExample: Cena\n```js\nvar price = U.parseFloat(model.price, 0);\n```\n\n### U.isDate(value)\n\nType: `method`\n\nSkontroluje, či je hodnota platný `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `Boolean`\n\nVráti `false` pre neplatný dátum ako `new Date('abc')`.\n\nExample: Validácia dátumu\n```js\nU.isDate(new Date()); // true\nU.isDate(new Date('abc')); // false\nU.isDate('2024-01-01'); // false\n```\n\n### U.DAYS\n\nType: `property`\n\nAnglické názvy dní v týždni.\n\nReturns: `String Array`\n\nPole začína `Sunday`, takže zodpovedá `Date.getDay()`.\n\nExample: Názov dňa\n```js\nvar name = U.DAYS[new Date().getDay()];\n```\n\n### U.MONTHS\n\nType: `property`\n\nAnglické názvy mesiacov.\n\nReturns: `String Array`\n\nPole začína `January`, takže zodpovedá `Date.getMonth()`.\n\nExample: Názov mesiaca\n```js\nvar name = U.MONTHS[new Date().getMonth()];\n```\n\n### U.httpstatus(code, [addCode])\n\nType: `method`\n\nVráti text HTTP stavového kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | yes |  | HTTP stavový kód. |\n| `addCode` | `Boolean` | no | `true` | Pridá kód k textu. |\n\nReturns: `String`\n\nText pochádza z `http.STATUS_CODES`. S `addCode` (predvolene `true`) sa kód pridá na začiatok.\n\nExample: Text stavu\n```js\nU.httpstatus(404); // '404: Not Found'\nU.httpstatus(404, false); // 'Not Found'\n```\n\n### U.toURLEncode(obj)\n\nType: `method`\n\nSerializuje objekt do URL-kódovaného query stringu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt. |\n\nReturns: `String` Napríklad `q=total&page=2`.\n\nReťazce sa zakódujú cez `encodeURIComponent()`, čísla a booleany sa pridajú tak, ako sú, polia sa spoja cez `,`. `null`, `undefined`, prázdne reťazce a iné objekty (vrátane dátumov) sa preskočia. Vráti prázdny reťazec, keď sa nič nepridá.\n\nExample: Query string\n```js\nvar url = 'https://example.com/api/?' + U.toURLEncode({ q: 'total js', page: 2, tags: ['a', 'b'] });\n// q=total%20js&page=2&tags=a%2Cb\n```\n\n### U.atob(value)\n\nType: `method`\n\nDekóduje base64 reťazec na UTF-8 reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Base64 reťazec. |\n\nReturns: `String`\n\nOpak `U.btoa()`.\n\nExample: Dekódovanie\n```js\nU.atob(U.btoa('Hello')); // 'Hello'\n```\n\n### U.isrelative(url)\n\nType: `method`\n\nSkontroluje, či je URL relatívna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n\nReturns: `Boolean`\n\nVráti `false`, keď URL začína `//` alebo obsahuje `http://` či `https://`.\n\nExample: Bezpečné presmerovanie\n```js\nvar url = $.query.redirect || '/';\nif (!U.isrelative(url))\n\turl = '/';\n$.redirect(url);\n```\n\n### U.isStaticFile(url)\n\nType: `method`\n\nSkontroluje, či URL vyzerá ako súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cesta URL. |\n\nReturns: `Boolean`\n\nVráti `true`, keď posledných 8 znakov URL obsahuje bodku, napríklad `/img/logo.png`.\n\nExample: Súbor alebo routa\n```js\nU.isStaticFile('/img/logo.png'); // true\nU.isStaticFile('/api/users/'); // false\n```\n\n### U.resolve(url, [callback], [param])\n\nType: `method`\n\nZistí IPv4 adresu URL a uloží ju do cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL. |\n| `callback` | `Function` | no |  | `function(err, uri, param, addresses)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná callbacku. |\n\nReturns: `Array|undefined` Adresy z cache, keď nie je zadaný callback.\n\n`callback(err, uri, param, addresses)` dostane spracovanú URL s `uri.host` nahradeným prvou adresou. Adresy sa ukladajú do cache pre každý host; bez callbacku metóda vráti adresy z cache (alebo `undefined`). Neúspešné vyhľadanie sa skúsi ešte raz. Príkaz `clear_dnscache` vymaže cache.\n\nExample: DNS vyhľadanie\n```js\nU.resolve('https://www.totaljs.com', function(err, uri, param, addresses) {\n\tconsole.log(err, addresses);\n});\n```\n\n### U.link(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nSpojí časti URL s presne jednou `/` medzi nimi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Jedna alebo viac častí URL. |\n\nReturns: `String`\n\nNa rozdiel od `U.join()` nepridáva úvodnú `/` a časti ponechá tak, ako sú.\n\nExample: Zostavenie URL\n```js\nU.link('https://example.com/', '/api/', 'users'); // 'https://example.com/api/users'\n```\n\n### U.normalize(path)\n\nType: `method` · Since: `0.0.39`\n\nPridá `/` na začiatok a koniec cesty, keď chýba.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta. |\n\nReturns: `String`\n\nExample: Normalizácia\n```js\nU.normalize('admin'); // '/admin/'\n```\n\n### U.path(path, [delimiter])\n\nType: `method`\n\nPridá ku ceste koncový oddeľovač, keď chýba.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta. |\n| `delimiter` | `String` | no | `/` | Oddeľovač. |\n\nReturns: `String`\n\nPrázdna cesta vráti oddeľovač.\n\nExample: Cesta k adresáru\n```js\nU.path('/www/app'); // '/www/app/'\n```\n\n### U.getExtensionFromContentType(contentType)\n\nType: `method` · Since: `0.0.63`\n\nVráti príponu súboru pre content type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `contentType` | `String` | yes |  | Content type. |\n\nReturns: `String`\n\nPrehľadá content typy známe pre `U.getContentType()` (vrátane tých pridaných cez `U.setContentType()`). Vráti prvú zhodu bez bodky, alebo `undefined`.\n\nExample: Prípona\n```js\nU.getExtensionFromContentType('image/png'); // 'png'\n```\n\n### U.ObjectToArray(obj)\n\nType: `method`\n\nPrevedie objekt na pole položiek `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt. |\n\nReturns: `Array`\n\n`null` alebo `undefined` vráti `EMPTYARRAY`.\n\nExample: Zoznam kľúč-hodnota\n```js\nU.ObjectToArray({ a: 1, b: 2 }); // [{ key: 'a', value: 1 }, { key: 'b', value: 2 }]\n```\n\n### U.createBuffer([value], [encoding])\n\nType: `method`\n\nSkratka pre `Buffer.from(value || '', encoding)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Array|Buffer` | no | `''` | Dáta. |\n| `encoding` | `String` | no | `utf8` | Kódovanie reťazca. |\n\nReturns: `Buffer`\n\nExample: Z base64\n```js\nvar buffer = U.createBuffer(body, 'base64');\n```\n\n### U.createBufferSize([size])\n\nType: `method`\n\nSkratka pre `Buffer.alloc(size || 0)`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `size` | `Number` | no | `0` | Veľkosť v bajtoch. |\n\nReturns: `Buffer` Buffer vyplnený nulami.\n\nExample: Prázdny buffer\n```js\nvar buffer = U.createBufferSize(4);\nbuffer.writeInt32BE(100);\n```\n\n### U.json2replacer(key, value)\n\nType: `method`\n\nReplacer pre `JSON.stringify()`, ktorý odstraňuje hodnoty `null` a `undefined`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč. |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `Object`\n\nExample: Menší JSON\n```js\nJSON.stringify({ id: 1, name: null }, U.json2replacer); // '{\"id\":1}'\n```\n\n### U.queuecache\n\nType: `property`\n\nStav front vytvorených cez `U.queue()`.\n\nReturns: `Object`\n\nObjekt s kľúčmi podľa názvu fronty. Každá položka má `limit`, `running` a `pending` (čakajúce callbacky). Čítaj ho iba na monitorovanie.\n\nExample: Čakajúce položky\n```js\nvar item = U.queuecache.import;\nitem && console.log(item.running, item.pending.length);\n```\n\n### new U.EventEmitter2([obj])\n\nType: `class`\n\nMalý emitor udalostí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | no |  | Objekt na rozšírenie. |\n\nReturns: `EventEmitter2`\n\n`new U.EventEmitter2()` vytvorí emitor. `U.EventEmitter2(obj)` (bez `new`) pridá `emit()`, `on()`, `once()`, `off()`, `removeListener()` a `removeAllListeners()` do existujúceho objektu a vráti ho; `U.EventEmitter2.extend(obj)` robí to isté. Listenery sa uchovávajú v `$events`. `emit()` odovzdá najviac 7 argumentov a `this` je emitor.\n\nExample: Rozšírenie objektu\n```js\nvar service = {};\nU.EventEmitter2(service);\nservice.on('ready', function(value) {\n\tconsole.log('ready', value);\n});\nservice.emit('ready', 1);\n```\n\n### emitter.off(name, [fn])\n\nType: `method` · Since: `0.0.90`\n\nOdstráni listener alebo všetky listenery udalosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti. |\n| `fn` | `Function` | no |  | Listener. |\n\nReturns: `EventEmitter2` Emitor.\n\nBez `fn` sa odstránia všetky listenery `name`. `removeListener()` je alias. `removeAllListeners([name])` odstráni listenery jednej udalosti alebo všetkých udalostí.\n\nExample: Odstránenie listenera\n```js\nvar fn = function() {};\nemitter.on('change', fn);\nemitter.off('change', fn);\n```\n\n### U.Callback(count, [callback])\n\nType: `method`\n\nZavolá callback po tom, čo bolo `next()` zavolané `count` krát.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Na koľko volaní `next()` sa čaká. |\n| `callback` | `Function` | no |  | Funkcia na zavolanie. |\n\nReturns: `Callback` Inštancia s `next()` a `done(fn)`.\n\nVráti inštanciu s `next()` a `done(callback)`. Callback sa spustí raz, keď počet čakajúcich dosiahne nulu. Trieda je dostupná aj ako globálny `Callback`.\n\nExample: Čakanie na 3 úlohy\n```js\nvar cb = U.Callback(3, function() {\n\tconsole.log('all done');\n});\n\nfor (var i = 0; i < 3; i++)\n\tsetTimeout(() => cb.next(), 100 * i);\n```\n\n### U.chunker(name, [max])\n\nType: `method`\n\nUkladá veľa položiek do dočasných súborov, stránku po stránke.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Unikátny názov, použitý v názvoch súborov. |\n| `max` | `Number` | no | `50` | Počet položiek na súbor. |\n\nReturns: `Chunker`\n\nKaždých `max` položiek zapísaných cez `write()` ide do jedného súboru `{name}-{index}.chunker` v dočasnom adresári, skomprimovaného cez deflate. Späť ich prečítaš stránku po stránke cez `each()` alebo `read()`. Vlastnosti: `compress` (predvolene `true`), `autoremove` (predvolene `true`, odstráni každý súbor po prečítaní), `count`, `pages` a `percentage` (priebeh `each()`). Trieda je dostupná ako `U.Chunker`.\n\nExample: Export po stránkach\n```js\nvar chunker = U.chunker('export', 100);\n\nfor (var item of items)\n\tchunker.write(item);\n\nchunker.end();\n\nchunker.each(function(items, next, index) {\n\tconsole.log('page', index, items.length);\n\tnext();\n}, function() {\n\tconsole.log('done');\n});\n```\n\n### chunker.write(item)\n\nType: `method`\n\nPridá položku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Object` | yes |  | Položka, ktorú možno serializovať do JSON. |\n\nReturns: `Chunker`\n\nKeď čaká `max` položiek, zapíšu sa do nového súboru. `append()` je alias. Po poslednej položke zavolaj `end()`.\n\nExample: Zápis\n```js\nchunker.write({ id: 1, name: 'Peter' });\n```\n\n### chunker.end()\n\nType: `method`\n\nZapíše zostávajúce položky do posledného súboru.\n\nReturns: `Chunker`\n\nExample: Dokončenie zápisu\n```js\nchunker.end();\n```\n\n### chunker.each(onItem, [onEnd])\n\nType: `method`\n\nPrečíta všetky stránky jednu po druhej.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | `function(items, next, index)`. |\n| `onEnd` | `Function` | no |  | Spustí sa po poslednej stránke. |\n\nReturns: `Chunker`\n\n`onItem(items, next, index)` dostane položky jednej stránky; zavolaj `next()` na prečítanie ďalšej stránky. `onEnd()` sa spustí po poslednej stránke. `percentage` ukazuje priebeh.\n\nExample: Spracovanie stránok\n```js\nchunker.each(function(items, next) {\n\titems.wait(save, next);\n}, () => console.log('done'));\n```\n\n### chunker.read(index, callback)\n\nType: `method`\n\nPrečíta jednu stránku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | Index stránky od `0`. |\n| `callback` | `Function` | yes |  | `function(err, items)`. |\n\nReturns: `Chunker`\n\n`callback(err, items)` dostane položky stránky, alebo prázdne pole, keď súbor neexistuje. Čaká, kým sa súbory ešte zapisujú.\n\nExample: Prvá stránka\n```js\nchunker.read(0, function(err, items) {\n\tconsole.log(items);\n});\n```\n\n### chunker.clear()\n\nType: `method`\n\nOdstráni všetky súbory chunkera.\n\nReturns: `Chunker`\n\n`destroy()` tiež odstráni súbory a uvoľní inštanciu.\n\nExample: Upratanie\n```js\nchunker.clear();\n```\n\n### U.reader([items])\n\nType: `method`\n\nDotazuje pole objektov pomocou NoSQL query buildera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|String` | no |  | Položky alebo URL. |\n\nReturns: `Reader`\n\n`items` je pole (alebo jeden objekt), alebo URL obsahu TextDB, ktorý sa stiahne a streamuje. Bez `items` pridávaj dáta cez `reader.push(items)` a ukonči cez `reader.push(null)`, alebo použi `reader.stream(stream)`. `find()`, `list()`, `read()`, `count()`, `scalar(type, key, [key2])` a `stats(groupfield, datefield, key, [type])` vracajú NoSQL query builder (`where()`, `sort()`, `take()`, `callback()`...). `list()` vracia `{ page, pages, limit, count, items }`. `assign(data)` vytvorí dotaz zo serializovaného objektu dotazu.\n\nExample: Filtrovanie poľa\n```js\nvar reader = U.reader(users);\n\nreader.find().where('age', '>', 18).sort('name').take(10).callback(function(err, response) {\n\tconsole.log(response);\n});\n\nreader.count().callback(function(err, response) {\n\tconsole.log(response);\n});\n```\n\n### reader.push(items)\n\nType: `method`\n\nPridá položky do readera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `items` | `Array|Object|null` | yes |  | Dáta, alebo `null` na konci. |\n\nReturns: `undefined`\n\nOdovzdaj pole alebo jeden objekt pre každú časť dát, potom `null` na ukončenie a získanie výsledkov.\n\nExample: Vloženie dát\n```js\nvar reader = U.reader();\nreader.find().where('active', true).callback(console.log);\nreader.push(page1);\nreader.push(page2);\nreader.push(null);\n```\n\n### U.streamer(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nRozdelí stream častí na kúsky podľa oddeľovačov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Oddeľovač alebo začiatok kúsku. |\n| `end` | `String|Buffer` | no |  | Koniec kúsku. |\n| `callback` | `Function` | yes |  | `function(value, index)`. |\n| `skip` | `Number` | no | `0` | Počet kúskov na preskočenie. |\n| `stream` | `Stream` | no |  | Stream pre udalosť `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nVráti `function(chunk)`, ktorej odovzdáš každú časť. Bez `end` každý kúsok končí `beg` (a obsahuje ho), napríklad riadok končiaci `\\n`. S `end` každý kúsok začína `beg` a končí `end`. `callback(value, index)` dostane každý kúsok ako reťazec; vráť `false` na zastavenie. `skip` preskočí prvé kúsky. So `stream` sa zostávajúce dáta spracujú pri udalosti `end` streamu. `U.streamer2()` je to isté, ale dáva Buffery.\n\nExample: Čítanie riadkov\n```js\nvar stream = F.Fs.createReadStream(PATH.databases('log.txt'));\nstream.on('data', U.streamer('\\n', function(line, index) {\n\tconsole.log(index, line.trim());\n}, stream));\n```\n\n### U.streamer2(beg, [end], callback, [skip], [stream])\n\nType: `method`\n\nTo isté ako `U.streamer()`, ale kúsky sú Buffery.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String|Buffer` | yes |  | Oddeľovač alebo začiatok kúsku. |\n| `end` | `String|Buffer` | no |  | Koniec kúsku. |\n| `callback` | `Function` | yes |  | `function(buffer, index)`. |\n| `skip` | `Number` | no | `0` | Počet kúskov na preskočenie. |\n| `stream` | `Stream` | no |  | Stream pre udalosť `end`. |\n\nReturns: `Function` `function(chunk)`.\n\nExample: Binárne kúsky\n```js\nstream.on('data', U.streamer2('<item>', '</item>', function(buffer) {\n\tconsole.log(buffer.length);\n}));\n```\n\n### U.filestreamer(filename)\n\nType: `method` · Since: `0.0.59`\n\nČíta textový súbor riadok po riadku v dávkach.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor. |\n\nReturns: `Object` Stream reader.\n\nVráti stream reader TextDB. Nastav `ondocuments` (volá sa s `this.docs`, riadkami jednej dávky spojenými cez `,`; vráť `false` na zastavenie) a `$callback` (volá sa na konci), potom zavolaj `openread()`. Nastav `array = true`, aby si dostal `docs` ako pole riadkov. Riadky, ktoré začínajú `-`, sa preskočia.\n\nExample: Čítanie súboru JSON-lines\n```js\nvar reader = U.filestreamer(PATH.databases('items.nosql'));\nreader.ondocuments = function() {\n\tvar items = JSON.parse('[' + reader.docs + ']');\n\tconsole.log(items.length);\n};\nreader.$callback = () => console.log('done');\nreader.openread();\n```\n\n### PATH.join(path1, [path2], [...])\n\nType: `method` · Since: `0.0.39`\n\nAlias pre `path.join()` z Node.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Jedna alebo viac častí cesty. |\n\nReturns: `String`\n\nExample: Spojenie\n```js\nvar filename = PATH.join(PATH.root(), 'data', 'file.json');\n```\n\n### PATH.exists(path, callback)\n\nType: `method`\n\nSkontroluje, či súbor alebo adresár existuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta. |\n| `callback` | `Function` | yes |  | `function(exists, size, isFile)`. |\n\nReturns: `undefined`\n\n`callback(exists, size, isFile)`.\n\nExample: Kontrola súboru\n```js\nPATH.exists(PATH.public('robots.txt'), function(exists, size, isFile) {\n\tconsole.log(exists, size, isFile);\n});\n```\n\n### PATH.verify(name)\n\nType: `method`\n\nVytvorí adresár aplikácie, ak neexistuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov adresára. |\n\nReturns: `undefined`\n\n`name` je názov nastavenia `CONF.directory_{name}`, napríklad `databases`. Kontrola prebehne raz pre každý názov.\n\nExample: Zabezpečenie existencie adresára\n```js\nPATH.verify('private');\n```\n\n### PATH.ls(path, [callback], [filter], [unified])\n\nType: `method`\n\nAlias pre `U.ls()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Adresár. |\n| `callback` | `Function` | no |  | `function(files, directories)`. |\n\nReturns: `Promise|undefined`\n\n`PATH.ls2()` je alias pre `U.ls2()`.\n\nExample: Výpis súborov\n```js\nPATH.ls(PATH.private(), function(files) {\n\tconsole.log(files);\n});\n```\n\n### PATH.unlink(files, [callback])\n\nType: `method`\n\nOdstráni súbory jeden po druhom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `files` | `String|String Array` | yes |  | Súbory. |\n| `callback` | `Function` | no |  | Spustí sa na konci. |\n\nReturns: `undefined`\n\nChyby sa ignorujú.\n\nExample: Odstránenie súborov\n```js\nPATH.unlink([PATH.temp('a.tmp'), PATH.temp('b.tmp')], () => console.log('removed'));\n```\n\n### PATH.rmdir(directories, [callback])\n\nType: `method`\n\nOdstráni adresáre s celým ich obsahom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directories` | `String|String Array` | yes |  | Adresáre. |\n| `callback` | `Function` | no |  | Spustí sa na konci. |\n\nReturns: `undefined`\n\nChyby sa ignorujú.\n\nExample: Odstránenie adresára\n```js\nPATH.rmdir(PATH.temp('import'), () => console.log('removed'));\n```\n\n### PATH.private([filename])\n\nType: `method`\n\nVráti cestu v adresári private.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_private` (predvolene `/private/`).\n\nExample: Cesta\n```js\nvar filename = PATH.private('data.json');\n```\n\n### PATH.models([filename])\n\nType: `method`\n\nVráti cestu v adresári models.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_models` (predvolene `/models/`).\n\nExample: Cesta\n```js\nvar filename = PATH.models('file.js');\n```\n\n### PATH.builds([filename])\n\nType: `method`\n\nVráti cestu v adresári builds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_builds` (predvolene `/builds/`).\n\nExample: Cesta\n```js\nvar filename = PATH.builds('file.js');\n```\n\n### PATH.views([filename])\n\nType: `method`\n\nVráti cestu v adresári views.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_views` (predvolene `/views/`).\n\nExample: Cesta\n```js\nvar filename = PATH.views('index.html');\n```\n\n### PATH.updates([filename])\n\nType: `method`\n\nVráti cestu v adresári updates.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_updates` (predvolene `/updates/`).\n\nExample: Cesta\n```js\nvar filename = PATH.updates('file.js');\n```\n\n### PATH.modules([filename])\n\nType: `method`\n\nVráti cestu v adresári modules.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_modules` (predvolene `/modules/`).\n\nExample: Cesta\n```js\nvar filename = PATH.modules('file.js');\n```\n\n### PATH.schemas([filename])\n\nType: `method`\n\nVráti cestu v adresári schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_schemas` (predvolene `/schemas/`).\n\nExample: Cesta\n```js\nvar filename = PATH.schemas('file.js');\n```\n\n### PATH.extensions([filename])\n\nType: `method`\n\nVráti cestu v adresári extensions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_extensions` (predvolene `/extensions/`).\n\nExample: Cesta\n```js\nvar filename = PATH.extensions('file.js');\n```\n\n### PATH.operations([filename])\n\nType: `method`\n\nVráti cestu v adresári operations.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_operations` (predvolene `/operations/`).\n\nExample: Cesta\n```js\nvar filename = PATH.operations('file.js');\n```\n\n### PATH.tasks([filename])\n\nType: `method`\n\nVráti cestu v adresári tasks.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_tasks` (predvolene `/tasks/`).\n\nExample: Cesta\n```js\nvar filename = PATH.tasks('file.js');\n```\n\n### PATH.controllers([filename])\n\nType: `method`\n\nVráti cestu v adresári controllers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_controllers` (predvolene `/controllers/`).\n\nExample: Cesta\n```js\nvar filename = PATH.controllers('file.js');\n```\n\n### PATH.definitions([filename])\n\nType: `method`\n\nVráti cestu v adresári definitions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_definitions` (predvolene `/definitions/`).\n\nExample: Cesta\n```js\nvar filename = PATH.definitions('file.js');\n```\n\n### PATH.tests([filename])\n\nType: `method`\n\nVráti cestu v adresári tests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_tests` (predvolene `/tests/`).\n\nExample: Cesta\n```js\nvar filename = PATH.tests('file.js');\n```\n\n### PATH.services([filename])\n\nType: `method`\n\nVráti cestu v adresári services.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_services` (predvolene `/services/`).\n\nExample: Cesta\n```js\nvar filename = PATH.services('file.js');\n```\n\n### PATH.packages([filename])\n\nType: `method`\n\nVráti cestu v adresári packages.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_packages` (predvolene `/packages/`).\n\nExample: Cesta\n```js\nvar filename = PATH.packages('file.js');\n```\n\n### PATH.themes([filename])\n\nType: `method`\n\nVráti cestu v adresári themes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_themes` (predvolene `/themes/`).\n\nExample: Cesta\n```js\nvar filename = PATH.themes('default/index.html');\n```\n\n### PATH.components([filename])\n\nType: `method`\n\nVráti cestu v adresári components.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_components` (predvolene `/components/`).\n\nExample: Cesta\n```js\nvar filename = PATH.components('file.js');\n```\n\n### PATH.templates([filename])\n\nType: `method`\n\nVráti cestu v adresári templates.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_templates` (predvolene `/templates/`).\n\nExample: Cesta\n```js\nvar filename = PATH.templates('email.html');\n```\n\n### PATH.plugins([filename])\n\nType: `method` · Since: `0.0.88`\n\nVráti cestu v adresári plugins.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_plugins` (predvolene `/plugins/`).\n\nExample: Cesta\n```js\nvar filename = PATH.plugins('file.js');\n```\n\n### PATH.flowstreams([filename])\n\nType: `method`\n\nVráti cestu v adresári flowstreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru. |\n\nReturns: `String` Absolútna cesta.\n\nAdresár je `CONF.directory_flowstreams` (predvolene `/flowstreams/`).\n\nExample: Cesta\n```js\nvar filename = PATH.flowstreams('file.js');\n```\n\n### OBSOLETE(name, message)\n\nType: `method`\n\nVypíše varovanie o zastaranom kóde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Čo je zastarané. |\n| `message` | `String` | yes |  | Čo použiť namiesto toho. |\n\nZapíše dátum, názov a správu do konzoly a zvýši `F.stats.other.obsolete`. Nič sa nevypíše, keď je `CONF.nowarnings` `true` (framework ho nastaví, keď watcher reštartuje aplikáciu s `--restart`).\n\nExample: Varovanie\n```js\nfunction oldsave(model) {\n\tOBSOLETE('oldsave()', 'Use save() instead.');\n\treturn save(model);\n}\n```\n\n### UID1([type], [date])\n\nType: `method`\n\nVygeneruje jedinečný identifikátor s desiatkovou časovou časťou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | Názov samostatného počítadla. |\n| `date` | `Date` | no | `NOW` | Čas identifikátora. |\n\nReturns: `String` Identifikátor.\n\nAko `UID()`, ale časová časť je počet minút od 2020-01-31 23:00 UTC zapísaný desiatkovými číslicami. Identifikátory končia písmenom verzie `b`. S `type` má každý typ vlastné počítadlo. `date` vytvorí identifikátor pre iný čas.\n\nExample: Identifikátor\n```js\nvar id = UID1();\nvar orderid = UID1('orders');\n```\n","entries":[{"type":"property","name":"U","signature":"U","since":"","deprecated":false},{"type":"property","name":"Total","signature":"Total","since":"0.0.96","deprecated":false},{"type":"property","name":"NOW","signature":"NOW","since":"","deprecated":false},{"type":"property","name":"EMPTYOBJECT","signature":"EMPTYOBJECT","since":"","deprecated":false},{"type":"property","name":"EMPTYARRAY","signature":"EMPTYARRAY","since":"","deprecated":false},{"type":"method","name":"NOOP()","signature":"NOOP()","since":"","deprecated":false},{"type":"property","name":"MAIN","signature":"MAIN","since":"","deprecated":false},{"type":"property","name":"REPO","signature":"REPO","since":"","deprecated":false},{"type":"property","name":"FUNC","signature":"FUNC","since":"","deprecated":false},{"type":"property","name":"TEMP","signature":"TEMP","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"method","name":"LOGGER()","signature":"LOGGER(name, value1, [value2], [...])","since":"","deprecated":false},{"type":"method","name":"PROMISIFY()","signature":"PROMISIFY(fn, [a], [b], [c])","since":"0.0.97","deprecated":false},{"type":"method","name":"WAIT()","signature":"WAIT(validator, callback, [timeout], [interval])","since":"","deprecated":false},{"type":"method","name":"UID()","signature":"UID([type], [date])","since":"","deprecated":false},{"type":"method","name":"UID16()","signature":"UID16([type], [date])","since":"","deprecated":false},{"type":"method","name":"GUID()","signature":"GUID([length])","since":"","deprecated":false},{"type":"method","name":"CLONE()","signature":"CLONE(obj, [skip], [skipFunctions])","since":"","deprecated":false},{"type":"method","name":"COPY()","signature":"COPY(source, [target])","since":"","deprecated":false},{"type":"method","name":"HASH()","signature":"HASH(value, [type])","since":"","deprecated":false},{"type":"method","name":"QUERIFY()","signature":"QUERIFY([url], obj)","since":"","deprecated":false},{"type":"method","name":"DIFFARR()","signature":"DIFFARR(prop, db, form)","since":"","deprecated":false},{"type":"method","name":"PATH.root()","signature":"PATH.root([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.temp()","signature":"PATH.temp([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.databases()","signature":"PATH.databases([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.logs()","signature":"PATH.logs([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.mkdir()","signature":"PATH.mkdir(path, [cache])","since":"","deprecated":false},{"type":"method","name":"U.random()","signature":"U.random([max], [min])","since":"","deprecated":false},{"type":"method","name":"U.random_text()","signature":"U.random_text(length)","since":"","deprecated":false},{"type":"method","name":"U.random_string()","signature":"U.random_string(length)","since":"","deprecated":false},{"type":"method","name":"U.random_number()","signature":"U.random_number(length)","since":"","deprecated":false},{"type":"method","name":"U.encrypt_uid()","signature":"U.encrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_uid()","signature":"U.decrypt_uid(value, [key])","since":"","deprecated":false},{"type":"method","name":"U.copy()","signature":"U.copy(source, [target])","since":"","deprecated":false},{"type":"method","name":"U.extend()","signature":"U.extend(target, source, [rewrite])","since":"","deprecated":false},{"type":"method","name":"U.reduce()","signature":"U.reduce(source, props, [reverse])","since":"","deprecated":false},{"type":"method","name":"U.get()","signature":"U.get(obj, path)","since":"","deprecated":false},{"type":"method","name":"U.set()","signature":"U.set(obj, path, value)","since":"","deprecated":false},{"type":"method","name":"U.trim()","signature":"U.trim(obj, [clean])","since":"","deprecated":false},{"type":"method","name":"U.keywords()","signature":"U.keywords(content, [forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"U.queue()","signature":"U.queue(name, max, fn, [param])","since":"","deprecated":false},{"type":"method","name":"U.sortcomparer()","signature":"U.sortcomparer(sort)","since":"","deprecated":false},{"type":"method","name":"U.combine()","signature":"U.combine(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.join()","signature":"U.join(path1, [path2], [...])","since":"","deprecated":false},{"type":"method","name":"U.getExtension()","signature":"U.getExtension(filename, [raw])","since":"","deprecated":false},{"type":"method","name":"U.getName()","signature":"U.getName(path)","since":"","deprecated":false},{"type":"method","name":"U.getContentType()","signature":"U.getContentType(ext)","since":"","deprecated":false},{"type":"method","name":"U.setContentType()","signature":"U.setContentType(ext, type)","since":"","deprecated":false},{"type":"method","name":"U.ls()","signature":"U.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.ls2()","signature":"U.ls2(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"U.encode()","signature":"U.encode(value)","since":"","deprecated":false},{"type":"method","name":"U.decode()","signature":"U.decode(value)","since":"","deprecated":false},{"type":"method","name":"U.btoa()","signature":"U.btoa(value)","since":"","deprecated":false},{"type":"method","name":"U.parseXML()","signature":"U.parseXML(xml, [replace])","since":"","deprecated":false},{"type":"method","name":"U.parseInt()","signature":"U.parseInt(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.distance()","signature":"U.distance(lat1, lon1, lat2, lon2)","since":"","deprecated":false},{"type":"method","name":"U.minify_css()","signature":"U.minify_css(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_js()","signature":"U.minify_js(value)","since":"","deprecated":false},{"type":"method","name":"U.minify_html()","signature":"U.minify_html(value)","since":"","deprecated":false},{"type":"method","name":"STATUS()","signature":"STATUS(id, data, [timeout])","since":"0.0.63","deprecated":false},{"type":"method","name":"U.encrypt_data()","signature":"U.encrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.decrypt_data()","signature":"U.decrypt_data(value, key, [encode])","since":"","deprecated":false},{"type":"method","name":"U.encrypt_crypto()","signature":"U.encrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.decrypt_crypto()","signature":"U.decrypt_crypto(type, key, value)","since":"","deprecated":false},{"type":"method","name":"U.convert62()","signature":"U.convert62(number)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.from62()","signature":"U.from62(value)","since":"0.0.85","deprecated":false},{"type":"method","name":"U.groupify()","signature":"U.groupify(id, [count])","since":"0.0.88","deprecated":false},{"type":"method","name":"U.parseBoolean()","signature":"U.parseBoolean(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.parseFloat()","signature":"U.parseFloat(value, [def])","since":"","deprecated":false},{"type":"method","name":"U.isDate()","signature":"U.isDate(value)","since":"","deprecated":false},{"type":"property","name":"U.DAYS","signature":"U.DAYS","since":"","deprecated":false},{"type":"property","name":"U.MONTHS","signature":"U.MONTHS","since":"","deprecated":false},{"type":"method","name":"U.httpstatus()","signature":"U.httpstatus(code, [addCode])","since":"","deprecated":false},{"type":"method","name":"U.toURLEncode()","signature":"U.toURLEncode(obj)","since":"","deprecated":false},{"type":"method","name":"U.atob()","signature":"U.atob(value)","since":"","deprecated":false},{"type":"method","name":"U.isrelative()","signature":"U.isrelative(url)","since":"","deprecated":false},{"type":"method","name":"U.isStaticFile()","signature":"U.isStaticFile(url)","since":"","deprecated":false},{"type":"method","name":"U.resolve()","signature":"U.resolve(url, [callback], [param])","since":"","deprecated":false},{"type":"method","name":"U.link()","signature":"U.link(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"U.normalize()","signature":"U.normalize(path)","since":"0.0.39","deprecated":false},{"type":"method","name":"U.path()","signature":"U.path(path, [delimiter])","since":"","deprecated":false},{"type":"method","name":"U.getExtensionFromContentType()","signature":"U.getExtensionFromContentType(contentType)","since":"0.0.63","deprecated":false},{"type":"method","name":"U.ObjectToArray()","signature":"U.ObjectToArray(obj)","since":"","deprecated":false},{"type":"method","name":"U.createBuffer()","signature":"U.createBuffer([value], [encoding])","since":"","deprecated":false},{"type":"method","name":"U.createBufferSize()","signature":"U.createBufferSize([size])","since":"","deprecated":false},{"type":"method","name":"U.json2replacer()","signature":"U.json2replacer(key, value)","since":"","deprecated":false},{"type":"property","name":"U.queuecache","signature":"U.queuecache","since":"","deprecated":false},{"type":"class","name":"U.EventEmitter2","signature":"new U.EventEmitter2([obj])","since":"","deprecated":false},{"type":"method","name":"eventemitter2.off()","signature":"emitter.off(name, [fn])","since":"0.0.90","deprecated":false},{"type":"method","name":"U.Callback()","signature":"U.Callback(count, [callback])","since":"","deprecated":false},{"type":"method","name":"U.chunker()","signature":"U.chunker(name, [max])","since":"","deprecated":false},{"type":"method","name":"chunker.write()","signature":"chunker.write(item)","since":"","deprecated":false},{"type":"method","name":"chunker.end()","signature":"chunker.end()","since":"","deprecated":false},{"type":"method","name":"chunker.each()","signature":"chunker.each(onItem, [onEnd])","since":"","deprecated":false},{"type":"method","name":"chunker.read()","signature":"chunker.read(index, callback)","since":"","deprecated":false},{"type":"method","name":"chunker.clear()","signature":"chunker.clear()","since":"","deprecated":false},{"type":"method","name":"U.reader()","signature":"U.reader([items])","since":"","deprecated":false},{"type":"method","name":"reader.push()","signature":"reader.push(items)","since":"","deprecated":false},{"type":"method","name":"U.streamer()","signature":"U.streamer(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.streamer2()","signature":"U.streamer2(beg, [end], callback, [skip], [stream])","since":"","deprecated":false},{"type":"method","name":"U.filestreamer()","signature":"U.filestreamer(filename)","since":"0.0.59","deprecated":false},{"type":"method","name":"PATH.join()","signature":"PATH.join(path1, [path2], [...])","since":"0.0.39","deprecated":false},{"type":"method","name":"PATH.exists()","signature":"PATH.exists(path, callback)","since":"","deprecated":false},{"type":"method","name":"PATH.verify()","signature":"PATH.verify(name)","since":"","deprecated":false},{"type":"method","name":"PATH.ls()","signature":"PATH.ls(path, [callback], [filter], [unified])","since":"","deprecated":false},{"type":"method","name":"PATH.unlink()","signature":"PATH.unlink(files, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.rmdir()","signature":"PATH.rmdir(directories, [callback])","since":"","deprecated":false},{"type":"method","name":"PATH.private()","signature":"PATH.private([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.models()","signature":"PATH.models([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.builds()","signature":"PATH.builds([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.views()","signature":"PATH.views([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.updates()","signature":"PATH.updates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.modules()","signature":"PATH.modules([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.schemas()","signature":"PATH.schemas([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.extensions()","signature":"PATH.extensions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.operations()","signature":"PATH.operations([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tasks()","signature":"PATH.tasks([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.controllers()","signature":"PATH.controllers([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.definitions()","signature":"PATH.definitions([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.tests()","signature":"PATH.tests([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.services()","signature":"PATH.services([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.packages()","signature":"PATH.packages([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.themes()","signature":"PATH.themes([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.components()","signature":"PATH.components([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.templates()","signature":"PATH.templates([filename])","since":"","deprecated":false},{"type":"method","name":"PATH.plugins()","signature":"PATH.plugins([filename])","since":"0.0.88","deprecated":false},{"type":"method","name":"PATH.flowstreams()","signature":"PATH.flowstreams([filename])","since":"","deprecated":false},{"type":"method","name":"OBSOLETE()","signature":"OBSOLETE(name, message)","since":"","deprecated":false},{"type":"method","name":"UID1()","signature":"UID1([type], [date])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Prototypes","summary":"Methods of String, Number, Date and Array added by Total.js 4.","markdown":"---\ntitle: Prototypes\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypes\n\n> Methods of String, Number, Date and Array added by Total.js 4.\n\nMethods that Total.js 4 adds to `String`, `Number`, `Date` and `Array`. The guide [Prototypes](../../guides/prototypes/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nReplaces indexed placeholders `{0}`, `{1}`... with the arguments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | The value for `{0}`. Any number of arguments can follow. |\n\nReturns: `String` The formatted string.\n\nEach `{n}` is replaced with the argument at index `n`. A `null` or `undefined` argument gives an empty string. For named placeholders use `String.args()`.\n\nExample: Indexed placeholders\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nReplaces named placeholders `{key}` or `{{key}}` with values of an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The values. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (URL encoding), `'html'`, `'json'` or a function `function(value, key)`. |\n| `def` | `String` | no |  | The text for a missing value. It is ignored when `encode` is a string. |\n\nReturns: `String` The string with the values.\n\nKeys may contain letters, numbers, `_`, `$`, `.` and `-`. A missing value keeps the placeholder, or uses `def` when you set it.\n\nThe `encode` argument changes how values are written: `true` encodes them with `encodeURIComponent()`, `'html'` encodes HTML entities, `'json'` writes `JSON.stringify(value)`, and a function `function(value, key)` returns the text itself. `String.arg()` is an alias.\n\nExample: Named placeholders\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: HTML encoding\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: A default for missing values\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nCreates a URL-friendly slug from the text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | The maximum length. |\n\nReturns: `String` The slug.\n\nThe text is trimmed, lower-cased and converted to ASCII (diacritics removed). Spaces and punctuation become a single `-`; a trailing `-` is removed. The result is cut at `max` characters.\n\nWhen the text has no usable Latin characters (for example Chinese or Cyrillic), the method returns a short hash built from the text instead.\n\nExample: Slug from a title\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nCuts the text to a maximum length and adds an ellipsis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | The maximum length of the result. |\n| `chars` | `String` | no | `'...'` | The text appended to a cut string. |\n\nReturns: `String` The shortened text.\n\nWhen the text is longer than `length`, it is cut so that the result with `chars` has exactly `length` characters. A shorter text is returned unchanged.\n\nExample: Shorten a description\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nUpper-cases the first letter of every word.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Capitalize only the first letter. |\n\nReturns: `String` The capitalized text.\n\nThe text is lower-cased and each letter after a space, tab or new line is upper-cased. With `first` set to `true`, only the first letter of the whole text is upper-cased.\n\nExample: Words and first letter\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nConverts the whole string to a number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value returned when the string is not a number. |\n\nReturns: `Number` The number, or `def`.\n\nThe string is trimmed and converted with the unary `+` operator, so the whole string must be a number: `'12px'` is not a number and gives `def`. To read a number from a longer text, use `String.parseInt2()`.\n\nExample: Query parameter\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nReads the first integer found in the text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value returned when the text contains no number. |\n\nReturns: `Number` The number, or `def`.\n\nUnlike `String.parseInt()`, the number may be surrounded by other text. A leading `-` is kept. `String.parseFloat2()` works the same way for decimal numbers (a `,` decimal separator is accepted).\n\nExample: Number inside text\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nConverts the string to a decimal number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value returned when the string is not a number. |\n\nReturns: `Number` The number, or `def`.\n\nThe string is trimmed and a `,` decimal separator is replaced with `.`. The whole string must be a number, otherwise `def` is returned.\n\nExample: Decimal comma\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nConverts `true`, `1` or `on` to `true`.\n\nReturns: `Boolean`\n\nThe comparison ignores case. Every other value gives `false`.\n\nExample: Checkbox value\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nConverts the string to a `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | The format of the input, for example `'dd/MM/yyyy'`. |\n\nReturns: `Date` The parsed date.\n\nWithout `format`, the method reads ISO strings (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` and any value that `new Date()` understands. A missing date part uses today.\n\nWith `format`, the digits of the string are read in the order of the format letters (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). A `pm` in the text adds 12 hours.\n\nExample: Parse dates\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nParses JSON without throwing an exception.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convert ISO date strings to dates. |\n\nReturns: `Object` The parsed value, or `undefined` for invalid JSON.\n\nInvalid JSON returns `undefined` instead of an error. With `date` set to `true`, ISO date strings are converted to `Date` objects.\n\nExample: Safe parse\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nParses `KEY=value` lines (the `.env` format) into an object.\n\nReturns: `Object` The keys and their string values.\n\nEmpty lines and lines starting with `#` or `//` are skipped. Values in double or single quotes lose the quotes, and `\\n` becomes a new line. Unquoted values are trimmed.\n\nExample: Read a .env file\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nChecks whether the string is an email address.\n\nReturns: `Boolean`\n\nThe test uses the `DEF.validators.email` regular expression, so you can replace it. Strings of 4 characters or less are always `false`.\n\nExample: Validate input\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nChecks whether the string is a phone number.\n\nReturns: `Boolean`\n\nThe test uses the `DEF.validators.phone` regular expression. Strings shorter than 6 characters are always `false`.\n\nExample: Phone number\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nChecks whether the string is a URL address.\n\nReturns: `Boolean`\n\nThe test uses the `DEF.validators.url` regular expression. Strings of 7 characters or less are always `false`.\n\nExample: URL address\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nChecks whether the string is a valid identifier created by `UID()`.\n\nReturns: `Boolean`\n\nThe method tests the format with `DEF.validators.uid` and then the checksum that `UID()` writes into every identifier, so a random string with the right characters is not accepted.\n\nExample: Validate an id from the URL\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nChecks whether the string looks like JSON.\n\nReturns: `Boolean`\n\nOnly the first and last non-white characters are tested: `{...}`, `[...]`, `\"...\"` or a number. The content is not parsed; use `String.parseJSON()` for that.\n\nExample: Quick test\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nCreates a hash of the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | The algorithm, or `true` for an unsigned number hash. |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String|Number` A hex string for md5/sha*, otherwise a number.\n\nThe `type` selects the algorithm: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (hex strings), `'crc32'` or `'crc32unsigned'` (numbers). Without a type, the method returns a fast 32-bit number hash; `true` makes it unsigned. The `salt` is appended to the string before hashing.\n\nExample: Different hashes\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nReturns the MD5 hash as a hex string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` A 32-character hex string.\n\nThe `salt` is appended to the string before hashing. Use it for checksums and cache keys, not for passwords.\n\nExample: Cache key\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nReturns the SHA-256 hash as a hex string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` A 64-character hex string.\n\nThe `salt` is appended to the string before hashing. `String.sha1([salt])` and `String.sha512([salt])` work the same way with the other algorithms.\n\nExample: Hash with a salt\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nEncodes HTML special characters.\n\nReturns: `String` The encoded text.\n\nReplaces `<`, `>`, `\"`, `'` and `&` with HTML entities, so the text can be written safely into HTML.\n\nExample: Escape user input\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDecodes HTML entities back to characters.\n\nReturns: `String` The decoded text.\n\nNamed entities and numeric entities (`&#65;`, `&#x41;`) are converted. It is the opposite of `String.encode()`.\n\nExample: Decode\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nEncrypts the string with a key.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The encryption key. |\n| `isUnique` | `Boolean` | no | `false` | Make every result different. |\n| `secret` | `String` | no | `CONF.secret` | An additional secret. |\n\nReturns: `String` The encrypted string.\n\nWith `isUnique` set to `true`, every call gives a different result for the same input. The result contains a checksum made from `secret` (default `CONF.secret`) and the key, which `String.decrypt()` checks. Use it for tokens and URLs, not for storing passwords.\n\nExample: Encrypt a token\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nDecrypts a string created by `String.encrypt()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The encryption key. |\n| `secret` | `String` | no | `CONF.secret` | The additional secret. |\n\nReturns: `String` The original string, or `null`.\n\nUse the same `key` and `secret` as for encryption. A wrong key, a wrong secret or a changed string returns `null`.\n\nExample: Decrypt a token\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtracts keywords from the text, sorted by frequency.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Normalize the words for search. |\n| `alternative` | `Boolean` | no | `false` | Shorten every word to 80% of its length. |\n| `max_count` | `Number` | no | `200` | The maximum number of words read. |\n| `max_length` | `Number` | no | `20` | The maximum length of a word. |\n| `min_length` | `Number` | no | `2` | The minimum length of a word. |\n\nReturns: `String[]` Unique words, the most frequent first.\n\nWith `forSearch` (default `true`) the text is converted to ASCII and `y` becomes `i`, which makes searching tolerant. With `alternative`, each word is shortened to 80% of its length. Words shorter than `min_length` or longer than `max_length` are skipped. `String.toKeywords()` is an alias.\n\nExample: Keywords for a search index\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormalizes the text for a full-text search.\n\nReturns: `String` The normalized text.\n\nThe text is lower-cased and converted to ASCII, special characters are removed, `y` becomes `i` and repeated letters are merged. Apply it to both the stored text and the searched phrase.\n\nExample: Search value\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nRemoves diacritics from the text.\n\nReturns: `String` The text without diacritics.\n\nAccented letters are replaced with their basic Latin letters, for example `á` with `a`.\n\nExample: Remove diacritics\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nRemoves HTML tags from the text.\n\nReturns: `String` The plain text.\n\nOnly the tags are removed; the text between them stays. HTML entities are not decoded.\n\nExample: Plain text\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nPads the string on the left to the length `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The final length. |\n| `c` | `String` | no | `' '` | The padding character. |\n\nReturns: `String` The padded string.\n\nA string that is already `max` characters or longer is returned unchanged.\n\nExample: Leading zeros\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nPads the string on the right to the length `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The final length. |\n| `c` | `String` | no | `' '` | The padding character. |\n\nReturns: `String` The padded string.\n\nA string that is already `max` characters or longer is returned unchanged.\n\nExample: Fixed-width column\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nChecks whether the string starts with `text`, optionally ignoring case.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | The text to find. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true` to ignore case, or a start position. |\n\nReturns: `Boolean`\n\nTotal.js replaces the native method. With `ignoreCase` set to `true` the comparison ignores case; a number is used as the start position. `String.endsWith(text, [ignoreCase])` works the same way at the end of the string.\n\nExample: Ignore case\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nConverts Markdown to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | The options described above. |\n\nReturns: `String` The HTML.\n\nThe result is wrapped in `<div class=\"markdown markdown-container\">` unless `opt.wrap` is `false`. Most features are on by default and you turn one off with `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Other options: `linetag` (the tag of a paragraph, default `'p'`), `prefix` (a prefix for generated ids), `custom` (a function that changes each line) and `html` (a function `function(html, type)` that changes the generated HTML).\n\nExample: Render Markdown\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Without wrapper and images\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nRemoves trailing slashes.\n\nReturns: `String` The string without trailing slashes.\n\nAll `/` characters at the end are removed, but a single `/` is kept, so `'/'` stays `'/'`.\n\nExample: Clean a URL\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nCreates a JSON schema object from an inline definition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The name of the schema used in `$id`. |\n| `url` | `String` | no | `CONF.url` | The base URL of `$id`. |\n\nReturns: `Object` The JSON schema.\n\nThe definition is a list of `name:type` pairs separated by commas or new lines. A `*` or `!` before the name makes the field required. Types: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` sets a maximum length, `[string]` makes an array, `{draft|published}` an enum, and `@name` uses another schema.\n\nThe `$id` is built from `url` (default `CONF.url`) and `name`.\n\nExample: Inline schema\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormats the number with a thousands separator and decimals.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | The number of decimals. |\n| `separator` | `String` | no | `' '` | The thousands separator. |\n| `separatorDecimal` | `String` | no | `'.'` | The decimal separator. |\n\nReturns: `String` The formatted number.\n\nThe default thousands separator is a space. Decimals are cut (not rounded) or padded with zeros to `decimals`. The decimal separator is `.`, or `,` when the thousands separator is `.`. You can also pass the separator first: `format(',', 2)`.\n\nExample: Format prices\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nChooses a word form by the number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | The form for 0, or all forms separated by commas. |\n| `one` | `String` | no |  | The form for 1. |\n| `few` | `String` | no |  | The form for 2 to 4. |\n| `other` | `String` | no |  | The form for other numbers. |\n\nReturns: `String` The chosen form.\n\n`zero` is used for 0, `one` for 1, `few` for 2 to 4 and `other` for the rest. A `#` in the chosen form is replaced with the number. You can also pass all forms as one comma-separated string.\n\nExample: Item count\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nConverts the number to a string padded on the left.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The final length. |\n| `c` | `String` | no | `'0'` | The padding character. |\n\nReturns: `String` The padded number.\n\nThe default padding character is `0`.\n\nExample: Invoice number\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nConverts the number to a string padded on the right.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The final length. |\n| `c` | `String` | no | `'0'` | The padding character. |\n\nReturns: `String` The padded number.\n\nThe default padding character is `0`.\n\nExample: Pad right\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nRounds the number to a number of decimals.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | The number of decimals. |\n\nReturns: `Number` The rounded number.\n\nWithout `precision` the number is rounded to an integer.\n\nExample: Round\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nRounds the number down to a number of decimals.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | The number of decimals. |\n\nReturns: `Number` The number rounded down.\n\nIt works like `Math.floor()` with decimals.\n\nExample: Floor\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nReturns a value from a map of number ranges.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Ranges as keys and results as values. |\n| `otherwise` | `Object` | yes |  | The value when no range matches. |\n\nReturns: `Object` The value of the matching range.\n\nKeys of `condition` are ranges: `'1-5'` (from 1 to 5), `'10-'` (10 and more) or `'-5'` (5 and less). The value of the first matching range is returned, otherwise `otherwise`.\n\nExample: Rating label\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nApplies a math operation written as a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | A number, or an operation such as `'-5'` or `'+20%'`. |\n| `decimals` | `Number` | no |  | Round the result down to these decimals. |\n\nReturns: `Number` The result.\n\nA number is added. A string starts with an operator `+`, `-`, `*` or `/` followed by a number, for example `'+10'`. With `%` at the end the operand is a percentage of the number: `'+20%'` adds 20%. With `decimals` the result is rounded down to that number of decimals.\n\nExample: Operations\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAdds VAT to the price, or removes it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | The VAT rate in percent. |\n| `decimals` | `Number` | no | `2` | The number of decimals. |\n| `includedVAT` | `Boolean` | no | `false` | The number already includes VAT. |\n\nReturns: `Number` The price.\n\nWithout `includedVAT` the method returns the price with VAT. With `includedVAT` set to `true`, the number is a price with VAT and the method returns the price without it. The result is rounded to `decimals`.\n\nExample: With and without VAT\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nSubtracts a percentage discount.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | The discount in percent. |\n| `decimals` | `Number` | no | `2` | The number of decimals. |\n\nReturns: `Number` The discounted number.\n\nThe result is rounded down to `decimals`.\n\nExample: Discount\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nFormats a number of bytes as a readable file size.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | The number of decimals. |\n| `type` | `String` | no |  | The unit: `'bytes'`, `'KB'`, `'MB'`, `'GB'` or `'TB'`. |\n\nReturns: `String` The size with the unit.\n\nWithout `type` the unit is chosen automatically (`bytes`, `KB`, `MB`, `GB` or `TB`). With `type` the value is converted to that unit. Without `decimals` the value has up to 2 decimals.\n\nExample: File size\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nRuns an asynchronous function the number of times, counting down.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | The function `function(number, next)`. |\n| `callback` | `Function` | no |  | Called after the last run. |\n\nReturns: `Number`\n\nThe function gets the current number (from the start value down to 1) and `next`. The next run starts after you call `next()`. When the count reaches zero, `callback` is called.\n\nExample: Three runs\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nReturns a new date moved by a time period.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | The unit, an expression such as `'5 days'`, or milliseconds. |\n| `value` | `Number` | no |  | The amount. |\n\nReturns: `Date` A new date.\n\nPass a type and a value (`add('days', 5)`) or one expression (`add('5 days')`). Types: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, also the short forms `s`, `m`, `h`, `d`, `w`, `M`, `y`. Negative values move back. A number adds milliseconds. The original date is not changed.\n\nExample: Move dates\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nFormats the date as a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | The format, for example `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | The resource file with translated month and day names. |\n\nReturns: `String` The formatted date.\n\nWithout `format` the date is returned as an ISO string in UTC. Format tokens use the local time: `yyyy`, `yy`, `MM`, `M`, `MMM` (short month name), `MMMM` (month name), `dd`, `d`, `ddd` (short day name), `dddd` (day name), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (ISO week), `a` (AM/PM). Month and day names are English; with `resource` they are read from that resource file.\n\nExample: Formats\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nReturns the difference between two dates in a unit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | The date to compare with. |\n| `type` | `String` | yes |  | The unit. |\n\nReturns: `Number` The difference.\n\nThe difference is `this - date`, rounded up. Without `date` the method compares with now. Units: `seconds`, `minutes`, `hours`, `days`, `months`, `years` and the short forms `s`, `m`, `h`, `d`, `M`, `y`. A month counts as 28 days. An unknown unit gives `NaN`.\n\nExample: Days left\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nShifts the date by the local timezone offset.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Return milliseconds. |\n\nReturns: `Date|Number`\n\nThe result shows the UTC time in the local fields of the date. With `ticks` set to `true`, the method returns milliseconds instead of a date.\n\nExample: UTC date\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nReturns a new date with parts set from a string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | The date or time parts, for example `'12:00'` or `'2024-12-24 18:00'`. |\n\nReturns: `Date` A new date.\n\nThe string may contain a date (`yyyy-MM-dd` or `dd.MM.yyyy`) and a time (`HH:mm` or `HH:mm:ss`). Only the given parts are changed; they are set in UTC.\n\nExample: Set time\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nReturns a new date converted to a timezone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | The IANA timezone name. |\n\nReturns: `Date` A new date.\n\nThe `timezone` is an IANA name such as `'Europe/Bratislava'`.\n\nExample: Time in New York\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nReturns the first matching item, or `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | A function or a property name. |\n| `value` | `Object` | no |  | The value of the property. |\n\nReturns: `Object` The item, or `null`.\n\n`cb` is a function `function(item, index)`, or a property name compared with `value` (`===`). With a single non-function argument the items themselves are compared.\n\nExample: By property and by function\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nReturns all matching items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | A function `function(item, index)` or a property name. |\n| `value` | `Object` | no |  | The value of the property. |\n\nReturns: `Array` The matching items.\n\nThe arguments are the same as in `Array.findItem()`. The result is a new array.\n\nExample: Filter\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nReturns the index of the first matching item, or `-1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | A function or a property name. |\n| `value` | `Object` | no |  | The value of the property. |\n\nReturns: `Number` The index, or `-1`.\n\nTotal.js replaces the native method so it also accepts a property name and a value. A function is called as `function(item, index)`. `Array.TfindIndex()` is the same method under a name that other modules do not override.\n\nExample: Index by property\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nAn alias of `Array.findIndex()` that other modules do not override.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | A function or a property name. |\n| `value` | `Object` | no |  | The value of the property. |\n\nReturns: `Number` The index, or `-1`.\n\nSome NPM modules replace `Array.prototype.findIndex` with their own version. `TfindIndex()` keeps the Total.js behaviour (property name and value) in that case. `findItem()` and `findValue()` use it internally.\n\nExample: Safe index\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nFinds an item and returns one of its properties.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | A function or a property name. |\n| `value` | `Object` | yes |  | The value of the property. |\n| `path` | `String` | yes |  | The property to return. |\n| `def` | `Object` | no |  | The default value. |\n\nReturns: `Object` The property value, or `def`.\n\nThe item is found like in `Array.findItem()`; then its property `path` is returned. When there is no item or the property is `null`/`undefined`, `def` is returned.\n\nExample: Name by id\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nReturns a new array without the matching items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | A function, a property name or an item. |\n| `value` | `Object` | no |  | The value of the property. |\n\nReturns: `Array` A new array.\n\nThe arguments are the same as in `Array.findItem()`. The original array is not changed, so assign the result.\n\nExample: Remove items\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nReturns the first `count` items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The number of items. |\n\nReturns: `Array` A new array.\n\nThe result is a new array.\n\nExample: First three\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nReturns the items after the first `count` items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The number of skipped items. |\n\nReturns: `Array` A new array.\n\nTogether with `Array.take()` it makes simple paging.\n\nExample: Paging\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nReturns the first item, or `def` for an empty array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | The value for an empty array. |\n\nReturns: `Object`\n\nExample: First item\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nReturns the last item, or `def` for an empty array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | The value for an empty array. |\n\nReturns: `Object`\n\nExample: Last item\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nSorts the array in place.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | The properties to sort by, or `true` for descending primitive values. |\n| `desc` | `Boolean` | no | `false` | Sort descending. |\n\nReturns: `Array` The same array.\n\n`sort` is a property name with an optional `_asc` or `_desc` suffix, for example `'name'` or `'price_desc'`. Several properties are separated by commas (`'name_asc,price_desc'`) and nested properties use dots. Strings, numbers, booleans and dates are compared by their type. With `desc` set to `true`, the order is reversed.\n\nWithout arguments, primitive values are sorted ascending; `quicksort(true)` sorts them descending.\n\nExample: Sort objects\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nCreates an object (a lookup map) from the array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The property used as the key. |\n\nReturns: `Object` The lookup object.\n\nWith `name`, each item is stored under the value of its property `name`. Without it, each item becomes a key with the value `true`.\n\nExample: Lookups\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nTrims strings and removes empty items.\n\nReturns: `Array` A new array.\n\nStrings are trimmed, and items that are empty after trimming (or are `null`, `0`, `false`) are removed. It returns a new array.\n\nExample: Clean a list\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nProcesses items one by one with an asynchronous function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | The function `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Called after the last item. |\n| `thread` | `Number|Boolean` | no | `1` | The number of parallel items, or `true` to remove items. |\n\nReturns: `Array` The same array.\n\n`onItem(item, next, index)` is called for each item; call `next()` to continue. `callback` is called after the last item. `thread` sets how many items are processed at once (default 1). With `thread` set to `true`, the items are removed from the array while they are processed. Call `next('cancel')` to stop; `callback` then gets `'cancel'`.\n\nExample: Send emails one by one\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nRuns an array of asynchronous functions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | The number of parallel functions. |\n| `callback` | `Function` | no |  | Called at the end. |\n\nReturns: `Array` The same array.\n\nEach item is a function `function(next)`. The items are removed from the array as they run. `thread` sets how many functions run at once (default 1). `callback` is called after the last function, or with `'cancel'` when a function calls `next('cancel')`.\n\nExample: A list of tasks\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nProcesses the array in chunks of `max` items.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | The size of a chunk. |\n| `fn` | `Function` | yes |  | The function `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Called after the last chunk. |\n\nReturns: `Array` The same array.\n\n`fn(items, next, beg, end)` gets the next chunk; call `next()` to continue with the following chunk. `callback` is called after the last chunk.\n\nExample: Insert in batches\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nShuffles the array, or returns a random item.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Return one random item. |\n\nReturns: `Array|Object`\n\nWithout arguments the array is shuffled in place (Fisher-Yates) and returned. With `item` set to `true`, one random item is returned and the array is not changed.\n\nExample: Shuffle and pick\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nParses CSV text into an array of objects.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | The column delimiter. |\n\nReturns: `Object[]` One object per line, with the keys `a`, `b`, `c`...\n\nEvery line becomes one object. The columns are named by letters: the first is `a`, the second `b` and so on. Values in double quotes may contain the delimiter and new lines, and `\"\"` inside quotes is an escaped quote. All values stay strings, and an empty column has no key in the object. A header line is not detected, so it comes back as the first object.\n\nExample: Read a CSV file\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nReads the operating system, browser and device type from a user agent string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Return an object instead of a text. |\n\nReturns: `String|Object` The detected names, or `{ os, browser, device }`.\n\nWithout an argument the method returns a short text with the detected names, such as `Mac Chrome` or `iOS iPhone Mobile Safari`. With `structured` set to `true` it returns an object `{ os, browser, device }`, where `device` is `desktop`, `mobile`, `tablet` or `tv`. An empty string returns an empty string.\n\nExample: Detect the client\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nParses `application/x-www-form-urlencoded` text into an object.\n\nReturns: `Object` The parsed keys and values.\n\nThe text looks like a query string: `key=value&key2=value2`. `+` becomes a space and `%xx` sequences are decoded. All values stay strings; a repeated key joins its values with a comma. Keys may contain only letters, digits and `-`, `_`, `.`, `[`, `]`, and parsing stops at the first other character in a key. The number of keys is limited by `CONF.default_request_maxkeys` and the length of a key by `CONF.default_request_maxkey`.\n\nExample: Parse a form body\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nParses XML into a flat object of paths and values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Replace special characters in the keys with `_`. |\n\nReturns: `Object` The flat object of paths.\n\nEvery element with text becomes a key made of the element names joined with dots, for example `book.title`. A repeated element gives an array of values. The attributes of an element are stored as an object under the path followed by `[]`. `CDATA` sections are read as text and comments are skipped. With `replace` set to `true`, the characters `[`, `]`, `:`, `.` and `_` in the keys are replaced with `_`.\n\nExample: Read an XML feed\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nParses HTML into a tree of elements that you can search and change.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Trim the text content. |\n\nReturns: `HTMLElement` The root element of the parsed document.\n\nThe method uses the built-in HTML parser and returns the root element. Elements have `tagName`, `attrs`, `children` and `parentNode`, and the methods `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` and `html([formatted])`. With `trim` set to `true`, the text inside the elements is trimmed.\n\nExample: Read and change HTML\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nCuts tagged blocks out of a text and returns their content by name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | The name and the opening tag of each block. |\n\nReturns: `Object` The content of every block that was found.\n\n`tags` maps a name to an opening tag, for example `{ js: '<script>', css: '<style>' }`. For each name the content between the opening tag and its closing tag is returned (nested tags of the same kind are counted). A missing tag gives no key. Total.js uses it to read the `<script total>` part of `.html` plugins and components.\n\nExample: Split a component file\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nParses the column output of a terminal command line by line.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Header names or regular expressions of the columns. |\n| `fn` | `Function` | yes |  | Called as `fn(values, index, count, line)` for every line. |\n| `skip` | `Number` | no | `0` | The number of lines to skip. |\n| `take` | `Number` | no | `all` | The number of lines to read. |\n\nReturns: `String` The same string.\n\nWith `fields`, the first non-empty line (of the first three) is the header. Each field is a header name (`String`) or a `RegExp` that finds the column in the header line, and `fn` gets the values of those columns for every following line. Without `fields`, every line is split into words and `fn` gets the array of words. `fn(values, index, count, line)` gets the values, the index of the parsed line, the end index and the line number. `skip` and `take` limit the lines. The method returns the string itself.\n\nExample: Read the output of df\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nParses text in the Total.js config format into an object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Default values copied into the result. |\n| `onerror` | `Function` | no |  | Called as `onerror(err, line)` when an `object` or `eval` value fails. |\n\nReturns: `Object` The parsed values.\n\nEach line is `key : value`, and lines starting with `#` or `//` are skipped. The value starts two characters after the first `:`, so write a space after the colon. A type in parentheses after the key converts the value: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (comma-separated), `(json)`, `(object)` or `(eval)` (evaluated as JavaScript), `(date)`, `(env)` (an environment variable), `(config)` (another `CONF` key) and `(random)` (a random string of the given length). `def` gives default values. `onerror(err, line)` handles a value that cannot be evaluated; without it the method throws.\n\nExample: Parse a config text\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nTurns a text like `5 minutes` into a date in the future.\n\nReturns: `Date` The current date plus the given time.\n\nThe text is read as pairs of a number and a unit, separated by spaces, for example `1 day 12 hours`. Each pair is added to the current date with `Date.add()`, so the same units work (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). A pair with the number `0` is ignored.\n\nExample: Expiration of a cookie\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nReads the information stored in an identifier created by `UID()`.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nThe result has `version` (the last character of the UID), `date` (when it was created), `century`, `index` (the counter), `hash` and `valid`. For the random `r` version (`CONF.default_uid = 'r'`) the result has no date, and identifiers are validated with `String.isUID()`.\n\nExample: When was a record created\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nFinds the first decimal number in a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | The value returned when no number is found. |\n\nReturns: `Number` The number found.\n\nUnlike `String.parseFloat()`, the text may contain other characters: the first group of digits, dots and commas is used, and commas become dots. A leading `-` makes it negative. Without a number the method returns `def`.\n\nExample: Price from a label\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nChecks whether the string is a GUID (UUID).\n\nReturns: `Boolean`\n\nThe string must have 36 characters in the form `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, where `M` is a version from 1 to 5. Upper and lower case letters are accepted.\n\nExample: Validate a UUID\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nChecks whether the string is a date in the JSON (ISO 8601 UTC) format.\n\nReturns: `Boolean`\n\nThe method checks the shape of the text, such as `2024-05-01T10:30:00.000Z`: the length, the `T`, the dashes and colons and the final `Z`. It does not check that the date exists.\n\nExample: Revive dates\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nChecks whether the string contains only digits.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Allow one decimal separator. |\n\nReturns: `Boolean`\n\nWith `decimal` set to `true`, one `.` or `,` is allowed as well. Signs, spaces and exponents are not accepted, and an empty string returns `false`.\n\nExample: Check user input\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nChecks whether the string is `true` or `false`.\n\nReturns: `Boolean`\n\nThe comparison ignores case. Other values such as `1` or `on` return `false`; `String.parseBoolean()` reads those.\n\nExample: Check a query value\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nChecks whether the string looks like a postal (ZIP) code.\n\nReturns: `Boolean`\n\nThe string is tested with `DEF.validators.zip`, by default 3 to 20 letters, digits, spaces or dashes. Change `DEF.validators.zip` to use your own rule.\n\nExample: Validate a postal code\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nChecks whether the string contains an HTML tag.\n\nReturns: `Boolean`\n\nThe test is simple: it returns `true` when the text contains `<` followed later by `>`. Use it to reject HTML in plain text fields.\n\nExample: Reject HTML\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nChecks whether the string contains a quoted text or an SQL keyword.\n\nReturns: `Boolean`\n\nThe method returns `true` for text in single quotes or for the upper-case words `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` and `UNION`. It is a rough check; use parameters in your queries anyway.\n\nExample: Check a search phrase\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nChecks whether the string is base64 encoded.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Accept a data URI prefix. |\n\nReturns: `Boolean`\n\nThe length must be divisible by 4 and the text must contain only base64 characters. With `data` set to `true`, a data URI such as `data:image/png;base64,...` is accepted and only the length of the encoded part is checked.\n\nExample: Check an upload\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nWrites base64 data to a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The path of the file. |\n| `callback` | `Function` | no |  | Called as `callback(err)` when the file is written. |\n\nReturns: `String` The same string.\n\nA data URI prefix (everything up to the first comma) is removed, and the rest is decoded and written with `fs.writeFile()`. The method returns the string itself; the result of writing comes to `callback(err)`.\n\nExample: Save an uploaded image\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDecodes base64 data into a `Buffer`.\n\nReturns: `Buffer` The decoded data.\n\nA data URI prefix (everything up to the first comma) is removed before decoding.\n\nExample: Decode a data URI\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nReturns the content type of a data URI.\n\nReturns: `String` The content type, for example `image/png`.\n\nThe text between `data:` and the first `;` is returned. A string without `;` returns an empty string.\n\nExample: Check the type of an upload\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nComputes the CRC32 checksum of the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Return an unsigned number. |\n\nReturns: `Number` The checksum.\n\nThe result is a signed 32-bit number, or an unsigned one when `unsigned` is `true`. `String.hash('crc32')` and `String.hash('crc32unsigned')` give the same results.\n\nExample: Checksum of a text\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nCreates a SHA-1 hash of the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` The hash as hex.\n\nThe `salt` is appended to the string before hashing.\n\nExample: SHA-1 hash\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nCreates a SHA-512 hash of the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text appended before hashing. |\n\nReturns: `String` The hash as hex.\n\nThe `salt` is appended to the string before hashing.\n\nExample: Hash a token\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nMakes a short id from the string.\n\nReturns: `String` The id.\n\nThe id is a quick unsigned hash of the string written in base 36. The same string always gives the same id. It is not a cryptographic hash.\n\nExample: Id for a cache key\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nAdds a quick checksum to the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | A secret mixed into the checksum. |\n\nReturns: `String` The string with the checksum.\n\nThe result is the string, a dash and a base 36 hash of the string with `key`. To verify a value, sign the part before the last dash again and compare. It is a quick checksum, not a cryptographic signature.\n\nExample: Sign and verify a value\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nProtects an identifier with a checksum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | The secret. |\n\nReturns: `String` The protected identifier.\n\nThe result is `x`, a checksum and `x` followed by the original value, so the value stays readable but cannot be changed without the key. The checksum uses `key` (default `CONF.secret`) and `CONF.secret_uid`. Read it back with `String.decrypt_uid()`. The same function for numbers is `U.encrypt_uid(value, [key])`.\n\nExample: Protected id in a link\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nReads an identifier protected with `String.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | The secret used for `encrypt_uid()`. |\n\nReturns: `String|Number` The original value, or `null` when the checksum is wrong.\n\nThe checksum is created again with `key` (default `CONF.secret`). When it matches, the original value is returned, otherwise `null`. A value created from a number comes back as a number.\n\nExample: Verify a link\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nCleans a person name: removes other characters and capitalizes each word.\n\nReturns: `String` The cleaned name.\n\nDigits and ASCII punctuation are removed, spaces are kept, and the first letter of each word is made upper case. Letters with diacritics are kept. Trailing spaces are dropped, but leading and repeated spaces are not, so trim the input first.\n\nExample: Clean a name from a form\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nEscapes characters outside printable ASCII as `\\uXXXX`.\n\nReturns: `String` The escaped string.\n\nCharacters with a code below 32 or above 126 are written as `\\u` and four hex digits. `String.fromUnicode()` reverses it.\n\nExample: Escape a text\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nTurns `\\uXXXX` escapes back into characters.\n\nReturns: `String` The unescaped string.\n\nEvery `\\u` followed by four hex digits is replaced with the character. It reverses `String.toUnicode()`.\n\nExample: Unescape a text\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nChecks whether the string ends with a text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | The text to find. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true` to ignore case, or an offset from the end. |\n\nReturns: `Boolean`\n\nTotal.js replaces the native method. With `ignoreCase` set to `true`, case is ignored. A number in place of `ignoreCase` checks the text that many characters before the end.\n\nExample: Check a file extension\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nReplaces the first occurrence of a text, without regular expressions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | The text to replace. |\n| `text` | `String` | yes |  | The new text. |\n\nReturns: `String` The new string.\n\n`find` is plain text, so characters like `$` or `.` have no special meaning in it or in `text`. When `find` is not found, the string is returned unchanged.\n\nExample: Insert a price into a template\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nInserts a value at a position in the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | The position. |\n| `value` | `Object` | yes |  | The value to insert. |\n\nReturns: `String` The new string.\n\nThe value is converted to a string with `toString()`.\n\nExample: Format a code\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nAdds a character to the start of the string a number of times.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | How many characters to add. |\n| `char` | `String` | no | `' '` | The character. |\n\nReturns: `String` The indented string.\n\nUnlike `String.padLeft()`, the characters are always added, whatever the length of the string.\n\nExample: Indent a line\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nChooses a word form by the number in the string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | The form for 0, or all forms separated by commas. |\n| `one` | `String` | no |  | The form for 1. |\n| `few` | `String` | no |  | The form for 2 to 4. |\n| `other` | `String` | no |  | The form for other numbers. |\n\nReturns: `String` The chosen form.\n\nThe string is read with `String.parseInt()` and passed to `Number.pluralize()`, so the rules and the `#` placeholder are the same.\n\nExample: Count from a query\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nReplaces `[key]` placeholders with configuration values.\n\nReturns: `String` The string with the values.\n\nEvery `[key]` (letters, digits and `_`) is replaced with `CONF[key]`; a missing key gives an empty string.\n\nExample: Build a URL from the config\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nFinds blocks in a string and passes each to a callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | The start delimiter, or the separator when `end` is missing. |\n| `end` | `String` | no |  | The end delimiter. |\n| `callback` | `Function` | yes |  | Called as `callback(value, index)`; return `false` to stop. |\n| `skip` | `Number` | no | `0` | The number of blocks to skip. |\n\nReturns: `undefined`\n\nWith `beg` and `end`, every block that starts with `beg` and ends with `end` is passed, delimiters included. Without `end`, the string is split after every `beg`, and each part ends with `beg`. `callback(value, index)` can return `false` to stop. `skip` skips the first blocks.\n\nExample: Read items from XML\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nRounds the number to a number of decimals and returns a number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | The number of decimals. |\n\nReturns: `Number` The rounded number.\n\nThe same as `+number.toFixed(decimals)`: unlike `toFixed()`, the result is a number, not a string.\n\nExample: Round a price\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormats the number with a currency formatter from `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | The key in `DEF.currencies`. |\n| `a` | `Object` | no |  | Passed to the formatter, like `b` and `c`. |\n\nReturns: `String` The formatted price.\n\n`DEF.currencies` is empty by default; add a function `function(value, a, b, c)` for each currency code you need, and `default` for calls without a code. The extra arguments are passed to it. Without a formatter the number is formatted with `Number.format(2)`.\n\nExample: Register and use currencies\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nConverts the number to upper-case hexadecimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | The minimum length. |\n\nReturns: `String` The hex value.\n\nThe result is padded with leading zeros to `length` characters.\n\nExample: Color component\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nCreates a date from a timestamp in milliseconds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Milliseconds to add. |\n\nReturns: `Date` The date.\n\n`plus` milliseconds are added to the number before the date is created.\n\nExample: Date from a timestamp\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nConverts degrees to radians.\n\nReturns: `Number` The angle in radians.\n\nDefined only when `Number.prototype.toRad` does not exist yet.\n\nExample: Distance between two GPS points\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nReturns the date itself.\n\nReturns: `Date` The same date.\n\nIt lets you call `parseDate()` on a value that can be a string, a number or a date, without checking its type first.\n\nExample: Value of an unknown type\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Prototypen","summary":"Methoden von String, Number, Date und Array, die Total.js 4 hinzufügt.","markdown":"---\ntitle: Prototypen\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypen\n\n> Methoden von String, Number, Date und Array, die Total.js 4 hinzufügt.\n\nMethoden, die Total.js 4 zu `String`, `Number`, `Date` und `Array` hinzufügt. Der Leitfaden [Prototypen](../../guides/prototypes/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nErsetzt indizierte Platzhalter `{0}`, `{1}`... durch die Argumente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | Der Wert für `{0}`. Es können beliebig viele Argumente folgen. |\n\nReturns: `String` Der formatierte String.\n\nJedes `{n}` wird durch das Argument mit dem Index `n` ersetzt. Ein Argument `null` oder `undefined` ergibt einen leeren String. Für benannte Platzhalter verwende `String.args()`.\n\nExample: Indizierte Platzhalter\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nErsetzt benannte Platzhalter `{key}` oder `{{key}}` durch Werte eines Objekts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Die Werte. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (URL-Kodierung), `'html'`, `'json'` oder eine Funktion `function(value, key)`. |\n| `def` | `String` | no |  | Der Text für einen fehlenden Wert. Er wird ignoriert, wenn `encode` ein String ist. |\n\nReturns: `String` Der String mit den Werten.\n\nSchlüssel dürfen Buchstaben, Ziffern, `_`, `$`, `.` und `-` enthalten. Ein fehlender Wert behält den Platzhalter oder verwendet `def`, wenn du es setzt.\n\nDas Argument `encode` ändert, wie Werte geschrieben werden: `true` kodiert sie mit `encodeURIComponent()`, `'html'` kodiert HTML-Entitäten, `'json'` schreibt `JSON.stringify(value)`, und eine Funktion `function(value, key)` gibt den Text selbst zurück. `String.arg()` ist ein Alias.\n\nExample: Benannte Platzhalter\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: HTML-Kodierung\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: Ein Standardwert für fehlende Werte\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nErstellt einen URL-freundlichen Slug aus dem Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | Die maximale Länge. |\n\nReturns: `String` Der Slug.\n\nDer Text wird getrimmt, in Kleinbuchstaben umgewandelt und in ASCII konvertiert (diakritische Zeichen entfernt). Leerzeichen und Satzzeichen werden zu einem einzelnen `-`; ein abschließendes `-` wird entfernt. Das Ergebnis wird nach `max` Zeichen abgeschnitten.\n\nHat der Text keine verwendbaren lateinischen Zeichen (zum Beispiel Chinesisch oder Kyrillisch), gibt die Methode stattdessen einen kurzen, aus dem Text gebildeten Hash zurück.\n\nExample: Slug aus einem Titel\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nKürzt den Text auf eine maximale Länge und fügt Auslassungspunkte an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Die maximale Länge des Ergebnisses. |\n| `chars` | `String` | no | `'...'` | Der Text, der an einen gekürzten String angehängt wird. |\n\nReturns: `String` Der gekürzte Text.\n\nIst der Text länger als `length`, wird er so gekürzt, dass das Ergebnis mit `chars` genau `length` Zeichen hat. Ein kürzerer Text wird unverändert zurückgegeben.\n\nExample: Eine Beschreibung kürzen\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nSchreibt den ersten Buchstaben jedes Wortes groß.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Nur den ersten Buchstaben großschreiben. |\n\nReturns: `String` Der Text mit großen Anfangsbuchstaben.\n\nDer Text wird in Kleinbuchstaben umgewandelt, und jeder Buchstabe nach einem Leerzeichen, Tabulator oder Zeilenumbruch wird großgeschrieben. Ist `first` auf `true` gesetzt, wird nur der erste Buchstabe des gesamten Textes großgeschrieben.\n\nExample: Wörter und erster Buchstabe\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nKonvertiert den gesamten String in eine Zahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert, der zurückgegeben wird, wenn der String keine Zahl ist. |\n\nReturns: `Number` Die Zahl oder `def`.\n\nDer String wird getrimmt und mit dem unären Operator `+` konvertiert, daher muss der gesamte String eine Zahl sein: `'12px'` ist keine Zahl und ergibt `def`. Um eine Zahl aus einem längeren Text zu lesen, verwende `String.parseInt2()`.\n\nExample: Query-Parameter\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nLiest die erste im Text gefundene Ganzzahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert, der zurückgegeben wird, wenn der Text keine Zahl enthält. |\n\nReturns: `Number` Die Zahl oder `def`.\n\nAnders als bei `String.parseInt()` darf die Zahl von anderem Text umgeben sein. Ein führendes `-` bleibt erhalten. `String.parseFloat2()` funktioniert genauso für Dezimalzahlen (ein `,` als Dezimaltrennzeichen wird akzeptiert).\n\nExample: Zahl im Text\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nKonvertiert den String in eine Dezimalzahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert, der zurückgegeben wird, wenn der String keine Zahl ist. |\n\nReturns: `Number` Die Zahl oder `def`.\n\nDer String wird getrimmt, und ein `,` als Dezimaltrennzeichen wird durch `.` ersetzt. Der gesamte String muss eine Zahl sein, sonst wird `def` zurückgegeben.\n\nExample: Dezimalkomma\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nKonvertiert `true`, `1` oder `on` in `true`.\n\nReturns: `Boolean`\n\nDer Vergleich ignoriert die Groß- und Kleinschreibung. Jeder andere Wert ergibt `false`.\n\nExample: Checkbox-Wert\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nKonvertiert den String in ein `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Das Format der Eingabe, zum Beispiel `'dd/MM/yyyy'`. |\n\nReturns: `Date` Das geparste Datum.\n\nOhne `format` liest die Methode ISO-Strings (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` und jeden Wert, den `new Date()` versteht. Ein fehlender Datumsteil wird vom heutigen Tag übernommen.\n\nMit `format` werden die Ziffern des Strings in der Reihenfolge der Formatbuchstaben gelesen (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). Ein `pm` im Text addiert 12 Stunden.\n\nExample: Datumsangaben parsen\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nParst JSON, ohne eine Exception zu werfen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | ISO-Datumsstrings in Datumsangaben konvertieren. |\n\nReturns: `Object` Der geparste Wert oder `undefined` bei ungültigem JSON.\n\nUngültiges JSON gibt `undefined` statt eines Fehlers zurück. Ist `date` auf `true` gesetzt, werden ISO-Datumsstrings in `Date`-Objekte konvertiert.\n\nExample: Sicheres Parsen\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nParst `KEY=value`-Zeilen (das `.env`-Format) in ein Objekt.\n\nReturns: `Object` Die Schlüssel und ihre String-Werte.\n\nLeere Zeilen und Zeilen, die mit `#` oder `//` beginnen, werden übersprungen. Werte in doppelten oder einfachen Anführungszeichen verlieren die Anführungszeichen, und `\\n` wird zu einem Zeilenumbruch. Werte ohne Anführungszeichen werden getrimmt.\n\nExample: Eine .env-Datei lesen\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nPrüft, ob der String eine E-Mail-Adresse ist.\n\nReturns: `Boolean`\n\nDer Test verwendet den regulären Ausdruck `DEF.validators.email`, sodass du ihn ersetzen kannst. Strings mit 4 oder weniger Zeichen sind immer `false`.\n\nExample: Eingabe validieren\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nPrüft, ob der String eine Telefonnummer ist.\n\nReturns: `Boolean`\n\nDer Test verwendet den regulären Ausdruck `DEF.validators.phone`. Strings mit weniger als 6 Zeichen sind immer `false`.\n\nExample: Telefonnummer\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nPrüft, ob der String eine URL-Adresse ist.\n\nReturns: `Boolean`\n\nDer Test verwendet den regulären Ausdruck `DEF.validators.url`. Strings mit 7 oder weniger Zeichen sind immer `false`.\n\nExample: URL-Adresse\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nPrüft, ob der String ein gültiger, mit `UID()` erstellter Bezeichner ist.\n\nReturns: `Boolean`\n\nDie Methode prüft das Format mit `DEF.validators.uid` und dann die Prüfsumme, die `UID()` in jeden Bezeichner schreibt, sodass ein zufälliger String mit den richtigen Zeichen nicht akzeptiert wird.\n\nExample: Eine ID aus der URL validieren\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nPrüft, ob der String wie JSON aussieht.\n\nReturns: `Boolean`\n\nNur das erste und das letzte Nicht-Leerzeichen werden geprüft: `{...}`, `[...]`, `\"...\"` oder eine Zahl. Der Inhalt wird nicht geparst; verwende dafür `String.parseJSON()`.\n\nExample: Schneller Test\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nErstellt einen Hash des Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | Der Algorithmus oder `true` für einen vorzeichenlosen Zahlen-Hash. |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String|Number` Ein Hex-String für md5/sha*, sonst eine Zahl.\n\n`type` wählt den Algorithmus: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (Hex-Strings), `'crc32'` oder `'crc32unsigned'` (Zahlen). Ohne Typ gibt die Methode einen schnellen 32-Bit-Zahlen-Hash zurück; `true` macht ihn vorzeichenlos. Der `salt` wird vor dem Hashen an den String angehängt.\n\nExample: Verschiedene Hashes\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nGibt den MD5-Hash als Hex-String zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String` Ein Hex-String mit 32 Zeichen.\n\nDer `salt` wird vor dem Hashen an den String angehängt. Verwende ihn für Prüfsummen und Cache-Schlüssel, nicht für Passwörter.\n\nExample: Cache-Schlüssel\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nGibt den SHA-256-Hash als Hex-String zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String` Ein Hex-String mit 64 Zeichen.\n\nDer `salt` wird vor dem Hashen an den String angehängt. `String.sha1([salt])` und `String.sha512([salt])` funktionieren genauso mit den anderen Algorithmen.\n\nExample: Hash mit einem Salt\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nKodiert HTML-Sonderzeichen.\n\nReturns: `String` Der kodierte Text.\n\nErsetzt `<`, `>`, `\"`, `'` und `&` durch HTML-Entitäten, sodass der Text sicher in HTML geschrieben werden kann.\n\nExample: Benutzereingaben maskieren\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDekodiert HTML-Entitäten zurück in Zeichen.\n\nReturns: `String` Der dekodierte Text.\n\nBenannte und numerische Entitäten (`&#65;`, `&#x41;`) werden konvertiert. Es ist das Gegenteil von `String.encode()`.\n\nExample: Dekodieren\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nVerschlüsselt den String mit einem Schlüssel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Verschlüsselungsschlüssel. |\n| `isUnique` | `Boolean` | no | `false` | Jedes Ergebnis unterschiedlich machen. |\n| `secret` | `String` | no | `CONF.secret` | Ein zusätzliches Secret. |\n\nReturns: `String` Der verschlüsselte String.\n\nIst `isUnique` auf `true` gesetzt, liefert jeder Aufruf für dieselbe Eingabe ein anderes Ergebnis. Das Ergebnis enthält eine aus `secret` (standardmäßig `CONF.secret`) und dem Schlüssel gebildete Prüfsumme, die `String.decrypt()` prüft. Verwende es für Tokens und URLs, nicht zum Speichern von Passwörtern.\n\nExample: Ein Token verschlüsseln\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nEntschlüsselt einen mit `String.encrypt()` erstellten String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Verschlüsselungsschlüssel. |\n| `secret` | `String` | no | `CONF.secret` | Das zusätzliche Secret. |\n\nReturns: `String` Der ursprüngliche String oder `null`.\n\nVerwende denselben `key` und dasselbe `secret` wie bei der Verschlüsselung. Ein falscher Schlüssel, ein falsches Secret oder ein veränderter String gibt `null` zurück.\n\nExample: Ein Token entschlüsseln\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrahiert Schlüsselwörter aus dem Text, sortiert nach Häufigkeit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Die Wörter für die Suche normalisieren. |\n| `alternative` | `Boolean` | no | `false` | Jedes Wort auf 80 % seiner Länge kürzen. |\n| `max_count` | `Number` | no | `200` | Die maximale Anzahl gelesener Wörter. |\n| `max_length` | `Number` | no | `20` | Die maximale Länge eines Wortes. |\n| `min_length` | `Number` | no | `2` | Die minimale Länge eines Wortes. |\n\nReturns: `String[]` Eindeutige Wörter, die häufigsten zuerst.\n\nMit `forSearch` (standardmäßig `true`) wird der Text in ASCII konvertiert und `y` wird zu `i`, was die Suche tolerant macht. Mit `alternative` wird jedes Wort auf 80 % seiner Länge gekürzt. Wörter, die kürzer als `min_length` oder länger als `max_length` sind, werden übersprungen. `String.toKeywords()` ist ein Alias.\n\nExample: Schlüsselwörter für einen Suchindex\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormalisiert den Text für eine Volltextsuche.\n\nReturns: `String` Der normalisierte Text.\n\nDer Text wird in Kleinbuchstaben umgewandelt und in ASCII konvertiert, Sonderzeichen werden entfernt, `y` wird zu `i`, und wiederholte Buchstaben werden zusammengefasst. Wende es sowohl auf den gespeicherten Text als auch auf die gesuchte Phrase an.\n\nExample: Suchwert\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nEntfernt diakritische Zeichen aus dem Text.\n\nReturns: `String` Der Text ohne diakritische Zeichen.\n\nBuchstaben mit Akzenten werden durch ihre lateinischen Grundbuchstaben ersetzt, zum Beispiel `á` durch `a`.\n\nExample: Diakritische Zeichen entfernen\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nEntfernt HTML-Tags aus dem Text.\n\nReturns: `String` Der reine Text.\n\nNur die Tags werden entfernt; der Text dazwischen bleibt. HTML-Entitäten werden nicht dekodiert.\n\nExample: Reiner Text\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nFüllt den String links auf die Länge `max` auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die endgültige Länge. |\n| `c` | `String` | no | `' '` | Das Füllzeichen. |\n\nReturns: `String` Der aufgefüllte String.\n\nEin String, der bereits `max` Zeichen oder länger ist, wird unverändert zurückgegeben.\n\nExample: Führende Nullen\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nFüllt den String rechts auf die Länge `max` auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die endgültige Länge. |\n| `c` | `String` | no | `' '` | Das Füllzeichen. |\n\nReturns: `String` Der aufgefüllte String.\n\nEin String, der bereits `max` Zeichen oder länger ist, wird unverändert zurückgegeben.\n\nExample: Spalte mit fester Breite\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nPrüft, ob der String mit `text` beginnt, optional ohne Beachtung der Groß- und Kleinschreibung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Der zu suchende Text. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true`, um die Groß- und Kleinschreibung zu ignorieren, oder eine Startposition. |\n\nReturns: `Boolean`\n\nTotal.js ersetzt die native Methode. Ist `ignoreCase` auf `true` gesetzt, ignoriert der Vergleich die Groß- und Kleinschreibung; eine Zahl wird als Startposition verwendet. `String.endsWith(text, [ignoreCase])` funktioniert genauso am Ende des Strings.\n\nExample: Groß- und Kleinschreibung ignorieren\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nKonvertiert Markdown in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | Die oben beschriebenen Optionen. |\n\nReturns: `String` Das HTML.\n\nDas Ergebnis wird in `<div class=\"markdown markdown-container\">` eingeschlossen, außer `opt.wrap` ist `false`. Die meisten Funktionen sind standardmäßig aktiv, und du schaltest eine mit `false` ab: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Weitere Optionen: `linetag` (das Tag eines Absatzes, standardmäßig `'p'`), `prefix` (ein Präfix für generierte IDs), `custom` (eine Funktion, die jede Zeile ändert) und `html` (eine Funktion `function(html, type)`, die das generierte HTML ändert).\n\nExample: Markdown rendern\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Ohne Wrapper und Bilder\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nEntfernt abschließende Schrägstriche.\n\nReturns: `String` Der String ohne abschließende Schrägstriche.\n\nAlle `/`-Zeichen am Ende werden entfernt, ein einzelnes `/` bleibt jedoch erhalten, sodass `'/'` gleich `'/'` bleibt.\n\nExample: Eine URL bereinigen\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nErstellt ein JSON-Schema-Objekt aus einer Inline-Definition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Name des Schemas, der in `$id` verwendet wird. |\n| `url` | `String` | no | `CONF.url` | Die Basis-URL von `$id`. |\n\nReturns: `Object` Das JSON-Schema.\n\nDie Definition ist eine Liste von `name:type`-Paaren, getrennt durch Kommas oder Zeilenumbrüche. Ein `*` oder `!` vor dem Namen macht das Feld erforderlich. Typen: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` setzt eine maximale Länge, `[string]` erzeugt ein Array, `{draft|published}` ein Enum, und `@name` verwendet ein anderes Schema.\n\nDie `$id` wird aus `url` (standardmäßig `CONF.url`) und `name` gebildet.\n\nExample: Inline-Schema\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatiert die Zahl mit einem Tausendertrennzeichen und Dezimalstellen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Die Anzahl der Dezimalstellen. |\n| `separator` | `String` | no | `' '` | Das Tausendertrennzeichen. |\n| `separatorDecimal` | `String` | no | `'.'` | Das Dezimaltrennzeichen. |\n\nReturns: `String` Die formatierte Zahl.\n\nDas Standard-Tausendertrennzeichen ist ein Leerzeichen. Dezimalstellen werden auf `decimals` abgeschnitten (nicht gerundet) oder mit Nullen aufgefüllt. Das Dezimaltrennzeichen ist `.` oder `,`, wenn das Tausendertrennzeichen `.` ist. Du kannst das Trennzeichen auch zuerst übergeben: `format(',', 2)`.\n\nExample: Preise formatieren\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nWählt eine Wortform nach der Zahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Die Form für 0 oder alle Formen durch Kommas getrennt. |\n| `one` | `String` | no |  | Die Form für 1. |\n| `few` | `String` | no |  | Die Form für 2 bis 4. |\n| `other` | `String` | no |  | Die Form für andere Zahlen. |\n\nReturns: `String` Die gewählte Form.\n\n`zero` wird für 0 verwendet, `one` für 1, `few` für 2 bis 4 und `other` für den Rest. Ein `#` in der gewählten Form wird durch die Zahl ersetzt. Du kannst auch alle Formen als einen kommagetrennten String übergeben.\n\nExample: Anzahl der Elemente\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nKonvertiert die Zahl in einen links aufgefüllten String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die endgültige Länge. |\n| `c` | `String` | no | `'0'` | Das Füllzeichen. |\n\nReturns: `String` Die aufgefüllte Zahl.\n\nDas Standard-Füllzeichen ist `0`.\n\nExample: Rechnungsnummer\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nKonvertiert die Zahl in einen rechts aufgefüllten String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die endgültige Länge. |\n| `c` | `String` | no | `'0'` | Das Füllzeichen. |\n\nReturns: `String` Die aufgefüllte Zahl.\n\nDas Standard-Füllzeichen ist `0`.\n\nExample: Rechts auffüllen\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nRundet die Zahl auf eine Anzahl von Dezimalstellen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number` Die gerundete Zahl.\n\nOhne `precision` wird die Zahl auf eine Ganzzahl gerundet.\n\nExample: Runden\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nRundet die Zahl auf eine Anzahl von Dezimalstellen ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number` Die abgerundete Zahl.\n\nEs funktioniert wie `Math.floor()` mit Dezimalstellen.\n\nExample: Abrunden\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nGibt einen Wert aus einer Zuordnung von Zahlenbereichen zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Bereiche als Schlüssel und Ergebnisse als Werte. |\n| `otherwise` | `Object` | yes |  | Der Wert, wenn kein Bereich passt. |\n\nReturns: `Object` Der Wert des passenden Bereichs.\n\nDie Schlüssel von `condition` sind Bereiche: `'1-5'` (von 1 bis 5), `'10-'` (10 und mehr) oder `'-5'` (5 und weniger). Der Wert des ersten passenden Bereichs wird zurückgegeben, sonst `otherwise`.\n\nExample: Bewertungslabel\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nWendet eine als String geschriebene mathematische Operation an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Eine Zahl oder eine Operation wie `'-5'` oder `'+20%'`. |\n| `decimals` | `Number` | no |  | Das Ergebnis auf diese Dezimalstellen abrunden. |\n\nReturns: `Number` Das Ergebnis.\n\nEine Zahl wird addiert. Ein String beginnt mit einem Operator `+`, `-`, `*` oder `/`, gefolgt von einer Zahl, zum Beispiel `'+10'`. Mit `%` am Ende ist der Operand ein Prozentsatz der Zahl: `'+20%'` addiert 20 %. Mit `decimals` wird das Ergebnis auf diese Anzahl von Dezimalstellen abgerundet.\n\nExample: Operationen\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAddiert die Mehrwertsteuer zum Preis oder entfernt sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Der Mehrwertsteuersatz in Prozent. |\n| `decimals` | `Number` | no | `2` | Die Anzahl der Dezimalstellen. |\n| `includedVAT` | `Boolean` | no | `false` | Die Zahl enthält bereits die Mehrwertsteuer. |\n\nReturns: `Number` Der Preis.\n\nOhne `includedVAT` gibt die Methode den Preis mit Mehrwertsteuer zurück. Ist `includedVAT` auf `true` gesetzt, ist die Zahl ein Preis mit Mehrwertsteuer, und die Methode gibt den Preis ohne sie zurück. Das Ergebnis wird auf `decimals` gerundet.\n\nExample: Mit und ohne Mehrwertsteuer\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nZieht einen prozentualen Rabatt ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Der Rabatt in Prozent. |\n| `decimals` | `Number` | no | `2` | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number` Die rabattierte Zahl.\n\nDas Ergebnis wird auf `decimals` abgerundet.\n\nExample: Rabatt\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nFormatiert eine Anzahl von Bytes als lesbare Dateigröße.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Die Anzahl der Dezimalstellen. |\n| `type` | `String` | no |  | Die Einheit: `'bytes'`, `'KB'`, `'MB'`, `'GB'` oder `'TB'`. |\n\nReturns: `String` Die Größe mit der Einheit.\n\nOhne `type` wird die Einheit automatisch gewählt (`bytes`, `KB`, `MB`, `GB` oder `TB`). Mit `type` wird der Wert in diese Einheit konvertiert. Ohne `decimals` hat der Wert bis zu 2 Dezimalstellen.\n\nExample: Dateigröße\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nFührt eine asynchrone Funktion entsprechend oft aus und zählt dabei rückwärts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Die Funktion `function(number, next)`. |\n| `callback` | `Function` | no |  | Wird nach dem letzten Durchlauf aufgerufen. |\n\nReturns: `Number`\n\nDie Funktion erhält die aktuelle Zahl (vom Startwert bis hinunter zu 1) und `next`. Der nächste Durchlauf beginnt, nachdem du `next()` aufgerufen hast. Erreicht der Zähler null, wird `callback` aufgerufen.\n\nExample: Drei Durchläufe\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nGibt ein neues, um einen Zeitraum verschobenes Datum zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | Die Einheit, ein Ausdruck wie `'5 days'` oder Millisekunden. |\n| `value` | `Number` | no |  | Die Menge. |\n\nReturns: `Date` Ein neues Datum.\n\nÜbergib einen Typ und einen Wert (`add('days', 5)`) oder einen Ausdruck (`add('5 days')`). Typen: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, außerdem die Kurzformen `s`, `m`, `h`, `d`, `w`, `M`, `y`. Negative Werte verschieben zurück. Eine Zahl addiert Millisekunden. Das ursprüngliche Datum wird nicht geändert.\n\nExample: Datumsangaben verschieben\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nFormatiert das Datum als String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Das Format, zum Beispiel `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | Die Ressourcendatei mit übersetzten Monats- und Tagesnamen. |\n\nReturns: `String` Das formatierte Datum.\n\nOhne `format` wird das Datum als ISO-String in UTC zurückgegeben. Format-Tokens verwenden die lokale Zeit: `yyyy`, `yy`, `MM`, `M`, `MMM` (kurzer Monatsname), `MMMM` (Monatsname), `dd`, `d`, `ddd` (kurzer Tagesname), `dddd` (Tagesname), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (ISO-Woche), `a` (AM/PM). Monats- und Tagesnamen sind englisch; mit `resource` werden sie aus dieser Ressourcendatei gelesen.\n\nExample: Formate\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nGibt die Differenz zwischen zwei Datumsangaben in einer Einheit zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | Das Datum, mit dem verglichen wird. |\n| `type` | `String` | yes |  | Die Einheit. |\n\nReturns: `Number` Die Differenz.\n\nDie Differenz ist `this - date`, aufgerundet. Ohne `date` vergleicht die Methode mit dem aktuellen Zeitpunkt. Einheiten: `seconds`, `minutes`, `hours`, `days`, `months`, `years` und die Kurzformen `s`, `m`, `h`, `d`, `M`, `y`. Ein Monat zählt als 28 Tage. Eine unbekannte Einheit ergibt `NaN`.\n\nExample: Verbleibende Tage\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nVerschiebt das Datum um den Offset der lokalen Zeitzone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Millisekunden zurückgeben. |\n\nReturns: `Date|Number`\n\nDas Ergebnis zeigt die UTC-Zeit in den lokalen Feldern des Datums. Ist `ticks` auf `true` gesetzt, gibt die Methode Millisekunden statt eines Datums zurück.\n\nExample: UTC-Datum\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nGibt ein neues Datum zurück, dessen Teile aus einem String gesetzt werden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Die Datums- oder Zeitteile, zum Beispiel `'12:00'` oder `'2024-12-24 18:00'`. |\n\nReturns: `Date` Ein neues Datum.\n\nDer String kann ein Datum (`yyyy-MM-dd` oder `dd.MM.yyyy`) und eine Uhrzeit (`HH:mm` oder `HH:mm:ss`) enthalten. Nur die angegebenen Teile werden geändert; sie werden in UTC gesetzt.\n\nExample: Uhrzeit setzen\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nGibt ein neues, in eine Zeitzone konvertiertes Datum zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Der Name der IANA-Zeitzone. |\n\nReturns: `Date` Ein neues Datum.\n\n`timezone` ist ein IANA-Name wie `'Europe/Bratislava'`.\n\nExample: Uhrzeit in New York\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nGibt das erste passende Element oder `null` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Eine Funktion oder ein Eigenschaftsname. |\n| `value` | `Object` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Object` Das Element oder `null`.\n\n`cb` ist eine Funktion `function(item, index)` oder ein Eigenschaftsname, der mit `value` verglichen wird (`===`). Mit einem einzelnen Argument, das keine Funktion ist, werden die Elemente selbst verglichen.\n\nExample: Nach Eigenschaft und nach Funktion\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nGibt alle passenden Elemente zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Eine Funktion `function(item, index)` oder ein Eigenschaftsname. |\n| `value` | `Object` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Array` Die passenden Elemente.\n\nDie Argumente sind dieselben wie bei `Array.findItem()`. Das Ergebnis ist ein neues Array.\n\nExample: Filtern\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nGibt den Index des ersten passenden Elements oder `-1` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Eine Funktion oder ein Eigenschaftsname. |\n| `value` | `Object` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Number` Der Index oder `-1`.\n\nTotal.js ersetzt die native Methode, sodass sie auch einen Eigenschaftsnamen und einen Wert akzeptiert. Eine Funktion wird als `function(item, index)` aufgerufen. `Array.TfindIndex()` ist dieselbe Methode unter einem Namen, den andere Module nicht überschreiben.\n\nExample: Index nach Eigenschaft\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nEin Alias von `Array.findIndex()`, den andere Module nicht überschreiben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Eine Funktion oder ein Eigenschaftsname. |\n| `value` | `Object` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Number` Der Index oder `-1`.\n\nManche NPM-Module ersetzen `Array.prototype.findIndex` durch ihre eigene Version. `TfindIndex()` behält in diesem Fall das Verhalten von Total.js (Eigenschaftsname und Wert) bei. `findItem()` und `findValue()` verwenden es intern.\n\nExample: Sicherer Index\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nFindet ein Element und gibt eine seiner Eigenschaften zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Eine Funktion oder ein Eigenschaftsname. |\n| `value` | `Object` | yes |  | Der Wert der Eigenschaft. |\n| `path` | `String` | yes |  | Die zurückzugebende Eigenschaft. |\n| `def` | `Object` | no |  | Der Standardwert. |\n\nReturns: `Object` Der Wert der Eigenschaft oder `def`.\n\nDas Element wird wie bei `Array.findItem()` gefunden; dann wird seine Eigenschaft `path` zurückgegeben. Gibt es kein Element oder ist die Eigenschaft `null`/`undefined`, wird `def` zurückgegeben.\n\nExample: Name nach ID\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nGibt ein neues Array ohne die passenden Elemente zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | Eine Funktion, ein Eigenschaftsname oder ein Element. |\n| `value` | `Object` | no |  | Der Wert der Eigenschaft. |\n\nReturns: `Array` Ein neues Array.\n\nDie Argumente sind dieselben wie bei `Array.findItem()`. Das ursprüngliche Array wird nicht geändert, also weise das Ergebnis zu.\n\nExample: Elemente entfernen\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nGibt die ersten `count` Elemente zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die Anzahl der Elemente. |\n\nReturns: `Array` Ein neues Array.\n\nDas Ergebnis ist ein neues Array.\n\nExample: Die ersten drei\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nGibt die Elemente nach den ersten `count` Elementen zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die Anzahl der übersprungenen Elemente. |\n\nReturns: `Array` Ein neues Array.\n\nZusammen mit `Array.take()` ergibt es eine einfache Paginierung.\n\nExample: Paginierung\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nGibt das erste Element oder bei einem leeren Array `def` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Der Wert für ein leeres Array. |\n\nReturns: `Object`\n\nExample: Erstes Element\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nGibt das letzte Element oder bei einem leeren Array `def` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Der Wert für ein leeres Array. |\n\nReturns: `Object`\n\nExample: Letztes Element\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nSortiert das Array direkt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Die Eigenschaften, nach denen sortiert wird, oder `true` für absteigende primitive Werte. |\n| `desc` | `Boolean` | no | `false` | Absteigend sortieren. |\n\nReturns: `Array` Dasselbe Array.\n\n`sort` ist ein Eigenschaftsname mit einem optionalen Suffix `_asc` oder `_desc`, zum Beispiel `'name'` oder `'price_desc'`. Mehrere Eigenschaften werden durch Kommas getrennt (`'name_asc,price_desc'`), und verschachtelte Eigenschaften verwenden Punkte. Strings, Zahlen, boolesche Werte und Datumsangaben werden nach ihrem Typ verglichen. Ist `desc` auf `true` gesetzt, wird die Reihenfolge umgekehrt.\n\nOhne Argumente werden primitive Werte aufsteigend sortiert; `quicksort(true)` sortiert sie absteigend.\n\nExample: Objekte sortieren\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nErstellt aus dem Array ein Objekt (eine Lookup-Map).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Die Eigenschaft, die als Schlüssel verwendet wird. |\n\nReturns: `Object` Das Lookup-Objekt.\n\nMit `name` wird jedes Element unter dem Wert seiner Eigenschaft `name` gespeichert. Ohne wird jedes Element zu einem Schlüssel mit dem Wert `true`.\n\nExample: Lookups\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nTrimmt Strings und entfernt leere Elemente.\n\nReturns: `Array` Ein neues Array.\n\nStrings werden getrimmt, und Elemente, die nach dem Trimmen leer sind (oder `null`, `0`, `false` sind), werden entfernt. Es gibt ein neues Array zurück.\n\nExample: Eine Liste bereinigen\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nVerarbeitet Elemente nacheinander mit einer asynchronen Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | Die Funktion `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Wird nach dem letzten Element aufgerufen. |\n| `thread` | `Number|Boolean` | no | `1` | Die Anzahl paralleler Elemente oder `true`, um Elemente zu entfernen. |\n\nReturns: `Array` Dasselbe Array.\n\n`onItem(item, next, index)` wird für jedes Element aufgerufen; ruf `next()` auf, um fortzufahren. `callback` wird nach dem letzten Element aufgerufen. `thread` legt fest, wie viele Elemente gleichzeitig verarbeitet werden (standardmäßig 1). Ist `thread` auf `true` gesetzt, werden die Elemente während der Verarbeitung aus dem Array entfernt. Ruf `next('cancel')` auf, um abzubrechen; `callback` erhält dann `'cancel'`.\n\nExample: E-Mails nacheinander senden\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nFührt ein Array asynchroner Funktionen aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Die Anzahl paralleler Funktionen. |\n| `callback` | `Function` | no |  | Wird am Ende aufgerufen. |\n\nReturns: `Array` Dasselbe Array.\n\nJedes Element ist eine Funktion `function(next)`. Die Elemente werden beim Ausführen aus dem Array entfernt. `thread` legt fest, wie viele Funktionen gleichzeitig laufen (standardmäßig 1). `callback` wird nach der letzten Funktion aufgerufen oder mit `'cancel'`, wenn eine Funktion `next('cancel')` aufruft.\n\nExample: Eine Liste von Aufgaben\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nVerarbeitet das Array in Blöcken von `max` Elementen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Die Größe eines Blocks. |\n| `fn` | `Function` | yes |  | Die Funktion `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Wird nach dem letzten Block aufgerufen. |\n\nReturns: `Array` Dasselbe Array.\n\n`fn(items, next, beg, end)` erhält den nächsten Block; ruf `next()` auf, um mit dem folgenden Block fortzufahren. `callback` wird nach dem letzten Block aufgerufen.\n\nExample: In Blöcken einfügen\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nMischt das Array oder gibt ein zufälliges Element zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Ein zufälliges Element zurückgeben. |\n\nReturns: `Array|Object`\n\nOhne Argumente wird das Array direkt gemischt (Fisher-Yates) und zurückgegeben. Ist `item` auf `true` gesetzt, wird ein zufälliges Element zurückgegeben, und das Array wird nicht geändert.\n\nExample: Mischen und auswählen\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nParst CSV-Text in ein Array von Objekten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Das Spaltentrennzeichen. |\n\nReturns: `Object[]` Ein Objekt pro Zeile mit den Schlüsseln `a`, `b`, `c`...\n\nJede Zeile wird zu einem Objekt. Die Spalten werden mit Buchstaben benannt: die erste ist `a`, die zweite `b` und so weiter. Werte in doppelten Anführungszeichen dürfen das Trennzeichen und Zeilenumbrüche enthalten, und `\"\"` innerhalb von Anführungszeichen ist ein maskiertes Anführungszeichen. Alle Werte bleiben Strings, und eine leere Spalte hat keinen Schlüssel im Objekt. Eine Kopfzeile wird nicht erkannt, sie kommt also als erstes Objekt zurück.\n\nExample: Eine CSV-Datei lesen\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nLiest Betriebssystem, Browser und Gerätetyp aus einem User-Agent-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Ein Objekt statt eines Textes zurückgeben. |\n\nReturns: `String|Object` Die erkannten Namen oder `{ os, browser, device }`.\n\nOhne Argument gibt die Methode einen kurzen Text mit den erkannten Namen zurück, etwa `Mac Chrome` oder `iOS iPhone Mobile Safari`. Ist `structured` auf `true` gesetzt, gibt sie ein Objekt `{ os, browser, device }` zurück, wobei `device` den Wert `desktop`, `mobile`, `tablet` oder `tv` hat. Ein leerer String gibt einen leeren String zurück.\n\nExample: Den Client erkennen\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nParst `application/x-www-form-urlencoded`-Text in ein Objekt.\n\nReturns: `Object` Die geparsten Schlüssel und Werte.\n\nDer Text sieht aus wie ein Query String: `key=value&key2=value2`. `+` wird zu einem Leerzeichen, und `%xx`-Sequenzen werden dekodiert. Alle Werte bleiben Strings; ein wiederholter Schlüssel verbindet seine Werte mit einem Komma. Schlüssel dürfen nur Buchstaben, Ziffern und `-`, `_`, `.`, `[`, `]` enthalten, und das Parsen stoppt beim ersten anderen Zeichen in einem Schlüssel. Die Anzahl der Schlüssel ist durch `CONF.default_request_maxkeys` begrenzt und die Länge eines Schlüssels durch `CONF.default_request_maxkey`.\n\nExample: Einen Formular-Body parsen\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nParst XML in ein flaches Objekt aus Pfaden und Werten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Sonderzeichen in den Schlüsseln durch `_` ersetzen. |\n\nReturns: `Object` Das flache Objekt aus Pfaden.\n\nJedes Element mit Text wird zu einem Schlüssel aus den mit Punkten verbundenen Elementnamen, zum Beispiel `book.title`. Ein wiederholtes Element ergibt ein Array von Werten. Die Attribute eines Elements werden als Objekt unter dem Pfad gefolgt von `[]` gespeichert. `CDATA`-Abschnitte werden als Text gelesen, und Kommentare werden übersprungen. Ist `replace` auf `true` gesetzt, werden die Zeichen `[`, `]`, `:`, `.` und `_` in den Schlüsseln durch `_` ersetzt.\n\nExample: Einen XML-Feed lesen\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nParst HTML in einen Baum von Elementen, den du durchsuchen und ändern kannst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Den Textinhalt trimmen. |\n\nReturns: `HTMLElement` Das Wurzelelement des geparsten Dokuments.\n\nDie Methode verwendet den eingebauten HTML-Parser und gibt das Wurzelelement zurück. Elemente haben `tagName`, `attrs`, `children` und `parentNode` sowie die Methoden `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` und `html([formatted])`. Ist `trim` auf `true` gesetzt, wird der Text in den Elementen getrimmt.\n\nExample: HTML lesen und ändern\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nSchneidet markierte Blöcke aus einem Text und gibt ihren Inhalt nach Namen zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | Der Name und das öffnende Tag jedes Blocks. |\n\nReturns: `Object` Der Inhalt jedes gefundenen Blocks.\n\n`tags` ordnet einem Namen ein öffnendes Tag zu, zum Beispiel `{ js: '<script>', css: '<style>' }`. Für jeden Namen wird der Inhalt zwischen dem öffnenden Tag und seinem schließenden Tag zurückgegeben (verschachtelte Tags derselben Art werden mitgezählt). Ein fehlendes Tag ergibt keinen Schlüssel. Total.js verwendet es, um den `<script total>`-Teil von `.html`-Plugins und -Komponenten zu lesen.\n\nExample: Eine Komponentendatei aufteilen\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nParst die Spaltenausgabe eines Terminalbefehls Zeile für Zeile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Spaltennamen oder reguläre Ausdrücke der Spalten. |\n| `fn` | `Function` | yes |  | Wird für jede Zeile als `fn(values, index, count, line)` aufgerufen. |\n| `skip` | `Number` | no | `0` | Die Anzahl der zu überspringenden Zeilen. |\n| `take` | `Number` | no | `all` | Die Anzahl der zu lesenden Zeilen. |\n\nReturns: `String` Derselbe String.\n\nMit `fields` ist die erste nicht leere Zeile (von den ersten drei) die Kopfzeile. Jedes Feld ist ein Spaltenname (`String`) oder ein `RegExp`, der die Spalte in der Kopfzeile findet, und `fn` erhält für jede folgende Zeile die Werte dieser Spalten. Ohne `fields` wird jede Zeile in Wörter aufgeteilt, und `fn` erhält das Array der Wörter. `fn(values, index, count, line)` erhält die Werte, den Index der geparsten Zeile, den Endindex und die Zeilennummer. `skip` und `take` begrenzen die Zeilen. Die Methode gibt den String selbst zurück.\n\nExample: Die Ausgabe von df lesen\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nParst Text im Konfigurationsformat von Total.js in ein Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Standardwerte, die in das Ergebnis kopiert werden. |\n| `onerror` | `Function` | no |  | Wird als `onerror(err, line)` aufgerufen, wenn ein `object`- oder `eval`-Wert fehlschlägt. |\n\nReturns: `Object` Die geparsten Werte.\n\nJede Zeile ist `key : value`, und Zeilen, die mit `#` oder `//` beginnen, werden übersprungen. Der Wert beginnt zwei Zeichen nach dem ersten `:`, also schreib ein Leerzeichen nach dem Doppelpunkt. Ein Typ in Klammern nach dem Schlüssel konvertiert den Wert: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (kommagetrennt), `(json)`, `(object)` oder `(eval)` (als JavaScript ausgewertet), `(date)`, `(env)` (eine Umgebungsvariable), `(config)` (ein anderer `CONF`-Schlüssel) und `(random)` (ein zufälliger String der angegebenen Länge). `def` liefert Standardwerte. `onerror(err, line)` behandelt einen Wert, der nicht ausgewertet werden kann; ohne es wirft die Methode einen Fehler.\n\nExample: Einen Konfigurationstext parsen\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nMacht aus einem Text wie `5 minutes` ein Datum in der Zukunft.\n\nReturns: `Date` Das aktuelle Datum plus die angegebene Zeit.\n\nDer Text wird als Paare aus einer Zahl und einer Einheit gelesen, getrennt durch Leerzeichen, zum Beispiel `1 day 12 hours`. Jedes Paar wird mit `Date.add()` zum aktuellen Datum addiert, daher funktionieren dieselben Einheiten (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Ein Paar mit der Zahl `0` wird ignoriert.\n\nExample: Ablauf eines Cookies\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nLiest die Informationen, die in einem mit `UID()` erstellten Bezeichner gespeichert sind.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nDas Ergebnis hat `version` (das letzte Zeichen der UID), `date` (wann sie erstellt wurde), `century`, `index` (den Zähler), `hash` und `valid`. Für die zufällige Version `r` (`CONF.default_uid = 'r'`) hat das Ergebnis kein Datum, und Bezeichner werden mit `String.isUID()` validiert.\n\nExample: Wann wurde ein Datensatz erstellt\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nFindet die erste Dezimalzahl in einem Text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Der Wert, der zurückgegeben wird, wenn keine Zahl gefunden wird. |\n\nReturns: `Number` Die gefundene Zahl.\n\nAnders als bei `String.parseFloat()` darf der Text andere Zeichen enthalten: Die erste Gruppe aus Ziffern, Punkten und Kommas wird verwendet, und Kommas werden zu Punkten. Ein führendes `-` macht sie negativ. Ohne Zahl gibt die Methode `def` zurück.\n\nExample: Preis aus einem Label\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nPrüft, ob der String eine GUID (UUID) ist.\n\nReturns: `Boolean`\n\nDer String muss 36 Zeichen in der Form `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx` haben, wobei `M` eine Version von 1 bis 5 ist. Groß- und Kleinbuchstaben werden akzeptiert.\n\nExample: Eine UUID validieren\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nPrüft, ob der String ein Datum im JSON-Format (ISO 8601 UTC) ist.\n\nReturns: `Boolean`\n\nDie Methode prüft die Form des Textes, etwa `2024-05-01T10:30:00.000Z`: die Länge, das `T`, die Bindestriche und Doppelpunkte und das abschließende `Z`. Sie prüft nicht, ob das Datum existiert.\n\nExample: Datumsangaben wiederherstellen\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nPrüft, ob der String nur Ziffern enthält.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Ein Dezimaltrennzeichen erlauben. |\n\nReturns: `Boolean`\n\nIst `decimal` auf `true` gesetzt, ist zusätzlich ein `.` oder `,` erlaubt. Vorzeichen, Leerzeichen und Exponenten werden nicht akzeptiert, und ein leerer String gibt `false` zurück.\n\nExample: Benutzereingaben prüfen\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nPrüft, ob der String `true` oder `false` ist.\n\nReturns: `Boolean`\n\nDer Vergleich ignoriert die Groß- und Kleinschreibung. Andere Werte wie `1` oder `on` geben `false` zurück; `String.parseBoolean()` liest diese.\n\nExample: Einen Query-Wert prüfen\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nPrüft, ob der String wie eine Postleitzahl (ZIP) aussieht.\n\nReturns: `Boolean`\n\nDer String wird mit `DEF.validators.zip` geprüft, standardmäßig 3 bis 20 Buchstaben, Ziffern, Leerzeichen oder Bindestriche. Ändere `DEF.validators.zip`, um deine eigene Regel zu verwenden.\n\nExample: Eine Postleitzahl validieren\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nPrüft, ob der String ein HTML-Tag enthält.\n\nReturns: `Boolean`\n\nDer Test ist einfach: Er gibt `true` zurück, wenn der Text `<` enthält, auf das später `>` folgt. Verwende ihn, um HTML in reinen Textfeldern abzulehnen.\n\nExample: HTML ablehnen\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nPrüft, ob der String einen Text in Anführungszeichen oder ein SQL-Schlüsselwort enthält.\n\nReturns: `Boolean`\n\nDie Methode gibt `true` für Text in einfachen Anführungszeichen oder für die großgeschriebenen Wörter `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` und `UNION` zurück. Es ist eine grobe Prüfung; verwende in deinen Abfragen trotzdem Parameter.\n\nExample: Eine Suchphrase prüfen\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nPrüft, ob der String Base64-kodiert ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Ein Data-URI-Präfix akzeptieren. |\n\nReturns: `Boolean`\n\nDie Länge muss durch 4 teilbar sein, und der Text darf nur Base64-Zeichen enthalten. Ist `data` auf `true` gesetzt, wird eine Data-URI wie `data:image/png;base64,...` akzeptiert, und nur die Länge des kodierten Teils wird geprüft.\n\nExample: Einen Upload prüfen\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nSchreibt Base64-Daten in eine Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Der Pfad der Datei. |\n| `callback` | `Function` | no |  | Wird als `callback(err)` aufgerufen, wenn die Datei geschrieben ist. |\n\nReturns: `String` Derselbe String.\n\nEin Data-URI-Präfix (alles bis zum ersten Komma) wird entfernt, und der Rest wird dekodiert und mit `fs.writeFile()` geschrieben. Die Methode gibt den String selbst zurück; das Ergebnis des Schreibens kommt in `callback(err)` an.\n\nExample: Ein hochgeladenes Bild speichern\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDekodiert Base64-Daten in einen `Buffer`.\n\nReturns: `Buffer` Die dekodierten Daten.\n\nEin Data-URI-Präfix (alles bis zum ersten Komma) wird vor dem Dekodieren entfernt.\n\nExample: Eine Data-URI dekodieren\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nGibt den Content-Type einer Data-URI zurück.\n\nReturns: `String` Der Content-Type, zum Beispiel `image/png`.\n\nDer Text zwischen `data:` und dem ersten `;` wird zurückgegeben. Ein String ohne `;` gibt einen leeren String zurück.\n\nExample: Den Typ eines Uploads prüfen\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nBerechnet die CRC32-Prüfsumme des Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Eine vorzeichenlose Zahl zurückgeben. |\n\nReturns: `Number` Die Prüfsumme.\n\nDas Ergebnis ist eine vorzeichenbehaftete 32-Bit-Zahl oder eine vorzeichenlose, wenn `unsigned` gleich `true` ist. `String.hash('crc32')` und `String.hash('crc32unsigned')` liefern dieselben Ergebnisse.\n\nExample: Prüfsumme eines Textes\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nErstellt einen SHA-1-Hash des Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String` Der Hash als Hex.\n\nDer `salt` wird vor dem Hashen an den String angehängt.\n\nExample: SHA-1-Hash\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nErstellt einen SHA-512-Hash des Strings.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text, der vor dem Hashen angehängt wird. |\n\nReturns: `String` Der Hash als Hex.\n\nDer `salt` wird vor dem Hashen an den String angehängt.\n\nExample: Ein Token hashen\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nErstellt eine kurze ID aus dem String.\n\nReturns: `String` Die ID.\n\nDie ID ist ein schneller, vorzeichenloser Hash des Strings zur Basis 36. Derselbe String ergibt immer dieselbe ID. Es ist kein kryptografischer Hash.\n\nExample: ID für einen Cache-Schlüssel\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nFügt dem String eine schnelle Prüfsumme hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Ein Secret, das in die Prüfsumme eingemischt wird. |\n\nReturns: `String` Der String mit der Prüfsumme.\n\nDas Ergebnis ist der String, ein Bindestrich und ein Hash zur Basis 36 aus dem String mit `key`. Um einen Wert zu prüfen, signiere den Teil vor dem letzten Bindestrich erneut und vergleiche. Es ist eine schnelle Prüfsumme, keine kryptografische Signatur.\n\nExample: Einen Wert signieren und prüfen\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nSchützt einen Bezeichner mit einer Prüfsumme.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Das Secret. |\n\nReturns: `String` Der geschützte Bezeichner.\n\nDas Ergebnis ist `x`, eine Prüfsumme und `x`, gefolgt vom ursprünglichen Wert, sodass der Wert lesbar bleibt, aber ohne den Schlüssel nicht verändert werden kann. Die Prüfsumme verwendet `key` (standardmäßig `CONF.secret`) und `CONF.secret_uid`. Lies ihn mit `String.decrypt_uid()` zurück. Dieselbe Funktion für Zahlen ist `U.encrypt_uid(value, [key])`.\n\nExample: Geschützte ID in einem Link\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nLiest einen mit `String.encrypt_uid()` geschützten Bezeichner.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Das für `encrypt_uid()` verwendete Secret. |\n\nReturns: `String|Number` Der ursprüngliche Wert oder `null`, wenn die Prüfsumme falsch ist.\n\nDie Prüfsumme wird mit `key` (standardmäßig `CONF.secret`) erneut erstellt. Stimmt sie überein, wird der ursprüngliche Wert zurückgegeben, sonst `null`. Ein aus einer Zahl erstellter Wert kommt als Zahl zurück.\n\nExample: Einen Link prüfen\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nBereinigt einen Personennamen: entfernt andere Zeichen und schreibt jedes Wort groß.\n\nReturns: `String` Der bereinigte Name.\n\nZiffern und ASCII-Satzzeichen werden entfernt, Leerzeichen bleiben erhalten, und der erste Buchstabe jedes Wortes wird großgeschrieben. Buchstaben mit diakritischen Zeichen bleiben erhalten. Abschließende Leerzeichen werden entfernt, führende und wiederholte jedoch nicht, also trimme die Eingabe zuerst.\n\nExample: Einen Namen aus einem Formular bereinigen\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nMaskiert Zeichen außerhalb des druckbaren ASCII-Bereichs als `\\uXXXX`.\n\nReturns: `String` Der maskierte String.\n\nZeichen mit einem Code unter 32 oder über 126 werden als `\\u` und vier Hex-Ziffern geschrieben. `String.fromUnicode()` kehrt das um.\n\nExample: Einen Text maskieren\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nWandelt `\\uXXXX`-Escapes zurück in Zeichen.\n\nReturns: `String` Der demaskierte String.\n\nJedes `\\u`, gefolgt von vier Hex-Ziffern, wird durch das Zeichen ersetzt. Es kehrt `String.toUnicode()` um.\n\nExample: Einen Text demaskieren\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nPrüft, ob der String mit einem Text endet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Der zu suchende Text. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true`, um die Groß- und Kleinschreibung zu ignorieren, oder ein Offset vom Ende. |\n\nReturns: `Boolean`\n\nTotal.js ersetzt die native Methode. Ist `ignoreCase` auf `true` gesetzt, wird die Groß- und Kleinschreibung ignoriert. Eine Zahl anstelle von `ignoreCase` prüft den Text so viele Zeichen vor dem Ende.\n\nExample: Eine Dateiendung prüfen\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nErsetzt das erste Vorkommen eines Textes, ohne reguläre Ausdrücke.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | Der zu ersetzende Text. |\n| `text` | `String` | yes |  | Der neue Text. |\n\nReturns: `String` Der neue String.\n\n`find` ist reiner Text, daher haben Zeichen wie `$` oder `.` weder darin noch in `text` eine besondere Bedeutung. Wird `find` nicht gefunden, wird der String unverändert zurückgegeben.\n\nExample: Einen Preis in ein Template einfügen\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nFügt einen Wert an einer Position in den String ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | Die Position. |\n| `value` | `Object` | yes |  | Der einzufügende Wert. |\n\nReturns: `String` Der neue String.\n\nDer Wert wird mit `toString()` in einen String konvertiert.\n\nExample: Einen Code formatieren\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nFügt am Anfang des Strings ein Zeichen mehrmals hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Wie viele Zeichen hinzugefügt werden. |\n| `char` | `String` | no | `' '` | Das Zeichen. |\n\nReturns: `String` Der eingerückte String.\n\nAnders als bei `String.padLeft()` werden die Zeichen immer hinzugefügt, unabhängig von der Länge des Strings.\n\nExample: Eine Zeile einrücken\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nWählt eine Wortform nach der Zahl im String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Die Form für 0 oder alle Formen durch Kommas getrennt. |\n| `one` | `String` | no |  | Die Form für 1. |\n| `few` | `String` | no |  | Die Form für 2 bis 4. |\n| `other` | `String` | no |  | Die Form für andere Zahlen. |\n\nReturns: `String` Die gewählte Form.\n\nDer String wird mit `String.parseInt()` gelesen und an `Number.pluralize()` übergeben, daher sind die Regeln und der Platzhalter `#` dieselben.\n\nExample: Anzahl aus einer Query\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nErsetzt `[key]`-Platzhalter durch Konfigurationswerte.\n\nReturns: `String` Der String mit den Werten.\n\nJedes `[key]` (Buchstaben, Ziffern und `_`) wird durch `CONF[key]` ersetzt; ein fehlender Schlüssel ergibt einen leeren String.\n\nExample: Eine URL aus der Konfiguration bauen\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nFindet Blöcke in einem String und übergibt jeden an einen Callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | Der Start-Begrenzer oder das Trennzeichen, wenn `end` fehlt. |\n| `end` | `String` | no |  | Der End-Begrenzer. |\n| `callback` | `Function` | yes |  | Wird als `callback(value, index)` aufgerufen; gib `false` zurück, um abzubrechen. |\n| `skip` | `Number` | no | `0` | Die Anzahl der zu überspringenden Blöcke. |\n\nReturns: `undefined`\n\nMit `beg` und `end` wird jeder Block übergeben, der mit `beg` beginnt und mit `end` endet, einschließlich der Begrenzer. Ohne `end` wird der String nach jedem `beg` aufgeteilt, und jeder Teil endet mit `beg`. `callback(value, index)` kann `false` zurückgeben, um abzubrechen. `skip` überspringt die ersten Blöcke.\n\nExample: Elemente aus XML lesen\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nRundet die Zahl auf eine Anzahl von Dezimalstellen und gibt eine Zahl zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Die Anzahl der Dezimalstellen. |\n\nReturns: `Number` Die gerundete Zahl.\n\nDasselbe wie `+number.toFixed(decimals)`: Anders als bei `toFixed()` ist das Ergebnis eine Zahl, kein String.\n\nExample: Einen Preis runden\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatiert die Zahl mit einem Währungsformatierer aus `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | Der Schlüssel in `DEF.currencies`. |\n| `a` | `Object` | no |  | Wird an den Formatierer übergeben, wie `b` und `c`. |\n\nReturns: `String` Der formatierte Preis.\n\n`DEF.currencies` ist standardmäßig leer; füge für jeden benötigten Währungscode eine Funktion `function(value, a, b, c)` hinzu und `default` für Aufrufe ohne Code. Die zusätzlichen Argumente werden an sie übergeben. Ohne Formatierer wird die Zahl mit `Number.format(2)` formatiert.\n\nExample: Währungen registrieren und verwenden\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nKonvertiert die Zahl in hexadezimale Großbuchstaben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Die minimale Länge. |\n\nReturns: `String` Der Hex-Wert.\n\nDas Ergebnis wird mit führenden Nullen auf `length` Zeichen aufgefüllt.\n\nExample: Farbkomponente\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nErstellt ein Datum aus einem Zeitstempel in Millisekunden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Zu addierende Millisekunden. |\n\nReturns: `Date` Das Datum.\n\n`plus` Millisekunden werden zur Zahl addiert, bevor das Datum erstellt wird.\n\nExample: Datum aus einem Zeitstempel\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nKonvertiert Grad in Radiant.\n\nReturns: `Number` Der Winkel in Radiant.\n\nNur definiert, wenn `Number.prototype.toRad` noch nicht existiert.\n\nExample: Entfernung zwischen zwei GPS-Punkten\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nGibt das Datum selbst zurück.\n\nReturns: `Date` Dasselbe Datum.\n\nDamit kannst du `parseDate()` auf einem Wert aufrufen, der ein String, eine Zahl oder ein Datum sein kann, ohne vorher seinen Typ zu prüfen.\n\nExample: Wert unbekannten Typs\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Prototipos","summary":"Métodos de String, Number, Date y Array añadidos por Total.js 4.","markdown":"---\ntitle: Prototipos\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototipos\n\n> Métodos de String, Number, Date y Array añadidos por Total.js 4.\n\nMétodos que Total.js 4 añade a `String`, `Number`, `Date` y `Array`. La guía [Prototipos](../../guides/prototypes/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nReemplaza los marcadores de posición indexados `{0}`, `{1}`... por los argumentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | El valor para `{0}`. Pueden seguir cualquier número de argumentos. |\n\nReturns: `String` La cadena formateada.\n\nCada `{n}` se reemplaza por el argumento del índice `n`. Un argumento `null` o `undefined` da una cadena vacía. Para marcadores con nombre usa `String.args()`.\n\nExample: Marcadores indexados\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nReemplaza los marcadores con nombre `{key}` o `{{key}}` por valores de un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Los valores. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (codificación URL), `'html'`, `'json'` o una función `function(value, key)`. |\n| `def` | `String` | no |  | El texto para un valor que falta. Se ignora cuando `encode` es una cadena. |\n\nReturns: `String` La cadena con los valores.\n\nLas claves pueden contener letras, números, `_`, `$`, `.` y `-`. Un valor que falta conserva el marcador, o usa `def` cuando lo defines.\n\nEl argumento `encode` cambia cómo se escriben los valores: `true` los codifica con `encodeURIComponent()`, `'html'` codifica entidades HTML, `'json'` escribe `JSON.stringify(value)` y una función `function(value, key)` devuelve el texto ella misma. `String.arg()` es un alias.\n\nExample: Marcadores con nombre\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: Codificación HTML\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: Un valor predeterminado para los valores que faltan\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nCrea un slug apto para URL a partir del texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | La longitud máxima. |\n\nReturns: `String` El slug.\n\nEl texto se recorta, se pasa a minúsculas y se convierte a ASCII (sin diacríticos). Los espacios y la puntuación se convierten en un único `-`; se elimina el `-` final. El resultado se corta en `max` caracteres.\n\nCuando el texto no tiene caracteres latinos utilizables (por ejemplo, chino o cirílico), el método devuelve en su lugar un hash corto creado a partir del texto.\n\nExample: Slug a partir de un título\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nCorta el texto a una longitud máxima y añade puntos suspensivos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | La longitud máxima del resultado. |\n| `chars` | `String` | no | `'...'` | El texto que se añade a una cadena cortada. |\n\nReturns: `String` El texto acortado.\n\nCuando el texto es más largo que `length`, se corta de modo que el resultado con `chars` tenga exactamente `length` caracteres. Un texto más corto se devuelve sin cambios.\n\nExample: Acortar una descripción\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nPone en mayúscula la primera letra de cada palabra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Poner en mayúscula solo la primera letra. |\n\nReturns: `String` El texto con mayúsculas iniciales.\n\nEl texto se pasa a minúsculas y cada letra después de un espacio, una tabulación o un salto de línea se pone en mayúscula. Con `first` en `true`, solo se pone en mayúscula la primera letra de todo el texto.\n\nExample: Palabras y primera letra\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nConvierte la cadena entera en un número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor que se devuelve cuando la cadena no es un número. |\n\nReturns: `Number` El número, o `def`.\n\nLa cadena se recorta y se convierte con el operador unario `+`, así que toda la cadena debe ser un número: `'12px'` no es un número y da `def`. Para leer un número de un texto más largo, usa `String.parseInt2()`.\n\nExample: Parámetro de la query string\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nLee el primer entero que encuentra en el texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor que se devuelve cuando el texto no contiene ningún número. |\n\nReturns: `Number` El número, o `def`.\n\nA diferencia de `String.parseInt()`, el número puede estar rodeado de otro texto. Se conserva un `-` inicial. `String.parseFloat2()` funciona igual para números decimales (se acepta `,` como separador decimal).\n\nExample: Número dentro de un texto\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nConvierte la cadena en un número decimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor que se devuelve cuando la cadena no es un número. |\n\nReturns: `Number` El número, o `def`.\n\nLa cadena se recorta y el separador decimal `,` se reemplaza por `.`. Toda la cadena debe ser un número; si no, se devuelve `def`.\n\nExample: Coma decimal\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nConvierte `true`, `1` u `on` en `true`.\n\nReturns: `Boolean`\n\nLa comparación no distingue mayúsculas de minúsculas. Cualquier otro valor da `false`.\n\nExample: Valor de una casilla de verificación\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nConvierte la cadena en un `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | El formato de la entrada, por ejemplo `'dd/MM/yyyy'`. |\n\nReturns: `Date` La fecha analizada.\n\nSin `format`, el método lee cadenas ISO (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` y cualquier valor que entienda `new Date()`. Una parte de la fecha que falta usa la de hoy.\n\nCon `format`, los dígitos de la cadena se leen en el orden de las letras del formato (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). Un `pm` en el texto suma 12 horas.\n\nExample: Analizar fechas\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nAnaliza JSON sin lanzar una excepción.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convertir las cadenas de fecha ISO en fechas. |\n\nReturns: `Object` El valor analizado, o `undefined` si el JSON no es válido.\n\nUn JSON no válido devuelve `undefined` en lugar de un error. Con `date` en `true`, las cadenas de fecha ISO se convierten en objetos `Date`.\n\nExample: Análisis seguro\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nAnaliza líneas `KEY=value` (el formato `.env`) y las convierte en un objeto.\n\nReturns: `Object` Las claves y sus valores como cadenas.\n\nSe omiten las líneas vacías y las que empiezan con `#` o `//`. Los valores entre comillas dobles o simples pierden las comillas, y `\\n` se convierte en un salto de línea. Los valores sin comillas se recortan.\n\nExample: Leer un archivo .env\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nComprueba si la cadena es una dirección de correo electrónico.\n\nReturns: `Boolean`\n\nLa prueba usa la expresión regular `DEF.validators.email`, así que puedes reemplazarla. Las cadenas de 4 caracteres o menos siempre son `false`.\n\nExample: Validar la entrada\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nComprueba si la cadena es un número de teléfono.\n\nReturns: `Boolean`\n\nLa prueba usa la expresión regular `DEF.validators.phone`. Las cadenas de menos de 6 caracteres siempre son `false`.\n\nExample: Número de teléfono\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nComprueba si la cadena es una dirección URL.\n\nReturns: `Boolean`\n\nLa prueba usa la expresión regular `DEF.validators.url`. Las cadenas de 7 caracteres o menos siempre son `false`.\n\nExample: Dirección URL\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nComprueba si la cadena es un identificador válido creado por `UID()`.\n\nReturns: `Boolean`\n\nEl método prueba el formato con `DEF.validators.uid` y después la suma de control que `UID()` escribe en cada identificador, así que no se acepta una cadena aleatoria con los caracteres correctos.\n\nExample: Validar un id de la URL\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nComprueba si la cadena parece JSON.\n\nReturns: `Boolean`\n\nSolo se prueban el primer y el último carácter que no son espacios: `{...}`, `[...]`, `\"...\"` o un número. El contenido no se analiza; para eso usa `String.parseJSON()`.\n\nExample: Prueba rápida\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nCrea un hash de la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | El algoritmo, o `true` para un hash numérico sin signo. |\n| `salt` | `String` | no |  | Texto que se añade antes de calcular el hash. |\n\nReturns: `String|Number` Una cadena hexadecimal para md5/sha*; si no, un número.\n\n`type` elige el algoritmo: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (cadenas hexadecimales), `'crc32'` o `'crc32unsigned'` (números). Sin tipo, el método devuelve un hash numérico rápido de 32 bits; `true` lo hace sin signo. La `salt` se añade a la cadena antes de calcular el hash.\n\nExample: Distintos hashes\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nDevuelve el hash MD5 como cadena hexadecimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texto que se añade antes de calcular el hash. |\n\nReturns: `String` Una cadena hexadecimal de 32 caracteres.\n\nLa `salt` se añade a la cadena antes de calcular el hash. Úsalo para sumas de control y claves de caché, no para contraseñas.\n\nExample: Clave de caché\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nDevuelve el hash SHA-256 como cadena hexadecimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texto que se añade antes de calcular el hash. |\n\nReturns: `String` Una cadena hexadecimal de 64 caracteres.\n\nLa `salt` se añade a la cadena antes de calcular el hash. `String.sha1([salt])` y `String.sha512([salt])` funcionan igual con los otros algoritmos.\n\nExample: Hash con sal\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nCodifica los caracteres especiales de HTML.\n\nReturns: `String` El texto codificado.\n\nReemplaza `<`, `>`, `\"`, `'` y `&` por entidades HTML, así el texto se puede escribir de forma segura en HTML.\n\nExample: Escapar la entrada del usuario\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDecodifica entidades HTML y las convierte de nuevo en caracteres.\n\nReturns: `String` El texto decodificado.\n\nSe convierten las entidades con nombre y las numéricas (`&#65;`, `&#x41;`). Es lo contrario de `String.encode()`.\n\nExample: Decodificar\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nCifra la cadena con una clave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave de cifrado. |\n| `isUnique` | `Boolean` | no | `false` | Hacer que cada resultado sea distinto. |\n| `secret` | `String` | no | `CONF.secret` | Un secreto adicional. |\n\nReturns: `String` La cadena cifrada.\n\nCon `isUnique` en `true`, cada llamada da un resultado distinto para la misma entrada. El resultado contiene una suma de control creada a partir de `secret` (por defecto `CONF.secret`) y la clave, que `String.decrypt()` comprueba. Úsalo para tokens y URLs, no para guardar contraseñas.\n\nExample: Cifrar un token\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nDescifra una cadena creada por `String.encrypt()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave de cifrado. |\n| `secret` | `String` | no | `CONF.secret` | El secreto adicional. |\n\nReturns: `String` La cadena original, o `null`.\n\nUsa la misma `key` y el mismo `secret` que para el cifrado. Una clave incorrecta, un secreto incorrecto o una cadena modificada devuelven `null`.\n\nExample: Descifrar un token\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrae palabras clave del texto, ordenadas por frecuencia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Normalizar las palabras para la búsqueda. |\n| `alternative` | `Boolean` | no | `false` | Acortar cada palabra al 80 % de su longitud. |\n| `max_count` | `Number` | no | `200` | El número máximo de palabras leídas. |\n| `max_length` | `Number` | no | `20` | La longitud máxima de una palabra. |\n| `min_length` | `Number` | no | `2` | La longitud mínima de una palabra. |\n\nReturns: `String[]` Palabras únicas, primero las más frecuentes.\n\nCon `forSearch` (por defecto `true`) el texto se convierte a ASCII y la `y` se convierte en `i`, lo que hace la búsqueda más tolerante. Con `alternative`, cada palabra se acorta al 80 % de su longitud. Se omiten las palabras más cortas que `min_length` o más largas que `max_length`. `String.toKeywords()` es un alias.\n\nExample: Palabras clave para un índice de búsqueda\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormaliza el texto para una búsqueda de texto completo.\n\nReturns: `String` El texto normalizado.\n\nEl texto se pasa a minúsculas y se convierte a ASCII, se eliminan los caracteres especiales, la `y` se convierte en `i` y se unen las letras repetidas. Aplícalo tanto al texto guardado como a la frase buscada.\n\nExample: Valor de búsqueda\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nElimina los diacríticos del texto.\n\nReturns: `String` El texto sin diacríticos.\n\nLas letras acentuadas se reemplazan por sus letras latinas básicas, por ejemplo `á` por `a`.\n\nExample: Eliminar diacríticos\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nElimina las etiquetas HTML del texto.\n\nReturns: `String` El texto plano.\n\nSolo se eliminan las etiquetas; el texto entre ellas se mantiene. Las entidades HTML no se decodifican.\n\nExample: Texto plano\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nRellena la cadena por la izquierda hasta la longitud `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud final. |\n| `c` | `String` | no | `' '` | El carácter de relleno. |\n\nReturns: `String` La cadena rellenada.\n\nUna cadena que ya tiene `max` caracteres o más se devuelve sin cambios.\n\nExample: Ceros a la izquierda\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nRellena la cadena por la derecha hasta la longitud `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud final. |\n| `c` | `String` | no | `' '` | El carácter de relleno. |\n\nReturns: `String` La cadena rellenada.\n\nUna cadena que ya tiene `max` caracteres o más se devuelve sin cambios.\n\nExample: Columna de ancho fijo\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nComprueba si la cadena empieza con `text`, opcionalmente sin distinguir mayúsculas de minúsculas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | El texto que se busca. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true` para no distinguir mayúsculas de minúsculas, o una posición inicial. |\n\nReturns: `Boolean`\n\nTotal.js reemplaza el método nativo. Con `ignoreCase` en `true`, la comparación no distingue mayúsculas de minúsculas; un número se usa como posición inicial. `String.endsWith(text, [ignoreCase])` funciona igual al final de la cadena.\n\nExample: Sin distinguir mayúsculas\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nConvierte Markdown a HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | Las opciones descritas arriba. |\n\nReturns: `String` El HTML.\n\nEl resultado se envuelve en `<div class=\"markdown markdown-container\">` salvo que `opt.wrap` sea `false`. La mayoría de las funciones están activadas por defecto y desactivas una con `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Otras opciones: `linetag` (la etiqueta de un párrafo, por defecto `'p'`), `prefix` (un prefijo para los ids generados), `custom` (una función que modifica cada línea) y `html` (una función `function(html, type)` que modifica el HTML generado).\n\nExample: Renderizar Markdown\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Sin envoltorio y sin imágenes\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nElimina las barras finales.\n\nReturns: `String` La cadena sin barras finales.\n\nSe eliminan todos los caracteres `/` del final, pero se conserva una sola `/`, así que `'/'` sigue siendo `'/'`.\n\nExample: Limpiar una URL\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nCrea un objeto de esquema JSON a partir de una definición en línea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre del esquema que se usa en `$id`. |\n| `url` | `String` | no | `CONF.url` | La URL base de `$id`. |\n\nReturns: `Object` El esquema JSON.\n\nLa definición es una lista de pares `name:type` separados por comas o saltos de línea. Un `*` o `!` delante del nombre hace que el campo sea obligatorio. Tipos: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` define una longitud máxima, `[string]` crea un array, `{draft|published}` un enum y `@name` usa otro esquema.\n\nEl `$id` se construye a partir de `url` (por defecto `CONF.url`) y `name`.\n\nExample: Esquema en línea\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatea el número con un separador de miles y decimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | El número de decimales. |\n| `separator` | `String` | no | `' '` | El separador de miles. |\n| `separatorDecimal` | `String` | no | `'.'` | El separador decimal. |\n\nReturns: `String` El número formateado.\n\nEl separador de miles predeterminado es un espacio. Los decimales se cortan (no se redondean) o se rellenan con ceros hasta `decimals`. El separador decimal es `.`, o `,` cuando el separador de miles es `.`. También puedes pasar primero el separador: `format(',', 2)`.\n\nExample: Formatear precios\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nElige una forma de la palabra según el número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forma para 0, o todas las formas separadas por comas. |\n| `one` | `String` | no |  | La forma para 1. |\n| `few` | `String` | no |  | La forma para 2 a 4. |\n| `other` | `String` | no |  | La forma para los demás números. |\n\nReturns: `String` La forma elegida.\n\n`zero` se usa para 0, `one` para 1, `few` para 2 a 4 y `other` para el resto. Un `#` en la forma elegida se reemplaza por el número. También puedes pasar todas las formas como un único string separado por comas.\n\nExample: Número de elementos\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nConvierte el número en una cadena rellenada por la izquierda.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud final. |\n| `c` | `String` | no | `'0'` | El carácter de relleno. |\n\nReturns: `String` El número rellenado.\n\nEl carácter de relleno predeterminado es `0`.\n\nExample: Número de factura\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nConvierte el número en una cadena rellenada por la derecha.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longitud final. |\n| `c` | `String` | no | `'0'` | El carácter de relleno. |\n\nReturns: `String` El número rellenado.\n\nEl carácter de relleno predeterminado es `0`.\n\nExample: Rellenar por la derecha\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nRedondea el número a un número de decimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | El número de decimales. |\n\nReturns: `Number` El número redondeado.\n\nSin `precision`, el número se redondea a un entero.\n\nExample: Redondear\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nRedondea el número hacia abajo a un número de decimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | El número de decimales. |\n\nReturns: `Number` El número redondeado hacia abajo.\n\nFunciona como `Math.floor()` con decimales.\n\nExample: Redondear hacia abajo\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nDevuelve un valor de un mapa de rangos numéricos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Rangos como claves y resultados como valores. |\n| `otherwise` | `Object` | yes |  | El valor cuando ningún rango coincide. |\n\nReturns: `Object` El valor del rango que coincide.\n\nLas claves de `condition` son rangos: `'1-5'` (de 1 a 5), `'10-'` (10 o más) o `'-5'` (5 o menos). Se devuelve el valor del primer rango que coincide; si no, `otherwise`.\n\nExample: Etiqueta de valoración\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nAplica una operación matemática escrita como cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Un número, o una operación como `'-5'` o `'+20%'`. |\n| `decimals` | `Number` | no |  | Redondear el resultado hacia abajo a estos decimales. |\n\nReturns: `Number` El resultado.\n\nUn número se suma. Una cadena empieza con un operador `+`, `-`, `*` o `/` seguido de un número, por ejemplo `'+10'`. Con `%` al final, el operando es un porcentaje del número: `'+20%'` suma un 20 %. Con `decimals`, el resultado se redondea hacia abajo a ese número de decimales.\n\nExample: Operaciones\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAñade el IVA al precio, o lo quita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | El tipo de IVA en porcentaje. |\n| `decimals` | `Number` | no | `2` | El número de decimales. |\n| `includedVAT` | `Boolean` | no | `false` | El número ya incluye el IVA. |\n\nReturns: `Number` El precio.\n\nSin `includedVAT`, el método devuelve el precio con IVA. Con `includedVAT` en `true`, el número es un precio con IVA y el método devuelve el precio sin él. El resultado se redondea a `decimals`.\n\nExample: Con y sin IVA\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nResta un descuento porcentual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | El descuento en porcentaje. |\n| `decimals` | `Number` | no | `2` | El número de decimales. |\n\nReturns: `Number` El número con el descuento aplicado.\n\nEl resultado se redondea hacia abajo a `decimals`.\n\nExample: Descuento\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nFormatea un número de bytes como un tamaño de archivo legible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | El número de decimales. |\n| `type` | `String` | no |  | La unidad: `'bytes'`, `'KB'`, `'MB'`, `'GB'` o `'TB'`. |\n\nReturns: `String` El tamaño con la unidad.\n\nSin `type`, la unidad se elige automáticamente (`bytes`, `KB`, `MB`, `GB` o `TB`). Con `type`, el valor se convierte a esa unidad. Sin `decimals`, el valor tiene hasta 2 decimales.\n\nExample: Tamaño de archivo\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nEjecuta una función asíncrona tantas veces como indica el número, en cuenta atrás.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La función `function(number, next)`. |\n| `callback` | `Function` | no |  | Se llama después de la última ejecución. |\n\nReturns: `Number`\n\nLa función recibe el número actual (desde el valor inicial hasta 1) y `next`. La siguiente ejecución empieza después de que llames a `next()`. Cuando la cuenta llega a cero, se llama a `callback`.\n\nExample: Tres ejecuciones\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nDevuelve una nueva fecha desplazada un periodo de tiempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | La unidad, una expresión como `'5 days'` o milisegundos. |\n| `value` | `Number` | no |  | La cantidad. |\n\nReturns: `Date` Una nueva fecha.\n\nPasa un tipo y un valor (`add('days', 5)`) o una expresión (`add('5 days')`). Tipos: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, y también las formas cortas `s`, `m`, `h`, `d`, `w`, `M`, `y`. Los valores negativos desplazan hacia atrás. Un número suma milisegundos. La fecha original no cambia.\n\nExample: Desplazar fechas\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nFormatea la fecha como cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | El formato, por ejemplo `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | El archivo de recursos con los nombres traducidos de meses y días. |\n\nReturns: `String` La fecha formateada.\n\nSin `format`, la fecha se devuelve como cadena ISO en UTC. Los tokens de formato usan la hora local: `yyyy`, `yy`, `MM`, `M`, `MMM` (nombre corto del mes), `MMMM` (nombre del mes), `dd`, `d`, `ddd` (nombre corto del día), `dddd` (nombre del día), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (semana ISO), `a` (AM/PM). Los nombres de meses y días están en inglés; con `resource` se leen de ese archivo de recursos.\n\nExample: Formatos\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nDevuelve la diferencia entre dos fechas en una unidad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | La fecha con la que se compara. |\n| `type` | `String` | yes |  | La unidad. |\n\nReturns: `Number` La diferencia.\n\nLa diferencia es `this - date`, redondeada hacia arriba. Sin `date`, el método compara con el momento actual. Unidades: `seconds`, `minutes`, `hours`, `days`, `months`, `years` y las formas cortas `s`, `m`, `h`, `d`, `M`, `y`. Un mes cuenta como 28 días. Una unidad desconocida da `NaN`.\n\nExample: Días restantes\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nDesplaza la fecha según el desfase de la zona horaria local.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Devolver milisegundos. |\n\nReturns: `Date|Number`\n\nEl resultado muestra la hora UTC en los campos locales de la fecha. Con `ticks` en `true`, el método devuelve milisegundos en lugar de una fecha.\n\nExample: Fecha UTC\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nDevuelve una nueva fecha con partes definidas a partir de una cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Las partes de fecha u hora, por ejemplo `'12:00'` o `'2024-12-24 18:00'`. |\n\nReturns: `Date` Una nueva fecha.\n\nLa cadena puede contener una fecha (`yyyy-MM-dd` o `dd.MM.yyyy`) y una hora (`HH:mm` o `HH:mm:ss`). Solo se cambian las partes indicadas; se definen en UTC.\n\nExample: Definir la hora\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nDevuelve una nueva fecha convertida a una zona horaria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | El nombre de la zona horaria IANA. |\n\nReturns: `Date` Una nueva fecha.\n\n`timezone` es un nombre IANA como `'Europe/Bratislava'`.\n\nExample: Hora en Nueva York\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nDevuelve el primer elemento que coincide, o `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una función o un nombre de propiedad. |\n| `value` | `Object` | no |  | El valor de la propiedad. |\n\nReturns: `Object` El elemento, o `null`.\n\n`cb` es una función `function(item, index)`, o un nombre de propiedad que se compara con `value` (`===`). Con un único argumento que no es una función, se comparan los propios elementos.\n\nExample: Por propiedad y por función\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nDevuelve todos los elementos que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una función `function(item, index)` o un nombre de propiedad. |\n| `value` | `Object` | no |  | El valor de la propiedad. |\n\nReturns: `Array` Los elementos que coinciden.\n\nLos argumentos son los mismos que en `Array.findItem()`. El resultado es un nuevo array.\n\nExample: Filtrar\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nDevuelve el índice del primer elemento que coincide, o `-1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una función o un nombre de propiedad. |\n| `value` | `Object` | no |  | El valor de la propiedad. |\n\nReturns: `Number` El índice, o `-1`.\n\nTotal.js reemplaza el método nativo para que también acepte un nombre de propiedad y un valor. Una función se llama como `function(item, index)`. `Array.TfindIndex()` es el mismo método con un nombre que otros módulos no sobrescriben.\n\nExample: Índice por propiedad\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nUn alias de `Array.findIndex()` que otros módulos no sobrescriben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una función o un nombre de propiedad. |\n| `value` | `Object` | no |  | El valor de la propiedad. |\n\nReturns: `Number` El índice, o `-1`.\n\nAlgunos módulos de NPM reemplazan `Array.prototype.findIndex` por su propia versión. En ese caso, `TfindIndex()` conserva el comportamiento de Total.js (nombre de propiedad y valor). `findItem()` y `findValue()` lo usan internamente.\n\nExample: Índice seguro\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nBusca un elemento y devuelve una de sus propiedades.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una función o un nombre de propiedad. |\n| `value` | `Object` | yes |  | El valor de la propiedad. |\n| `path` | `String` | yes |  | La propiedad que se devuelve. |\n| `def` | `Object` | no |  | El valor predeterminado. |\n\nReturns: `Object` El valor de la propiedad, o `def`.\n\nEl elemento se busca como en `Array.findItem()`; después se devuelve su propiedad `path`. Cuando no hay elemento o la propiedad es `null`/`undefined`, se devuelve `def`.\n\nExample: Nombre por id\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nDevuelve un nuevo array sin los elementos que coinciden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | Una función, un nombre de propiedad o un elemento. |\n| `value` | `Object` | no |  | El valor de la propiedad. |\n\nReturns: `Array` Un nuevo array.\n\nLos argumentos son los mismos que en `Array.findItem()`. El array original no cambia, así que asigna el resultado.\n\nExample: Eliminar elementos\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nDevuelve los primeros `count` elementos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número de elementos. |\n\nReturns: `Array` Un nuevo array.\n\nEl resultado es un nuevo array.\n\nExample: Los tres primeros\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nDevuelve los elementos que siguen a los primeros `count` elementos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número de elementos omitidos. |\n\nReturns: `Array` Un nuevo array.\n\nJunto con `Array.take()` permite una paginación sencilla.\n\nExample: Paginación\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nDevuelve el primer elemento, o `def` si el array está vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | El valor para un array vacío. |\n\nReturns: `Object`\n\nExample: Primer elemento\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nDevuelve el último elemento, o `def` si el array está vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | El valor para un array vacío. |\n\nReturns: `Object`\n\nExample: Último elemento\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nOrdena el array en el mismo array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Las propiedades por las que se ordena, o `true` para valores primitivos en orden descendente. |\n| `desc` | `Boolean` | no | `false` | Ordenar de forma descendente. |\n\nReturns: `Array` El mismo array.\n\n`sort` es un nombre de propiedad con un sufijo opcional `_asc` o `_desc`, por ejemplo `'name'` o `'price_desc'`. Varias propiedades se separan con comas (`'name_asc,price_desc'`) y las propiedades anidadas usan puntos. Las cadenas, los números, los booleanos y las fechas se comparan según su tipo. Con `desc` en `true`, el orden se invierte.\n\nSin argumentos, los valores primitivos se ordenan de forma ascendente; `quicksort(true)` los ordena de forma descendente.\n\nExample: Ordenar objetos\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nCrea un objeto (un mapa de búsqueda) a partir del array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | La propiedad que se usa como clave. |\n\nReturns: `Object` El objeto de búsqueda.\n\nCon `name`, cada elemento se guarda bajo el valor de su propiedad `name`. Sin él, cada elemento se convierte en una clave con el valor `true`.\n\nExample: Búsquedas por clave\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nRecorta las cadenas y elimina los elementos vacíos.\n\nReturns: `Array` Un nuevo array.\n\nLas cadenas se recortan, y se eliminan los elementos que quedan vacíos después de recortarlos (o que son `null`, `0`, `false`). Devuelve un nuevo array.\n\nExample: Limpiar una lista\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nProcesa los elementos uno a uno con una función asíncrona.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | La función `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Se llama después del último elemento. |\n| `thread` | `Number|Boolean` | no | `1` | El número de elementos en paralelo, o `true` para eliminar los elementos. |\n\nReturns: `Array` El mismo array.\n\n`onItem(item, next, index)` se llama para cada elemento; llama a `next()` para continuar. `callback` se llama después del último elemento. `thread` define cuántos elementos se procesan a la vez (por defecto 1). Con `thread` en `true`, los elementos se eliminan del array mientras se procesan. Llama a `next('cancel')` para detener; entonces `callback` recibe `'cancel'`.\n\nExample: Enviar correos electrónicos uno a uno\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nEjecuta un array de funciones asíncronas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | El número de funciones en paralelo. |\n| `callback` | `Function` | no |  | Se llama al final. |\n\nReturns: `Array` El mismo array.\n\nCada elemento es una función `function(next)`. Los elementos se eliminan del array a medida que se ejecutan. `thread` define cuántas funciones se ejecutan a la vez (por defecto 1). `callback` se llama después de la última función, o con `'cancel'` cuando una función llama a `next('cancel')`.\n\nExample: Una lista de tareas\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nProcesa el array en bloques de `max` elementos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | El tamaño de un bloque. |\n| `fn` | `Function` | yes |  | La función `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Se llama después del último bloque. |\n\nReturns: `Array` El mismo array.\n\n`fn(items, next, beg, end)` recibe el siguiente bloque; llama a `next()` para continuar con el bloque siguiente. `callback` se llama después del último bloque.\n\nExample: Insertar por lotes\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nMezcla el array, o devuelve un elemento aleatorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Devolver un elemento aleatorio. |\n\nReturns: `Array|Object`\n\nSin argumentos, el array se mezcla en el mismo array (Fisher-Yates) y se devuelve. Con `item` en `true`, se devuelve un elemento aleatorio y el array no cambia.\n\nExample: Mezclar y elegir\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nAnaliza texto CSV y lo convierte en un array de objetos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | El delimitador de columnas. |\n\nReturns: `Object[]` Un objeto por línea, con las claves `a`, `b`, `c`...\n\nCada línea se convierte en un objeto. Las columnas se nombran con letras: la primera es `a`, la segunda `b`, etc. Los valores entre comillas dobles pueden contener el delimitador y saltos de línea, y `\"\"` dentro de las comillas es una comilla escapada. Todos los valores siguen siendo cadenas, y una columna vacía no tiene clave en el objeto. No se detecta una línea de cabecera, así que se devuelve como el primer objeto.\n\nExample: Leer un archivo CSV\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nLee el sistema operativo, el navegador y el tipo de dispositivo a partir de una cadena de user agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Devolver un objeto en lugar de un texto. |\n\nReturns: `String|Object` Los nombres detectados, o `{ os, browser, device }`.\n\nSin argumento, el método devuelve un texto corto con los nombres detectados, como `Mac Chrome` o `iOS iPhone Mobile Safari`. Con `structured` en `true` devuelve un objeto `{ os, browser, device }`, donde `device` es `desktop`, `mobile`, `tablet` o `tv`. Una cadena vacía devuelve una cadena vacía.\n\nExample: Detectar el cliente\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nAnaliza texto `application/x-www-form-urlencoded` y lo convierte en un objeto.\n\nReturns: `Object` Las claves y los valores analizados.\n\nEl texto tiene la forma de una query string: `key=value&key2=value2`. `+` se convierte en un espacio y las secuencias `%xx` se decodifican. Todos los valores siguen siendo cadenas; una clave repetida une sus valores con una coma. Las claves solo pueden contener letras, dígitos y `-`, `_`, `.`, `[`, `]`, y el análisis se detiene en el primer carácter distinto de una clave. El número de claves está limitado por `CONF.default_request_maxkeys` y la longitud de una clave por `CONF.default_request_maxkey`.\n\nExample: Analizar el cuerpo de un formulario\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nAnaliza XML y lo convierte en un objeto plano de rutas y valores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Reemplazar los caracteres especiales de las claves por `_`. |\n\nReturns: `Object` El objeto plano de rutas.\n\nCada elemento con texto se convierte en una clave formada por los nombres de los elementos unidos con puntos, por ejemplo `book.title`. Un elemento repetido da un array de valores. Los atributos de un elemento se guardan como un objeto bajo la ruta seguida de `[]`. Las secciones `CDATA` se leen como texto y los comentarios se omiten. Con `replace` en `true`, los caracteres `[`, `]`, `:`, `.` y `_` de las claves se reemplazan por `_`.\n\nExample: Leer un feed XML\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nAnaliza HTML y lo convierte en un árbol de elementos que puedes buscar y modificar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Recortar el contenido de texto. |\n\nReturns: `HTMLElement` El elemento raíz del documento analizado.\n\nEl método usa el parser HTML integrado y devuelve el elemento raíz. Los elementos tienen `tagName`, `attrs`, `children` y `parentNode`, y los métodos `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` y `html([formatted])`. Con `trim` en `true`, el texto dentro de los elementos se recorta.\n\nExample: Leer y modificar HTML\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nExtrae bloques etiquetados de un texto y devuelve su contenido por nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | El nombre y la etiqueta de apertura de cada bloque. |\n\nReturns: `Object` El contenido de cada bloque encontrado.\n\n`tags` asigna un nombre a una etiqueta de apertura, por ejemplo `{ js: '<script>', css: '<style>' }`. Para cada nombre se devuelve el contenido entre la etiqueta de apertura y su etiqueta de cierre (se cuentan las etiquetas anidadas del mismo tipo). Una etiqueta que falta no da ninguna clave. Total.js lo usa para leer la parte `<script total>` de los plugins y componentes `.html`.\n\nExample: Dividir un archivo de componente\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nAnaliza línea a línea la salida en columnas de un comando de terminal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Nombres de cabecera o expresiones regulares de las columnas. |\n| `fn` | `Function` | yes |  | Se llama como `fn(values, index, count, line)` para cada línea. |\n| `skip` | `Number` | no | `0` | El número de líneas que se omiten. |\n| `take` | `Number` | no | `all` | El número de líneas que se leen. |\n\nReturns: `String` La misma cadena.\n\nCon `fields`, la primera línea no vacía (de las tres primeras) es la cabecera. Cada campo es un nombre de cabecera (`String`) o una `RegExp` que encuentra la columna en la línea de cabecera, y `fn` recibe los valores de esas columnas para cada línea siguiente. Sin `fields`, cada línea se divide en palabras y `fn` recibe el array de palabras. `fn(values, index, count, line)` recibe los valores, el índice de la línea analizada, el índice final y el número de línea. `skip` y `take` limitan las líneas. El método devuelve la propia cadena.\n\nExample: Leer la salida de df\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nAnaliza texto en el formato de configuración de Total.js y lo convierte en un objeto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valores predeterminados copiados en el resultado. |\n| `onerror` | `Function` | no |  | Se llama como `onerror(err, line)` cuando falla un valor `object` o `eval`. |\n\nReturns: `Object` Los valores parseados.\n\nCada línea es `key : value`, y se omiten las líneas que empiezan con `#` o `//`. El valor empieza dos caracteres después del primer `:`, así que escribe un espacio después de los dos puntos. Un tipo entre paréntesis después de la clave convierte el valor: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (separado por comas), `(json)`, `(object)` o `(eval)` (evaluado como JavaScript), `(date)`, `(env)` (una variable de entorno), `(config)` (otra clave de `CONF`) y `(random)` (una cadena aleatoria de la longitud indicada). `def` da los valores predeterminados. `onerror(err, line)` gestiona un valor que no se puede evaluar; sin él, el método lanza una excepción.\n\nExample: Analizar un texto de configuración\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nConvierte un texto como `5 minutes` en una fecha futura.\n\nReturns: `Date` La fecha actual más el tiempo indicado.\n\nEl texto se lee como pares de un número y una unidad, separados por espacios, por ejemplo `1 day 12 hours`. Cada par se suma a la fecha actual con `Date.add()`, así que funcionan las mismas unidades (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Un par con el número `0` se ignora.\n\nExample: Caducidad de una cookie\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nLee la información guardada en un identificador creado por `UID()`.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nEl resultado tiene `version` (el último carácter del UID), `date` (cuándo se creó), `century`, `index` (el contador), `hash` y `valid`. Para la versión aleatoria `r` (`CONF.default_uid = 'r'`) el resultado no tiene fecha, y los identificadores se validan con `String.isUID()`.\n\nExample: Cuándo se creó un registro\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nBusca el primer número decimal de un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | El valor que se devuelve cuando no se encuentra ningún número. |\n\nReturns: `Number` El número encontrado.\n\nA diferencia de `String.parseFloat()`, el texto puede contener otros caracteres: se usa el primer grupo de dígitos, puntos y comas, y las comas se convierten en puntos. Un `-` inicial lo hace negativo. Sin número, el método devuelve `def`.\n\nExample: Precio a partir de una etiqueta\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nComprueba si la cadena es un GUID (UUID).\n\nReturns: `Boolean`\n\nLa cadena debe tener 36 caracteres con la forma `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, donde `M` es una versión del 1 al 5. Se aceptan letras mayúsculas y minúsculas.\n\nExample: Validar un UUID\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nComprueba si la cadena es una fecha en formato JSON (ISO 8601 UTC).\n\nReturns: `Boolean`\n\nEl método comprueba la forma del texto, como `2024-05-01T10:30:00.000Z`: la longitud, la `T`, los guiones y los dos puntos, y la `Z` final. No comprueba que la fecha exista.\n\nExample: Restaurar fechas\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nComprueba si la cadena contiene solo dígitos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Permitir un separador decimal. |\n\nReturns: `Boolean`\n\nCon `decimal` en `true`, también se permite un `.` o una `,`. No se aceptan signos, espacios ni exponentes, y una cadena vacía devuelve `false`.\n\nExample: Comprobar la entrada del usuario\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nComprueba si la cadena es `true` o `false`.\n\nReturns: `Boolean`\n\nLa comparación no distingue mayúsculas de minúsculas. Otros valores como `1` u `on` devuelven `false`; esos los lee `String.parseBoolean()`.\n\nExample: Comprobar un valor de la query string\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nComprueba si la cadena parece un código postal (ZIP).\n\nReturns: `Boolean`\n\nLa cadena se prueba con `DEF.validators.zip`, por defecto de 3 a 20 letras, dígitos, espacios o guiones. Cambia `DEF.validators.zip` para usar tu propia regla.\n\nExample: Validar un código postal\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nComprueba si la cadena contiene una etiqueta HTML.\n\nReturns: `Boolean`\n\nLa prueba es sencilla: devuelve `true` cuando el texto contiene `<` seguido más adelante de `>`. Úsalo para rechazar HTML en campos de texto plano.\n\nExample: Rechazar HTML\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nComprueba si la cadena contiene un texto entre comillas o una palabra clave de SQL.\n\nReturns: `Boolean`\n\nEl método devuelve `true` para texto entre comillas simples o para las palabras en mayúsculas `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` y `UNION`. Es una comprobación aproximada; usa parámetros en tus consultas de todos modos.\n\nExample: Comprobar una frase de búsqueda\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nComprueba si la cadena está codificada en base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Aceptar un prefijo de data URI. |\n\nReturns: `Boolean`\n\nLa longitud debe ser divisible por 4 y el texto solo debe contener caracteres base64. Con `data` en `true`, se acepta una data URI como `data:image/png;base64,...` y solo se comprueba la longitud de la parte codificada.\n\nExample: Comprobar una subida\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nEscribe datos base64 en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | La ruta del archivo. |\n| `callback` | `Function` | no |  | Se llama como `callback(err)` cuando se ha escrito el archivo. |\n\nReturns: `String` La misma cadena.\n\nSe elimina el prefijo de data URI (todo hasta la primera coma), y el resto se decodifica y se escribe con `fs.writeFile()`. El método devuelve la propia cadena; el resultado de la escritura llega a `callback(err)`.\n\nExample: Guardar una imagen subida\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDecodifica datos base64 en un `Buffer`.\n\nReturns: `Buffer` Los datos decodificados.\n\nAntes de decodificar se elimina el prefijo de data URI (todo hasta la primera coma).\n\nExample: Decodificar una data URI\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nDevuelve el tipo de contenido de una data URI.\n\nReturns: `String` El tipo de contenido, por ejemplo `image/png`.\n\nSe devuelve el texto entre `data:` y el primer `;`. Una cadena sin `;` devuelve una cadena vacía.\n\nExample: Comprobar el tipo de una subida\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nCalcula la suma de control CRC32 de la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Devolver un número sin signo. |\n\nReturns: `Number` La suma de control.\n\nEl resultado es un número de 32 bits con signo, o sin signo cuando `unsigned` es `true`. `String.hash('crc32')` y `String.hash('crc32unsigned')` dan los mismos resultados.\n\nExample: Suma de control de un texto\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nCrea un hash SHA-1 de la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texto que se añade antes de calcular el hash. |\n\nReturns: `String` El hash en hexadecimal.\n\nLa `salt` se añade a la cadena antes de calcular el hash.\n\nExample: Hash SHA-1\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nCrea un hash SHA-512 de la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texto que se añade antes de calcular el hash. |\n\nReturns: `String` El hash en hexadecimal.\n\nLa `salt` se añade a la cadena antes de calcular el hash.\n\nExample: Hash de un token\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nCrea un id corto a partir de la cadena.\n\nReturns: `String` El id.\n\nEl id es un hash rápido sin signo de la cadena escrito en base 36. La misma cadena siempre da el mismo id. No es un hash criptográfico.\n\nExample: Id para una clave de caché\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nAñade una suma de control rápida a la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Un secreto que se mezcla en la suma de control. |\n\nReturns: `String` La cadena con la suma de control.\n\nEl resultado es la cadena, un guion y un hash en base 36 de la cadena con `key`. Para verificar un valor, firma de nuevo la parte anterior al último guion y compara. Es una suma de control rápida, no una firma criptográfica.\n\nExample: Firmar y verificar un valor\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nProtege un identificador con una suma de control.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | El secreto. |\n\nReturns: `String` El identificador protegido.\n\nEl resultado es `x`, una suma de control y `x` seguido del valor original, así que el valor sigue siendo legible pero no se puede cambiar sin la clave. La suma de control usa `key` (por defecto `CONF.secret`) y `CONF.secret_uid`. Léelo de nuevo con `String.decrypt_uid()`. La misma función para números es `U.encrypt_uid(value, [key])`.\n\nExample: Id protegido en un enlace\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nLee un identificador protegido con `String.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | El secreto usado en `encrypt_uid()`. |\n\nReturns: `String|Number` El valor original, o `null` cuando la suma de control es incorrecta.\n\nLa suma de control se vuelve a crear con `key` (por defecto `CONF.secret`). Cuando coincide, se devuelve el valor original; si no, `null`. Un valor creado a partir de un número se devuelve como número.\n\nExample: Verificar un enlace\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nLimpia un nombre de persona: elimina otros caracteres y pone en mayúscula cada palabra.\n\nReturns: `String` El nombre limpio.\n\nSe eliminan los dígitos y la puntuación ASCII, se conservan los espacios y la primera letra de cada palabra se pone en mayúscula. Las letras con diacríticos se conservan. Se eliminan los espacios finales, pero no los iniciales ni los repetidos, así que recorta la entrada primero.\n\nExample: Limpiar un nombre de un formulario\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nEscapa los caracteres fuera del ASCII imprimible como `\\uXXXX`.\n\nReturns: `String` La cadena escapada.\n\nLos caracteres con un código menor que 32 o mayor que 126 se escriben como `\\u` y cuatro dígitos hexadecimales. `String.fromUnicode()` lo revierte.\n\nExample: Escapar un texto\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nConvierte los escapes `\\uXXXX` de nuevo en caracteres.\n\nReturns: `String` La cadena sin escapar.\n\nCada `\\u` seguido de cuatro dígitos hexadecimales se reemplaza por el carácter. Revierte `String.toUnicode()`.\n\nExample: Quitar el escape de un texto\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nComprueba si la cadena termina con un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | El texto que se busca. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true` para no distinguir mayúsculas de minúsculas, o un desplazamiento desde el final. |\n\nReturns: `Boolean`\n\nTotal.js reemplaza el método nativo. Con `ignoreCase` en `true`, no se distinguen mayúsculas de minúsculas. Un número en lugar de `ignoreCase` comprueba el texto ese número de caracteres antes del final.\n\nExample: Comprobar una extensión de archivo\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nReemplaza la primera aparición de un texto, sin expresiones regulares.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | El texto que se reemplaza. |\n| `text` | `String` | yes |  | El texto nuevo. |\n\nReturns: `String` La nueva cadena.\n\n`find` es texto plano, así que caracteres como `$` o `.` no tienen un significado especial en él ni en `text`. Cuando no se encuentra `find`, la cadena se devuelve sin cambios.\n\nExample: Insertar un precio en una plantilla\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nInserta un valor en una posición de la cadena.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | La posición. |\n| `value` | `Object` | yes |  | El valor que se inserta. |\n\nReturns: `String` La nueva cadena.\n\nEl valor se convierte en cadena con `toString()`.\n\nExample: Formatear un código\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nAñade un carácter al principio de la cadena un número de veces.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Cuántos caracteres se añaden. |\n| `char` | `String` | no | `' '` | El carácter. |\n\nReturns: `String` La cadena con sangría.\n\nA diferencia de `String.padLeft()`, los caracteres siempre se añaden, sea cual sea la longitud de la cadena.\n\nExample: Sangrar una línea\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nElige una forma de la palabra según el número del string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forma para 0, o todas las formas separadas por comas. |\n| `one` | `String` | no |  | La forma para 1. |\n| `few` | `String` | no |  | La forma para 2 a 4. |\n| `other` | `String` | no |  | La forma para los demás números. |\n\nReturns: `String` La forma elegida.\n\nEl string se lee con `String.parseInt()` y se pasa a `Number.pluralize()`, así que las reglas y el marcador `#` son los mismos.\n\nExample: Contador desde una query\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nReemplaza los marcadores `[key]` por valores de configuración.\n\nReturns: `String` La cadena con los valores.\n\nCada `[key]` (letras, dígitos y `_`) se reemplaza por `CONF[key]`; una clave que falta da una cadena vacía.\n\nExample: Construir una URL a partir de la configuración\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nBusca bloques en una cadena y pasa cada uno a un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | El delimitador inicial, o el separador cuando falta `end`. |\n| `end` | `String` | no |  | El delimitador final. |\n| `callback` | `Function` | yes |  | Se llama como `callback(value, index)`; devuelve `false` para detener. |\n| `skip` | `Number` | no | `0` | El número de bloques que se omiten. |\n\nReturns: `undefined`\n\nCon `beg` y `end`, se pasa cada bloque que empieza con `beg` y termina con `end`, delimitadores incluidos. Sin `end`, la cadena se divide después de cada `beg`, y cada parte termina con `beg`. `callback(value, index)` puede devolver `false` para detener. `skip` omite los primeros bloques.\n\nExample: Leer elementos de un XML\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nRedondea el número a un número de decimales y devuelve un número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | El número de decimales. |\n\nReturns: `Number` El número redondeado.\n\nEs lo mismo que `+number.toFixed(decimals)`: a diferencia de `toFixed()`, el resultado es un número, no una cadena.\n\nExample: Redondear un precio\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatea el número con un formateador de moneda de `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La clave en `DEF.currencies`. |\n| `a` | `Object` | no |  | Se pasa al formateador, igual que `b` y `c`. |\n\nReturns: `String` El precio formateado.\n\n`DEF.currencies` está vacío por defecto; añade una función `function(value, a, b, c)` para cada código de moneda que necesites, y `default` para las llamadas sin código. Los argumentos adicionales se le pasan. Sin formateador, el número se formatea con `Number.format(2)`.\n\nExample: Registrar y usar monedas\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nConvierte el número en hexadecimal en mayúsculas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | La longitud mínima. |\n\nReturns: `String` El valor hexadecimal.\n\nEl resultado se rellena con ceros a la izquierda hasta `length` caracteres.\n\nExample: Componente de color\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nCrea una fecha a partir de una marca de tiempo en milisegundos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Milisegundos que se suman. |\n\nReturns: `Date` La fecha.\n\nSe suman `plus` milisegundos al número antes de crear la fecha.\n\nExample: Fecha a partir de una marca de tiempo\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nConvierte grados en radianes.\n\nReturns: `Number` El ángulo en radianes.\n\nSolo se define cuando `Number.prototype.toRad` todavía no existe.\n\nExample: Distancia entre dos puntos GPS\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nDevuelve la propia fecha.\n\nReturns: `Date` La misma fecha.\n\nTe permite llamar a `parseDate()` sobre un valor que puede ser una cadena, un número o una fecha, sin comprobar antes su tipo.\n\nExample: Valor de tipo desconocido\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Prototypes","summary":"Les méthodes de String, Number, Date et Array ajoutées par Total.js 4.","markdown":"---\ntitle: Prototypes\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypes\n\n> Les méthodes de String, Number, Date et Array ajoutées par Total.js 4.\n\nLes méthodes que Total.js 4 ajoute à `String`, `Number`, `Date` et `Array`. Le guide [Prototypes](../../guides/prototypes/) explique comment les utiliser, avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nRemplace les placeholders indexés `{0}`, `{1}`... par les arguments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | La valeur pour `{0}`. N'importe quel nombre d'arguments peut suivre. |\n\nReturns: `String` La chaîne formatée.\n\nChaque `{n}` est remplacé par l'argument d'indice `n`. Un argument `null` ou `undefined` donne une chaîne vide. Pour les placeholders nommés, utilise `String.args()`.\n\nExample: Placeholders indexés\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nRemplace les placeholders nommés `{key}` ou `{{key}}` par les valeurs d'un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Les valeurs. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (encodage URL), `'html'`, `'json'` ou une fonction `function(value, key)`. |\n| `def` | `String` | no |  | Le texte pour une valeur manquante. Il est ignoré quand `encode` est une chaîne. |\n\nReturns: `String` La chaîne avec les valeurs.\n\nLes clés peuvent contenir des lettres, des chiffres, `_`, `$`, `.` et `-`. Une valeur manquante conserve le placeholder, ou utilise `def` si tu l'as défini.\n\nL'argument `encode` change la façon dont les valeurs sont écrites : `true` les encode avec `encodeURIComponent()`, `'html'` encode les entités HTML, `'json'` écrit `JSON.stringify(value)`, et une fonction `function(value, key)` renvoie elle-même le texte. `String.arg()` est un alias.\n\nExample: Placeholders nommés\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: Encodage HTML\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: Une valeur par défaut pour les valeurs manquantes\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nCrée un slug adapté aux URL à partir du texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | La longueur maximale. |\n\nReturns: `String` Le slug.\n\nLe texte est débarrassé de ses espaces superflus, mis en minuscules et converti en ASCII (signes diacritiques supprimés). Les espaces et la ponctuation deviennent un seul `-` ; un `-` final est supprimé. Le résultat est coupé à `max` caractères.\n\nQuand le texte ne contient aucun caractère latin exploitable (par exemple du chinois ou du cyrillique), la méthode renvoie à la place un court hachage construit à partir du texte.\n\nExample: Slug à partir d'un titre\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nCoupe le texte à une longueur maximale et ajoute des points de suspension.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | La longueur maximale du résultat. |\n| `chars` | `String` | no | `'...'` | Le texte ajouté à une chaîne coupée. |\n\nReturns: `String` Le texte raccourci.\n\nQuand le texte est plus long que `length`, il est coupé de sorte que le résultat avec `chars` fasse exactement `length` caractères. Un texte plus court est renvoyé tel quel.\n\nExample: Raccourcir une description\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nMet en majuscule la première lettre de chaque mot.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Mettre en majuscule uniquement la première lettre. |\n\nReturns: `String` Le texte avec majuscules.\n\nLe texte est mis en minuscules et chaque lettre qui suit un espace, une tabulation ou un saut de ligne est mise en majuscule. Avec `first` à `true`, seule la première lettre du texte entier est mise en majuscule.\n\nExample: Mots et première lettre\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nConvertit la chaîne entière en nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur renvoyée quand la chaîne n'est pas un nombre. |\n\nReturns: `Number` Le nombre, ou `def`.\n\nLa chaîne est débarrassée de ses espaces superflus et convertie avec l'opérateur unaire `+`, la chaîne entière doit donc être un nombre : `'12px'` n'est pas un nombre et donne `def`. Pour lire un nombre dans un texte plus long, utilise `String.parseInt2()`.\n\nExample: Paramètre de query\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nLit le premier entier trouvé dans le texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur renvoyée quand le texte ne contient aucun nombre. |\n\nReturns: `Number` Le nombre, ou `def`.\n\nContrairement à `String.parseInt()`, le nombre peut être entouré d'autre texte. Un `-` initial est conservé. `String.parseFloat2()` fonctionne de la même façon pour les nombres décimaux (un séparateur décimal `,` est accepté).\n\nExample: Nombre dans un texte\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nConvertit la chaîne en nombre décimal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur renvoyée quand la chaîne n'est pas un nombre. |\n\nReturns: `Number` Le nombre, ou `def`.\n\nLa chaîne est débarrassée de ses espaces superflus et un séparateur décimal `,` est remplacé par `.`. La chaîne entière doit être un nombre, sinon `def` est renvoyé.\n\nExample: Virgule décimale\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nConvertit `true`, `1` ou `on` en `true`.\n\nReturns: `Boolean`\n\nLa comparaison ignore la casse. Toute autre valeur donne `false`.\n\nExample: Valeur d'une case à cocher\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nConvertit la chaîne en `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Le format de l'entrée, par exemple `'dd/MM/yyyy'`. |\n\nReturns: `Date` La date analysée.\n\nSans `format`, la méthode lit les chaînes ISO (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` et toute valeur que `new Date()` comprend. Une partie de date manquante prend celle d'aujourd'hui.\n\nAvec `format`, les chiffres de la chaîne sont lus dans l'ordre des lettres du format (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). Un `pm` dans le texte ajoute 12 heures.\n\nExample: Analyser des dates\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nAnalyse du JSON sans lever d'exception.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convertir les chaînes de date ISO en dates. |\n\nReturns: `Object` La valeur analysée, ou `undefined` pour un JSON invalide.\n\nUn JSON invalide renvoie `undefined` au lieu d'une erreur. Avec `date` à `true`, les chaînes de date ISO sont converties en objets `Date`.\n\nExample: Analyse sûre\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nAnalyse des lignes `KEY=value` (le format `.env`) en un objet.\n\nReturns: `Object` Les clés et leurs valeurs sous forme de chaînes.\n\nLes lignes vides et celles commençant par `#` ou `//` sont ignorées. Les valeurs entre guillemets doubles ou simples perdent leurs guillemets, et `\\n` devient un saut de ligne. Les valeurs sans guillemets sont débarrassées de leurs espaces superflus.\n\nExample: Lire un fichier .env\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nVérifie si la chaîne est une adresse e-mail.\n\nReturns: `Boolean`\n\nLe test utilise l'expression régulière `DEF.validators.email`, tu peux donc la remplacer. Les chaînes de 4 caractères ou moins sont toujours `false`.\n\nExample: Valider une saisie\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nVérifie si la chaîne est un numéro de téléphone.\n\nReturns: `Boolean`\n\nLe test utilise l'expression régulière `DEF.validators.phone`. Les chaînes de moins de 6 caractères sont toujours `false`.\n\nExample: Numéro de téléphone\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nVérifie si la chaîne est une adresse URL.\n\nReturns: `Boolean`\n\nLe test utilise l'expression régulière `DEF.validators.url`. Les chaînes de 7 caractères ou moins sont toujours `false`.\n\nExample: Adresse URL\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nVérifie si la chaîne est un identifiant valide créé par `UID()`.\n\nReturns: `Boolean`\n\nLa méthode teste le format avec `DEF.validators.uid`, puis la somme de contrôle que `UID()` écrit dans chaque identifiant ; une chaîne aléatoire avec les bons caractères n'est donc pas acceptée.\n\nExample: Valider un id issu de l'URL\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nVérifie si la chaîne ressemble à du JSON.\n\nReturns: `Boolean`\n\nSeuls le premier et le dernier caractère non blancs sont testés : `{...}`, `[...]`, `\"...\"` ou un nombre. Le contenu n'est pas analysé ; utilise `String.parseJSON()` pour cela.\n\nExample: Test rapide\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nCrée un hachage de la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | L'algorithme, ou `true` pour un hachage numérique non signé. |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String|Number` Une chaîne hexadécimale pour md5/sha*, sinon un nombre.\n\n`type` choisit l'algorithme : `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (chaînes hexadécimales), `'crc32'` ou `'crc32unsigned'` (nombres). Sans type, la méthode renvoie un hachage numérique rapide sur 32 bits ; `true` le rend non signé. Le `salt` est ajouté à la chaîne avant le hachage.\n\nExample: Différents hachages\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nRenvoie le hachage MD5 sous forme de chaîne hexadécimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String` Une chaîne hexadécimale de 32 caractères.\n\nLe `salt` est ajouté à la chaîne avant le hachage. Utilise-le pour les sommes de contrôle et les clés de cache, pas pour les mots de passe.\n\nExample: Clé de cache\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nRenvoie le hachage SHA-256 sous forme de chaîne hexadécimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String` Une chaîne hexadécimale de 64 caractères.\n\nLe `salt` est ajouté à la chaîne avant le hachage. `String.sha1([salt])` et `String.sha512([salt])` fonctionnent de la même façon avec les autres algorithmes.\n\nExample: Hachage avec un sel\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nEncode les caractères spéciaux HTML.\n\nReturns: `String` Le texte encodé.\n\nRemplace `<`, `>`, `\"`, `'` et `&` par des entités HTML, afin que le texte puisse être écrit dans du HTML en toute sécurité.\n\nExample: Échapper une saisie utilisateur\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDécode les entités HTML en caractères.\n\nReturns: `String` Le texte décodé.\n\nLes entités nommées et numériques (`&#65;`, `&#x41;`) sont converties. C'est l'inverse de `String.encode()`.\n\nExample: Décoder\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nChiffre la chaîne avec une clé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de chiffrement. |\n| `isUnique` | `Boolean` | no | `false` | Rendre chaque résultat différent. |\n| `secret` | `String` | no | `CONF.secret` | Un secret supplémentaire. |\n\nReturns: `String` La chaîne chiffrée.\n\nAvec `isUnique` à `true`, chaque appel donne un résultat différent pour la même entrée. Le résultat contient une somme de contrôle construite à partir de `secret` (par défaut `CONF.secret`) et de la clé, que `String.decrypt()` vérifie. Utilise-la pour les jetons et les URL, pas pour stocker des mots de passe.\n\nExample: Chiffrer un jeton\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nDéchiffre une chaîne créée par `String.encrypt()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de chiffrement. |\n| `secret` | `String` | no | `CONF.secret` | Le secret supplémentaire. |\n\nReturns: `String` La chaîne d'origine, ou `null`.\n\nUtilise les mêmes `key` et `secret` que pour le chiffrement. Une mauvaise clé, un mauvais secret ou une chaîne modifiée renvoie `null`.\n\nExample: Déchiffrer un jeton\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrait les mots-clés du texte, triés par fréquence.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Normaliser les mots pour la recherche. |\n| `alternative` | `Boolean` | no | `false` | Raccourcir chaque mot à 80 % de sa longueur. |\n| `max_count` | `Number` | no | `200` | Le nombre maximal de mots lus. |\n| `max_length` | `Number` | no | `20` | La longueur maximale d'un mot. |\n| `min_length` | `Number` | no | `2` | La longueur minimale d'un mot. |\n\nReturns: `String[]` Des mots uniques, les plus fréquents en premier.\n\nAvec `forSearch` (par défaut `true`), le texte est converti en ASCII et `y` devient `i`, ce qui rend la recherche tolérante. Avec `alternative`, chaque mot est raccourci à 80 % de sa longueur. Les mots plus courts que `min_length` ou plus longs que `max_length` sont ignorés. `String.toKeywords()` est un alias.\n\nExample: Mots-clés pour un index de recherche\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormalise le texte pour une recherche plein texte.\n\nReturns: `String` Le texte normalisé.\n\nLe texte est mis en minuscules et converti en ASCII, les caractères spéciaux sont supprimés, `y` devient `i` et les lettres répétées sont fusionnées. Applique-la à la fois au texte stocké et à la phrase recherchée.\n\nExample: Valeur de recherche\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nSupprime les signes diacritiques du texte.\n\nReturns: `String` Le texte sans signes diacritiques.\n\nLes lettres accentuées sont remplacées par leurs lettres latines de base, par exemple `á` par `a`.\n\nExample: Supprimer les signes diacritiques\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nSupprime les balises HTML du texte.\n\nReturns: `String` Le texte brut.\n\nSeules les balises sont supprimées ; le texte entre elles reste. Les entités HTML ne sont pas décodées.\n\nExample: Texte brut\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nComplète la chaîne à gauche jusqu'à la longueur `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur finale. |\n| `c` | `String` | no | `' '` | Le caractère de remplissage. |\n\nReturns: `String` La chaîne complétée.\n\nUne chaîne qui fait déjà `max` caractères ou plus est renvoyée telle quelle.\n\nExample: Zéros en tête\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nComplète la chaîne à droite jusqu'à la longueur `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur finale. |\n| `c` | `String` | no | `' '` | Le caractère de remplissage. |\n\nReturns: `String` La chaîne complétée.\n\nUne chaîne qui fait déjà `max` caractères ou plus est renvoyée telle quelle.\n\nExample: Colonne à largeur fixe\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nVérifie si la chaîne commence par `text`, en ignorant éventuellement la casse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Le texte à trouver. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true` pour ignorer la casse, ou une position de départ. |\n\nReturns: `Boolean`\n\nTotal.js remplace la méthode native. Avec `ignoreCase` à `true`, la comparaison ignore la casse ; un nombre est utilisé comme position de départ. `String.endsWith(text, [ignoreCase])` fonctionne de la même façon à la fin de la chaîne.\n\nExample: Ignorer la casse\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nConvertit du Markdown en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | Les options décrites ci-dessus. |\n\nReturns: `String` Le HTML.\n\nLe résultat est enveloppé dans `<div class=\"markdown markdown-container\">` sauf si `opt.wrap` vaut `false`. La plupart des fonctionnalités sont activées par défaut et tu en désactives une avec `false` : `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Autres options : `linetag` (la balise d'un paragraphe, par défaut `'p'`), `prefix` (un préfixe pour les id générés), `custom` (une fonction qui modifie chaque ligne) et `html` (une fonction `function(html, type)` qui modifie le HTML généré).\n\nExample: Rendre du Markdown\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Sans enveloppe ni images\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nSupprime les barres obliques finales.\n\nReturns: `String` La chaîne sans barres obliques finales.\n\nTous les caractères `/` en fin de chaîne sont supprimés, mais un `/` seul est conservé, ainsi `'/'` reste `'/'`.\n\nExample: Nettoyer une URL\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nCrée un objet de schéma JSON à partir d'une définition en ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom du schéma utilisé dans `$id`. |\n| `url` | `String` | no | `CONF.url` | L'URL de base de `$id`. |\n\nReturns: `Object` Le schéma JSON.\n\nLa définition est une liste de paires `name:type` séparées par des virgules ou des sauts de ligne. Un `*` ou un `!` devant le nom rend le champ obligatoire. Types : `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` fixe une longueur maximale, `[string]` crée un tableau, `{draft|published}` une énumération, et `@name` utilise un autre schéma.\n\nLe `$id` est construit à partir de `url` (par défaut `CONF.url`) et de `name`.\n\nExample: Schéma en ligne\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormate le nombre avec un séparateur de milliers et des décimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Le nombre de décimales. |\n| `separator` | `String` | no | `' '` | Le séparateur de milliers. |\n| `separatorDecimal` | `String` | no | `'.'` | Le séparateur décimal. |\n\nReturns: `String` Le nombre formaté.\n\nLe séparateur de milliers par défaut est une espace. Les décimales sont tronquées (pas arrondies) ou complétées par des zéros jusqu'à `decimals`. Le séparateur décimal est `.`, ou `,` quand le séparateur de milliers est `.`. Tu peux aussi passer le séparateur en premier : `format(',', 2)`.\n\nExample: Formater des prix\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nChoisit une forme de mot selon le nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forme pour 0, ou toutes les formes séparées par des virgules. |\n| `one` | `String` | no |  | La forme pour 1. |\n| `few` | `String` | no |  | La forme pour 2 à 4. |\n| `other` | `String` | no |  | La forme pour les autres nombres. |\n\nReturns: `String` La forme choisie.\n\n`zero` est utilisé pour 0, `one` pour 1, `few` pour 2 à 4 et `other` pour le reste. Un `#` dans la forme choisie est remplacé par le nombre. Tu peux aussi passer toutes les formes dans une seule chaîne séparée par des virgules.\n\nExample: Nombre d'éléments\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nConvertit le nombre en chaîne complétée à gauche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur finale. |\n| `c` | `String` | no | `'0'` | Le caractère de remplissage. |\n\nReturns: `String` Le nombre complété.\n\nLe caractère de remplissage par défaut est `0`.\n\nExample: Numéro de facture\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nConvertit le nombre en chaîne complétée à droite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La longueur finale. |\n| `c` | `String` | no | `'0'` | Le caractère de remplissage. |\n\nReturns: `String` Le nombre complété.\n\nLe caractère de remplissage par défaut est `0`.\n\nExample: Compléter à droite\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nArrondit le nombre à un nombre de décimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | Le nombre de décimales. |\n\nReturns: `Number` Le nombre arrondi.\n\nSans `precision`, le nombre est arrondi à un entier.\n\nExample: Arrondir\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nArrondit le nombre vers le bas à un nombre de décimales.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Le nombre de décimales. |\n\nReturns: `Number` Le nombre arrondi vers le bas.\n\nElle fonctionne comme `Math.floor()` avec des décimales.\n\nExample: Arrondi inférieur\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nRenvoie une valeur à partir d'une table de plages de nombres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Les plages comme clés et les résultats comme valeurs. |\n| `otherwise` | `Object` | yes |  | La valeur quand aucune plage ne correspond. |\n\nReturns: `Object` La valeur de la plage correspondante.\n\nLes clés de `condition` sont des plages : `'1-5'` (de 1 à 5), `'10-'` (10 et plus) ou `'-5'` (5 et moins). La valeur de la première plage correspondante est renvoyée, sinon `otherwise`.\n\nExample: Libellé de note\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nApplique une opération mathématique écrite sous forme de chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Un nombre, ou une opération comme `'-5'` ou `'+20%'`. |\n| `decimals` | `Number` | no |  | Arrondir le résultat vers le bas à ce nombre de décimales. |\n\nReturns: `Number` Le résultat.\n\nUn nombre est additionné. Une chaîne commence par un opérateur `+`, `-`, `*` ou `/` suivi d'un nombre, par exemple `'+10'`. Avec `%` à la fin, l'opérande est un pourcentage du nombre : `'+20%'` ajoute 20 %. Avec `decimals`, le résultat est arrondi vers le bas à ce nombre de décimales.\n\nExample: Opérations\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAjoute la TVA au prix, ou la retire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Le taux de TVA en pourcentage. |\n| `decimals` | `Number` | no | `2` | Le nombre de décimales. |\n| `includedVAT` | `Boolean` | no | `false` | Le nombre inclut déjà la TVA. |\n\nReturns: `Number` Le prix.\n\nSans `includedVAT`, la méthode renvoie le prix TTC. Avec `includedVAT` à `true`, le nombre est un prix TTC et la méthode renvoie le prix hors taxe. Le résultat est arrondi à `decimals`.\n\nExample: Avec et sans TVA\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nSoustrait une remise en pourcentage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | La remise en pourcentage. |\n| `decimals` | `Number` | no | `2` | Le nombre de décimales. |\n\nReturns: `Number` Le nombre après remise.\n\nLe résultat est arrondi vers le bas à `decimals`.\n\nExample: Remise\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nFormate un nombre d'octets en taille de fichier lisible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Le nombre de décimales. |\n| `type` | `String` | no |  | L'unité : `'bytes'`, `'KB'`, `'MB'`, `'GB'` ou `'TB'`. |\n\nReturns: `String` La taille avec l'unité.\n\nSans `type`, l'unité est choisie automatiquement (`bytes`, `KB`, `MB`, `GB` ou `TB`). Avec `type`, la valeur est convertie dans cette unité. Sans `decimals`, la valeur a jusqu'à 2 décimales.\n\nExample: Taille de fichier\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nExécute une fonction asynchrone autant de fois que le nombre, en décomptant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La fonction `function(number, next)`. |\n| `callback` | `Function` | no |  | Appelé après la dernière exécution. |\n\nReturns: `Number`\n\nLa fonction reçoit le nombre courant (de la valeur de départ jusqu'à 1) et `next`. L'exécution suivante démarre après ton appel à `next()`. Quand le compteur atteint zéro, `callback` est appelé.\n\nExample: Trois exécutions\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nRenvoie une nouvelle date décalée d'une période.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | L'unité, une expression comme `'5 days'`, ou des millisecondes. |\n| `value` | `Number` | no |  | La quantité. |\n\nReturns: `Date` Une nouvelle date.\n\nPasse un type et une valeur (`add('days', 5)`) ou une seule expression (`add('5 days')`). Types : `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, ainsi que les formes courtes `s`, `m`, `h`, `d`, `w`, `M`, `y`. Les valeurs négatives reculent. Un nombre ajoute des millisecondes. La date d'origine n'est pas modifiée.\n\nExample: Décaler des dates\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nFormate la date en chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Le format, par exemple `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | Le fichier de ressources contenant les noms traduits des mois et des jours. |\n\nReturns: `String` La date formatée.\n\nSans `format`, la date est renvoyée sous forme de chaîne ISO en UTC. Les jetons de format utilisent l'heure locale : `yyyy`, `yy`, `MM`, `M`, `MMM` (nom de mois court), `MMMM` (nom du mois), `dd`, `d`, `ddd` (nom de jour court), `dddd` (nom du jour), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (semaine ISO), `a` (AM/PM). Les noms des mois et des jours sont en anglais ; avec `resource`, ils sont lus dans ce fichier de ressources.\n\nExample: Formats\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nRenvoie la différence entre deux dates dans une unité.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | La date avec laquelle comparer. |\n| `type` | `String` | yes |  | L'unité. |\n\nReturns: `Number` La différence.\n\nLa différence est `this - date`, arrondie vers le haut. Sans `date`, la méthode compare avec maintenant. Unités : `seconds`, `minutes`, `hours`, `days`, `months`, `years` et les formes courtes `s`, `m`, `h`, `d`, `M`, `y`. Un mois compte 28 jours. Une unité inconnue donne `NaN`.\n\nExample: Jours restants\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nDécale la date du décalage du fuseau horaire local.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Renvoyer des millisecondes. |\n\nReturns: `Date|Number`\n\nLe résultat affiche l'heure UTC dans les champs locaux de la date. Avec `ticks` à `true`, la méthode renvoie des millisecondes au lieu d'une date.\n\nExample: Date UTC\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nRenvoie une nouvelle date dont certaines parties sont définies à partir d'une chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Les parties de date ou d'heure, par exemple `'12:00'` ou `'2024-12-24 18:00'`. |\n\nReturns: `Date` Une nouvelle date.\n\nLa chaîne peut contenir une date (`yyyy-MM-dd` ou `dd.MM.yyyy`) et une heure (`HH:mm` ou `HH:mm:ss`). Seules les parties fournies sont modifiées ; elles sont définies en UTC.\n\nExample: Définir l'heure\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nRenvoie une nouvelle date convertie vers un fuseau horaire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Le nom du fuseau horaire IANA. |\n\nReturns: `Date` Une nouvelle date.\n\n`timezone` est un nom IANA comme `'Europe/Bratislava'`.\n\nExample: L'heure à New York\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nRenvoie le premier élément correspondant, ou `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Une fonction ou un nom de propriété. |\n| `value` | `Object` | no |  | La valeur de la propriété. |\n\nReturns: `Object` L'élément, ou `null`.\n\n`cb` est une fonction `function(item, index)`, ou un nom de propriété comparé à `value` (`===`). Avec un seul argument qui n'est pas une fonction, ce sont les éléments eux-mêmes qui sont comparés.\n\nExample: Par propriété et par fonction\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nRenvoie tous les éléments correspondants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Une fonction `function(item, index)` ou un nom de propriété. |\n| `value` | `Object` | no |  | La valeur de la propriété. |\n\nReturns: `Array` Les éléments correspondants.\n\nLes arguments sont les mêmes que pour `Array.findItem()`. Le résultat est un nouveau tableau.\n\nExample: Filtrer\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nRenvoie l'indice du premier élément correspondant, ou `-1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Une fonction ou un nom de propriété. |\n| `value` | `Object` | no |  | La valeur de la propriété. |\n\nReturns: `Number` L'indice, ou `-1`.\n\nTotal.js remplace la méthode native afin qu'elle accepte aussi un nom de propriété et une valeur. Une fonction est appelée sous la forme `function(item, index)`. `Array.TfindIndex()` est la même méthode sous un nom que les autres modules ne surchargent pas.\n\nExample: Indice par propriété\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nUn alias de `Array.findIndex()` que les autres modules ne surchargent pas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Une fonction ou un nom de propriété. |\n| `value` | `Object` | no |  | La valeur de la propriété. |\n\nReturns: `Number` L'indice, ou `-1`.\n\nCertains modules NPM remplacent `Array.prototype.findIndex` par leur propre version. `TfindIndex()` conserve dans ce cas le comportement de Total.js (nom de propriété et valeur). `findItem()` et `findValue()` l'utilisent en interne.\n\nExample: Indice sûr\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nTrouve un élément et renvoie l'une de ses propriétés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Une fonction ou un nom de propriété. |\n| `value` | `Object` | yes |  | La valeur de la propriété. |\n| `path` | `String` | yes |  | La propriété à renvoyer. |\n| `def` | `Object` | no |  | La valeur par défaut. |\n\nReturns: `Object` La valeur de la propriété, ou `def`.\n\nL'élément est trouvé comme avec `Array.findItem()` ; ensuite, sa propriété `path` est renvoyée. Quand il n'y a pas d'élément ou que la propriété vaut `null`/`undefined`, `def` est renvoyé.\n\nExample: Nom par id\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nRenvoie un nouveau tableau sans les éléments correspondants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | Une fonction, un nom de propriété ou un élément. |\n| `value` | `Object` | no |  | La valeur de la propriété. |\n\nReturns: `Array` Un nouveau tableau.\n\nLes arguments sont les mêmes que pour `Array.findItem()`. Le tableau d'origine n'est pas modifié, affecte donc le résultat.\n\nExample: Supprimer des éléments\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nRenvoie les `count` premiers éléments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre d'éléments. |\n\nReturns: `Array` Un nouveau tableau.\n\nLe résultat est un nouveau tableau.\n\nExample: Les trois premiers\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nRenvoie les éléments situés après les `count` premiers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre d'éléments ignorés. |\n\nReturns: `Array` Un nouveau tableau.\n\nAvec `Array.take()`, elle permet une pagination simple.\n\nExample: Pagination\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nRenvoie le premier élément, ou `def` pour un tableau vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | La valeur pour un tableau vide. |\n\nReturns: `Object`\n\nExample: Premier élément\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nRenvoie le dernier élément, ou `def` pour un tableau vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | La valeur pour un tableau vide. |\n\nReturns: `Object`\n\nExample: Dernier élément\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nTrie le tableau sur place.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Les propriétés de tri, ou `true` pour des valeurs primitives en ordre décroissant. |\n| `desc` | `Boolean` | no | `false` | Trier par ordre décroissant. |\n\nReturns: `Array` Le même tableau.\n\n`sort` est un nom de propriété avec un suffixe facultatif `_asc` ou `_desc`, par exemple `'name'` ou `'price_desc'`. Plusieurs propriétés sont séparées par des virgules (`'name_asc,price_desc'`) et les propriétés imbriquées utilisent des points. Les chaînes, nombres, booléens et dates sont comparés selon leur type. Avec `desc` à `true`, l'ordre est inversé.\n\nSans arguments, les valeurs primitives sont triées par ordre croissant ; `quicksort(true)` les trie par ordre décroissant.\n\nExample: Trier des objets\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nCrée un objet (une table de correspondance) à partir du tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | La propriété utilisée comme clé. |\n\nReturns: `Object` L'objet de correspondance.\n\nAvec `name`, chaque élément est stocké sous la valeur de sa propriété `name`. Sans lui, chaque élément devient une clé avec la valeur `true`.\n\nExample: Tables de correspondance\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nSupprime les espaces superflus des chaînes et retire les éléments vides.\n\nReturns: `Array` Un nouveau tableau.\n\nLes chaînes sont débarrassées de leurs espaces superflus, et les éléments vides après ce nettoyage (ou valant `null`, `0`, `false`) sont retirés. Elle renvoie un nouveau tableau.\n\nExample: Nettoyer une liste\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nTraite les éléments un par un avec une fonction asynchrone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | La fonction `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Appelé après le dernier élément. |\n| `thread` | `Number|Boolean` | no | `1` | Le nombre d'éléments en parallèle, ou `true` pour retirer les éléments. |\n\nReturns: `Array` Le même tableau.\n\n`onItem(item, next, index)` est appelée pour chaque élément ; appelle `next()` pour continuer. `callback` est appelé après le dernier élément. `thread` définit combien d'éléments sont traités simultanément (par défaut 1). Avec `thread` à `true`, les éléments sont retirés du tableau pendant leur traitement. Appelle `next('cancel')` pour arrêter ; `callback` reçoit alors `'cancel'`.\n\nExample: Envoyer des e-mails un par un\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nExécute un tableau de fonctions asynchrones.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Le nombre de fonctions en parallèle. |\n| `callback` | `Function` | no |  | Appelé à la fin. |\n\nReturns: `Array` Le même tableau.\n\nChaque élément est une fonction `function(next)`. Les éléments sont retirés du tableau au fur et à mesure de leur exécution. `thread` définit combien de fonctions s'exécutent simultanément (par défaut 1). `callback` est appelé après la dernière fonction, ou avec `'cancel'` quand une fonction appelle `next('cancel')`.\n\nExample: Une liste de tâches\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nTraite le tableau par lots de `max` éléments.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La taille d'un lot. |\n| `fn` | `Function` | yes |  | La fonction `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Appelé après le dernier lot. |\n\nReturns: `Array` Le même tableau.\n\n`fn(items, next, beg, end)` reçoit le lot suivant ; appelle `next()` pour passer au lot d'après. `callback` est appelé après le dernier lot.\n\nExample: Insérer par lots\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nMélange le tableau, ou renvoie un élément aléatoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Renvoyer un élément aléatoire. |\n\nReturns: `Array|Object`\n\nSans arguments, le tableau est mélangé sur place (Fisher-Yates) et renvoyé. Avec `item` à `true`, un élément aléatoire est renvoyé et le tableau n'est pas modifié.\n\nExample: Mélanger et choisir\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nAnalyse un texte CSV en un tableau d'objets.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Le délimiteur de colonnes. |\n\nReturns: `Object[]` Un objet par ligne, avec les clés `a`, `b`, `c`...\n\nChaque ligne devient un objet. Les colonnes sont nommées par des lettres : la première est `a`, la deuxième `b`, et ainsi de suite. Les valeurs entre guillemets doubles peuvent contenir le délimiteur et des sauts de ligne, et `\"\"` entre guillemets est un guillemet échappé. Toutes les valeurs restent des chaînes, et une colonne vide n'a pas de clé dans l'objet. Une ligne d'en-tête n'est pas détectée, elle revient donc comme premier objet.\n\nExample: Lire un fichier CSV\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nLit le système d'exploitation, le navigateur et le type d'appareil à partir d'une chaîne user agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Renvoyer un objet au lieu d'un texte. |\n\nReturns: `String|Object` Les noms détectés, ou `{ os, browser, device }`.\n\nSans argument, la méthode renvoie un court texte avec les noms détectés, comme `Mac Chrome` ou `iOS iPhone Mobile Safari`. Avec `structured` à `true`, elle renvoie un objet `{ os, browser, device }`, où `device` vaut `desktop`, `mobile`, `tablet` ou `tv`. Une chaîne vide renvoie une chaîne vide.\n\nExample: Détecter le client\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nAnalyse un texte `application/x-www-form-urlencoded` en un objet.\n\nReturns: `Object` Les clés et les valeurs analysées.\n\nLe texte ressemble à une query string : `key=value&key2=value2`. `+` devient une espace et les séquences `%xx` sont décodées. Toutes les valeurs restent des chaînes ; une clé répétée joint ses valeurs par une virgule. Les clés ne peuvent contenir que des lettres, des chiffres et `-`, `_`, `.`, `[`, `]`, et l'analyse s'arrête au premier autre caractère rencontré dans une clé. Le nombre de clés est limité par `CONF.default_request_maxkeys` et la longueur d'une clé par `CONF.default_request_maxkey`.\n\nExample: Analyser le corps d'un formulaire\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nAnalyse du XML en un objet plat de chemins et de valeurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Remplacer les caractères spéciaux des clés par `_`. |\n\nReturns: `Object` L'objet plat de chemins.\n\nChaque élément contenant du texte devient une clé composée des noms des éléments joints par des points, par exemple `book.title`. Un élément répété donne un tableau de valeurs. Les attributs d'un élément sont stockés sous forme d'objet sous le chemin suivi de `[]`. Les sections `CDATA` sont lues comme du texte et les commentaires sont ignorés. Avec `replace` à `true`, les caractères `[`, `]`, `:`, `.` et `_` des clés sont remplacés par `_`.\n\nExample: Lire un flux XML\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nAnalyse du HTML en un arbre d'éléments que tu peux parcourir et modifier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Supprimer les espaces superflus du contenu texte. |\n\nReturns: `HTMLElement` L'élément racine du document analysé.\n\nLa méthode utilise l'analyseur HTML intégré et renvoie l'élément racine. Les éléments ont `tagName`, `attrs`, `children` et `parentNode`, ainsi que les méthodes `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` et `html([formatted])`. Avec `trim` à `true`, le texte à l'intérieur des éléments est débarrassé de ses espaces superflus.\n\nExample: Lire et modifier du HTML\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nExtrait d'un texte des blocs balisés et renvoie leur contenu par nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | Le nom et la balise ouvrante de chaque bloc. |\n\nReturns: `Object` Le contenu de chaque bloc trouvé.\n\n`tags` associe un nom à une balise ouvrante, par exemple `{ js: '<script>', css: '<style>' }`. Pour chaque nom, le contenu entre la balise ouvrante et sa balise fermante est renvoyé (les balises imbriquées du même type sont comptées). Une balise absente ne donne pas de clé. Total.js l'utilise pour lire la partie `<script total>` des plugins et des composants `.html`.\n\nExample: Découper un fichier de composant\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nAnalyse ligne par ligne la sortie en colonnes d'une commande de terminal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Les noms d'en-tête ou les expressions régulières des colonnes. |\n| `fn` | `Function` | yes |  | Appelée sous la forme `fn(values, index, count, line)` pour chaque ligne. |\n| `skip` | `Number` | no | `0` | Le nombre de lignes à ignorer. |\n| `take` | `Number` | no | `all` | Le nombre de lignes à lire. |\n\nReturns: `String` La même chaîne.\n\nAvec `fields`, la première ligne non vide (parmi les trois premières) est l'en-tête. Chaque champ est un nom d'en-tête (`String`) ou une `RegExp` qui trouve la colonne dans la ligne d'en-tête, et `fn` reçoit les valeurs de ces colonnes pour chaque ligne suivante. Sans `fields`, chaque ligne est découpée en mots et `fn` reçoit le tableau des mots. `fn(values, index, count, line)` reçoit les valeurs, l'indice de la ligne analysée, l'indice de fin et le numéro de ligne. `skip` et `take` limitent les lignes. La méthode renvoie la chaîne elle-même.\n\nExample: Lire la sortie de df\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nAnalyse un texte au format de configuration Total.js en un objet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Les valeurs par défaut copiées dans le résultat. |\n| `onerror` | `Function` | no |  | Appelée sous la forme `onerror(err, line)` quand une valeur `object` ou `eval` échoue. |\n\nReturns: `Object` Les valeurs analysées.\n\nChaque ligne est `key : value`, et les lignes commençant par `#` ou `//` sont ignorées. La valeur commence deux caractères après le premier `:`, écris donc une espace après les deux-points. Un type entre parenthèses après la clé convertit la valeur : `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (séparé par des virgules), `(json)`, `(object)` ou `(eval)` (évalué comme du JavaScript), `(date)`, `(env)` (une variable d'environnement), `(config)` (une autre clé `CONF`) et `(random)` (une chaîne aléatoire de la longueur indiquée). `def` fournit les valeurs par défaut. `onerror(err, line)` gère une valeur qui ne peut pas être évaluée ; sans lui, la méthode lève une exception.\n\nExample: Analyser un texte de configuration\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nTransforme un texte comme `5 minutes` en une date future.\n\nReturns: `Date` La date actuelle plus la durée indiquée.\n\nLe texte est lu sous forme de paires d'un nombre et d'une unité, séparées par des espaces, par exemple `1 day 12 hours`. Chaque paire est ajoutée à la date actuelle avec `Date.add()`, les mêmes unités fonctionnent donc (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Une paire dont le nombre est `0` est ignorée.\n\nExample: Expiration d'un cookie\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nLit les informations stockées dans un identifiant créé par `UID()`.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nLe résultat contient `version` (le dernier caractère de l'UID), `date` (sa date de création), `century`, `index` (le compteur), `hash` et `valid`. Pour la version aléatoire `r` (`CONF.default_uid = 'r'`), le résultat n'a pas de date, et les identifiants sont validés avec `String.isUID()`.\n\nExample: Quand un enregistrement a-t-il été créé\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nTrouve le premier nombre décimal dans un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | La valeur renvoyée quand aucun nombre n'est trouvé. |\n\nReturns: `Number` Le nombre trouvé.\n\nContrairement à `String.parseFloat()`, le texte peut contenir d'autres caractères : le premier groupe de chiffres, de points et de virgules est utilisé, et les virgules deviennent des points. Un `-` initial le rend négatif. Sans nombre, la méthode renvoie `def`.\n\nExample: Prix à partir d'un libellé\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nVérifie si la chaîne est un GUID (UUID).\n\nReturns: `Boolean`\n\nLa chaîne doit comporter 36 caractères au format `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, où `M` est une version de 1 à 5. Les lettres majuscules et minuscules sont acceptées.\n\nExample: Valider un UUID\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nVérifie si la chaîne est une date au format JSON (ISO 8601 UTC).\n\nReturns: `Boolean`\n\nLa méthode vérifie la forme du texte, comme `2024-05-01T10:30:00.000Z` : la longueur, le `T`, les tirets et les deux-points, ainsi que le `Z` final. Elle ne vérifie pas que la date existe.\n\nExample: Reconstituer des dates\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nVérifie si la chaîne ne contient que des chiffres.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Autoriser un séparateur décimal. |\n\nReturns: `Boolean`\n\nAvec `decimal` à `true`, un `.` ou une `,` est également autorisé. Les signes, les espaces et les exposants ne sont pas acceptés, et une chaîne vide renvoie `false`.\n\nExample: Vérifier une saisie utilisateur\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nVérifie si la chaîne vaut `true` ou `false`.\n\nReturns: `Boolean`\n\nLa comparaison ignore la casse. Les autres valeurs comme `1` ou `on` renvoient `false` ; `String.parseBoolean()` les lit.\n\nExample: Vérifier une valeur de query\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nVérifie si la chaîne ressemble à un code postal (ZIP).\n\nReturns: `Boolean`\n\nLa chaîne est testée avec `DEF.validators.zip`, par défaut 3 à 20 lettres, chiffres, espaces ou tirets. Modifie `DEF.validators.zip` pour utiliser ta propre règle.\n\nExample: Valider un code postal\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nVérifie si la chaîne contient une balise HTML.\n\nReturns: `Boolean`\n\nLe test est simple : il renvoie `true` quand le texte contient `<` suivi plus loin de `>`. Utilise-le pour refuser du HTML dans les champs de texte brut.\n\nExample: Refuser du HTML\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nVérifie si la chaîne contient un texte entre guillemets ou un mot-clé SQL.\n\nReturns: `Boolean`\n\nLa méthode renvoie `true` pour un texte entre guillemets simples ou pour les mots en majuscules `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` et `UNION`. C'est une vérification grossière ; utilise de toute façon des paramètres dans tes requêtes.\n\nExample: Vérifier une phrase de recherche\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nVérifie si la chaîne est encodée en base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Accepter un préfixe de data URI. |\n\nReturns: `Boolean`\n\nLa longueur doit être divisible par 4 et le texte ne doit contenir que des caractères base64. Avec `data` à `true`, une data URI comme `data:image/png;base64,...` est acceptée et seule la longueur de la partie encodée est vérifiée.\n\nExample: Vérifier un envoi de fichier\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nÉcrit des données base64 dans un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le chemin du fichier. |\n| `callback` | `Function` | no |  | Appelé sous la forme `callback(err)` quand le fichier est écrit. |\n\nReturns: `String` La même chaîne.\n\nUn préfixe de data URI (tout ce qui précède la première virgule) est supprimé, et le reste est décodé et écrit avec `fs.writeFile()`. La méthode renvoie la chaîne elle-même ; le résultat de l'écriture arrive dans `callback(err)`.\n\nExample: Enregistrer une image envoyée\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDécode des données base64 en un `Buffer`.\n\nReturns: `Buffer` Les données décodées.\n\nUn préfixe de data URI (tout ce qui précède la première virgule) est supprimé avant le décodage.\n\nExample: Décoder une data URI\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nRenvoie le type de contenu d'une data URI.\n\nReturns: `String` Le type de contenu, par exemple `image/png`.\n\nLe texte entre `data:` et le premier `;` est renvoyé. Une chaîne sans `;` renvoie une chaîne vide.\n\nExample: Vérifier le type d'un envoi de fichier\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nCalcule la somme de contrôle CRC32 de la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Renvoyer un nombre non signé. |\n\nReturns: `Number` La somme de contrôle.\n\nLe résultat est un nombre signé sur 32 bits, ou non signé quand `unsigned` vaut `true`. `String.hash('crc32')` et `String.hash('crc32unsigned')` donnent les mêmes résultats.\n\nExample: Somme de contrôle d'un texte\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nCrée un hachage SHA-1 de la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String` Le hachage en hexadécimal.\n\nLe `salt` est ajouté à la chaîne avant le hachage.\n\nExample: Hachage SHA-1\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nCrée un hachage SHA-512 de la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Texte ajouté avant le hachage. |\n\nReturns: `String` Le hachage en hexadécimal.\n\nLe `salt` est ajouté à la chaîne avant le hachage.\n\nExample: Hacher un jeton\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nCrée un id court à partir de la chaîne.\n\nReturns: `String` L'id.\n\nL'id est un hachage rapide non signé de la chaîne écrit en base 36. La même chaîne donne toujours le même id. Ce n'est pas un hachage cryptographique.\n\nExample: Id pour une clé de cache\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nAjoute une somme de contrôle rapide à la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Un secret mélangé à la somme de contrôle. |\n\nReturns: `String` La chaîne avec la somme de contrôle.\n\nLe résultat est la chaîne, un tiret et un hachage en base 36 de la chaîne avec `key`. Pour vérifier une valeur, signe à nouveau la partie précédant le dernier tiret et compare. C'est une somme de contrôle rapide, pas une signature cryptographique.\n\nExample: Signer et vérifier une valeur\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nProtège un identifiant avec une somme de contrôle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Le secret. |\n\nReturns: `String` L'identifiant protégé.\n\nLe résultat est `x`, une somme de contrôle et `x` suivis de la valeur d'origine ; la valeur reste donc lisible mais ne peut pas être modifiée sans la clé. La somme de contrôle utilise `key` (par défaut `CONF.secret`) et `CONF.secret_uid`. Relis-la avec `String.decrypt_uid()`. La même fonction pour les nombres est `U.encrypt_uid(value, [key])`.\n\nExample: Id protégé dans un lien\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nLit un identifiant protégé avec `String.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Le secret utilisé pour `encrypt_uid()`. |\n\nReturns: `String|Number` La valeur d'origine, ou `null` quand la somme de contrôle est incorrecte.\n\nLa somme de contrôle est recalculée avec `key` (par défaut `CONF.secret`). Si elle correspond, la valeur d'origine est renvoyée, sinon `null`. Une valeur créée à partir d'un nombre revient sous forme de nombre.\n\nExample: Vérifier un lien\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nNettoie un nom de personne : supprime les autres caractères et met une majuscule à chaque mot.\n\nReturns: `String` Le nom nettoyé.\n\nLes chiffres et la ponctuation ASCII sont supprimés, les espaces sont conservées, et la première lettre de chaque mot est mise en majuscule. Les lettres avec signes diacritiques sont conservées. Les espaces finales sont supprimées, mais pas les espaces initiales ni répétées, nettoie donc d'abord l'entrée.\n\nExample: Nettoyer un nom issu d'un formulaire\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nÉchappe les caractères hors de l'ASCII imprimable sous la forme `\\uXXXX`.\n\nReturns: `String` La chaîne échappée.\n\nLes caractères dont le code est inférieur à 32 ou supérieur à 126 sont écrits sous la forme `\\u` suivi de quatre chiffres hexadécimaux. `String.fromUnicode()` fait l'inverse.\n\nExample: Échapper un texte\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nRetransforme les séquences d'échappement `\\uXXXX` en caractères.\n\nReturns: `String` La chaîne sans échappement.\n\nChaque `\\u` suivi de quatre chiffres hexadécimaux est remplacé par le caractère. C'est l'inverse de `String.toUnicode()`.\n\nExample: Supprimer l'échappement d'un texte\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nVérifie si la chaîne se termine par un texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Le texte à trouver. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true` pour ignorer la casse, ou un décalage depuis la fin. |\n\nReturns: `Boolean`\n\nTotal.js remplace la méthode native. Avec `ignoreCase` à `true`, la casse est ignorée. Un nombre à la place de `ignoreCase` vérifie le texte situé ce nombre de caractères avant la fin.\n\nExample: Vérifier une extension de fichier\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nRemplace la première occurrence d'un texte, sans expressions régulières.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | Le texte à remplacer. |\n| `text` | `String` | yes |  | Le nouveau texte. |\n\nReturns: `String` La nouvelle chaîne.\n\n`find` est du texte brut, les caractères comme `$` ou `.` n'ont donc aucune signification particulière ni dans celui-ci ni dans `text`. Quand `find` est introuvable, la chaîne est renvoyée telle quelle.\n\nExample: Insérer un prix dans un modèle\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nInsère une valeur à une position de la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | La position. |\n| `value` | `Object` | yes |  | La valeur à insérer. |\n\nReturns: `String` La nouvelle chaîne.\n\nLa valeur est convertie en chaîne avec `toString()`.\n\nExample: Formater un code\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nAjoute un caractère au début de la chaîne un certain nombre de fois.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Combien de caractères ajouter. |\n| `char` | `String` | no | `' '` | Le caractère. |\n\nReturns: `String` La chaîne indentée.\n\nContrairement à `String.padLeft()`, les caractères sont toujours ajoutés, quelle que soit la longueur de la chaîne.\n\nExample: Indenter une ligne\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nChoisit une forme de mot selon le nombre contenu dans la chaîne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forme pour 0, ou toutes les formes séparées par des virgules. |\n| `one` | `String` | no |  | La forme pour 1. |\n| `few` | `String` | no |  | La forme pour 2 à 4. |\n| `other` | `String` | no |  | La forme pour les autres nombres. |\n\nReturns: `String` La forme choisie.\n\nLa chaîne est lue avec `String.parseInt()` et transmise à `Number.pluralize()` ; les règles et le placeholder `#` sont donc les mêmes.\n\nExample: Nombre issu d'une query\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nRemplace les placeholders `[key]` par des valeurs de configuration.\n\nReturns: `String` La chaîne avec les valeurs.\n\nChaque `[key]` (lettres, chiffres et `_`) est remplacé par `CONF[key]` ; une clé manquante donne une chaîne vide.\n\nExample: Construire une URL à partir de la configuration\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nTrouve des blocs dans une chaîne et passe chacun à un callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | Le délimiteur de début, ou le séparateur quand `end` est absent. |\n| `end` | `String` | no |  | Le délimiteur de fin. |\n| `callback` | `Function` | yes |  | Appelé sous la forme `callback(value, index)` ; renvoie `false` pour arrêter. |\n| `skip` | `Number` | no | `0` | Le nombre de blocs à ignorer. |\n\nReturns: `undefined`\n\nAvec `beg` et `end`, chaque bloc qui commence par `beg` et se termine par `end` est transmis, délimiteurs compris. Sans `end`, la chaîne est découpée après chaque `beg`, et chaque partie se termine par `beg`. `callback(value, index)` peut renvoyer `false` pour arrêter. `skip` ignore les premiers blocs.\n\nExample: Lire des éléments depuis du XML\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nArrondit le nombre à un nombre de décimales et renvoie un nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Le nombre de décimales. |\n\nReturns: `Number` Le nombre arrondi.\n\nIdentique à `+number.toFixed(decimals)` : contrairement à `toFixed()`, le résultat est un nombre, pas une chaîne.\n\nExample: Arrondir un prix\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormate le nombre avec un formateur de devise issu de `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La clé dans `DEF.currencies`. |\n| `a` | `Object` | no |  | Transmis au formateur, comme `b` et `c`. |\n\nReturns: `String` Le prix formaté.\n\n`DEF.currencies` est vide par défaut ; ajoute une fonction `function(value, a, b, c)` pour chaque code de devise dont tu as besoin, et `default` pour les appels sans code. Les arguments supplémentaires lui sont transmis. Sans formateur, le nombre est formaté avec `Number.format(2)`.\n\nExample: Enregistrer et utiliser des devises\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nConvertit le nombre en hexadécimal majuscule.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | La longueur minimale. |\n\nReturns: `String` La valeur hexadécimale.\n\nLe résultat est complété par des zéros en tête jusqu'à `length` caractères.\n\nExample: Composante de couleur\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nCrée une date à partir d'un horodatage en millisecondes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Les millisecondes à ajouter. |\n\nReturns: `Date` La date.\n\n`plus` millisecondes sont ajoutées au nombre avant la création de la date.\n\nExample: Date à partir d'un horodatage\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nConvertit des degrés en radians.\n\nReturns: `Number` L'angle en radians.\n\nDéfinie uniquement lorsque `Number.prototype.toRad` n'existe pas encore.\n\nExample: Distance entre deux points GPS\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nRenvoie la date elle-même.\n\nReturns: `Date` La même date.\n\nElle te permet d'appeler `parseDate()` sur une valeur qui peut être une chaîne, un nombre ou une date, sans vérifier son type au préalable.\n\nExample: Valeur de type inconnu\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Prototipi","summary":"Metodi di String, Number, Date e Array aggiunti da Total.js 4.","markdown":"---\ntitle: Prototipi\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototipi\n\n> Metodi di String, Number, Date e Array aggiunti da Total.js 4.\n\nMetodi che Total.js 4 aggiunge a `String`, `Number`, `Date` e `Array`. La guida [Prototipi](../../guides/prototypes/) spiega come usarli con esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nSostituisce i segnaposto indicizzati `{0}`, `{1}`... con gli argomenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | Il valore per `{0}`. Può seguire un numero qualsiasi di argomenti. |\n\nReturns: `String` La stringa formattata.\n\nOgni `{n}` viene sostituito con l'argomento all'indice `n`. Un argomento `null` o `undefined` produce una stringa vuota. Per i segnaposto con nome usa `String.args()`.\n\nExample: Segnaposto indicizzati\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nSostituisce i segnaposto con nome `{key}` o `{{key}}` con i valori di un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | I valori. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (codifica URL), `'html'`, `'json'` o una funzione `function(value, key)`. |\n| `def` | `String` | no |  | Il testo per un valore mancante. Viene ignorato quando `encode` è una stringa. |\n\nReturns: `String` La stringa con i valori.\n\nLe chiavi possono contenere lettere, numeri, `_`, `$`, `.` e `-`. Un valore mancante mantiene il segnaposto, oppure usa `def` quando lo imposti.\n\nL'argomento `encode` cambia il modo in cui vengono scritti i valori: `true` li codifica con `encodeURIComponent()`, `'html'` codifica le entità HTML, `'json'` scrive `JSON.stringify(value)` e una funzione `function(value, key)` restituisce il testo stesso. `String.arg()` è un alias.\n\nExample: Segnaposto con nome\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: Codifica HTML\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: Un valore predefinito per i valori mancanti\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nCrea uno slug adatto agli URL a partire dal testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | La lunghezza massima. |\n\nReturns: `String` Lo slug.\n\nIl testo viene privato degli spazi esterni, convertito in minuscolo e in ASCII (senza segni diacritici). Spazi e punteggiatura diventano un unico `-`; un `-` finale viene rimosso. Il risultato viene tagliato a `max` caratteri.\n\nQuando il testo non ha caratteri latini utilizzabili (per esempio cinese o cirillico), il metodo restituisce invece un breve hash costruito dal testo.\n\nExample: Slug da un titolo\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nTaglia il testo a una lunghezza massima e aggiunge i puntini di sospensione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | La lunghezza massima del risultato. |\n| `chars` | `String` | no | `'...'` | Il testo aggiunto a una stringa tagliata. |\n\nReturns: `String` Il testo accorciato.\n\nQuando il testo è più lungo di `length`, viene tagliato in modo che il risultato con `chars` abbia esattamente `length` caratteri. Un testo più corto viene restituito invariato.\n\nExample: Accorciare una descrizione\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nRende maiuscola la prima lettera di ogni parola.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Rendere maiuscola solo la prima lettera. |\n\nReturns: `String` Il testo con le iniziali maiuscole.\n\nIl testo viene convertito in minuscolo e ogni lettera dopo uno spazio, una tabulazione o un a capo diventa maiuscola. Con `first` impostato su `true`, diventa maiuscola solo la prima lettera dell'intero testo.\n\nExample: Parole e prima lettera\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nConverte l'intera stringa in un numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore restituito quando la stringa non è un numero. |\n\nReturns: `Number` Il numero, oppure `def`.\n\nLa stringa viene privata degli spazi esterni e convertita con l'operatore unario `+`, quindi l'intera stringa deve essere un numero: `'12px'` non è un numero e restituisce `def`. Per leggere un numero da un testo più lungo, usa `String.parseInt2()`.\n\nExample: Parametro della query\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nLegge il primo intero trovato nel testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore restituito quando il testo non contiene numeri. |\n\nReturns: `Number` Il numero, oppure `def`.\n\nA differenza di `String.parseInt()`, il numero può essere circondato da altro testo. Un `-` iniziale viene mantenuto. `String.parseFloat2()` funziona allo stesso modo per i numeri decimali (è accettato il separatore decimale `,`).\n\nExample: Numero all'interno del testo\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nConverte la stringa in un numero decimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore restituito quando la stringa non è un numero. |\n\nReturns: `Number` Il numero, oppure `def`.\n\nLa stringa viene privata degli spazi esterni e un separatore decimale `,` viene sostituito con `.`. L'intera stringa deve essere un numero, altrimenti viene restituito `def`.\n\nExample: Virgola decimale\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nConverte `true`, `1` o `on` in `true`.\n\nReturns: `Boolean`\n\nIl confronto non distingue tra maiuscole e minuscole. Qualsiasi altro valore restituisce `false`.\n\nExample: Valore di una checkbox\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nConverte la stringa in un `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Il formato dell'input, per esempio `'dd/MM/yyyy'`. |\n\nReturns: `Date` La data analizzata.\n\nSenza `format`, il metodo legge stringhe ISO (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` e qualsiasi valore che `new Date()` comprende. Una parte della data mancante usa la data odierna.\n\nCon `format`, le cifre della stringa vengono lette nell'ordine delle lettere del formato (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). Un `pm` nel testo aggiunge 12 ore.\n\nExample: Analizzare date\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nAnalizza un JSON senza sollevare eccezioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Convertire le stringhe di data ISO in date. |\n\nReturns: `Object` Il valore analizzato, oppure `undefined` per un JSON non valido.\n\nUn JSON non valido restituisce `undefined` invece di un errore. Con `date` impostato su `true`, le stringhe di data ISO vengono convertite in oggetti `Date`.\n\nExample: Analisi sicura\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nAnalizza righe `KEY=value` (il formato `.env`) e le trasforma in un oggetto.\n\nReturns: `Object` Le chiavi e i loro valori stringa.\n\nLe righe vuote e quelle che iniziano con `#` o `//` vengono saltate. I valori tra virgolette doppie o singole perdono le virgolette, e `\\n` diventa un a capo. I valori senza virgolette vengono privati degli spazi esterni.\n\nExample: Leggere un file .env\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nVerifica se la stringa è un indirizzo email.\n\nReturns: `Boolean`\n\nIl test usa l'espressione regolare `DEF.validators.email`, quindi puoi sostituirla. Le stringhe di 4 caratteri o meno sono sempre `false`.\n\nExample: Validare l'input\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nVerifica se la stringa è un numero di telefono.\n\nReturns: `Boolean`\n\nIl test usa l'espressione regolare `DEF.validators.phone`. Le stringhe più corte di 6 caratteri sono sempre `false`.\n\nExample: Numero di telefono\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nVerifica se la stringa è un indirizzo URL.\n\nReturns: `Boolean`\n\nIl test usa l'espressione regolare `DEF.validators.url`. Le stringhe di 7 caratteri o meno sono sempre `false`.\n\nExample: Indirizzo URL\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nVerifica se la stringa è un identificatore valido creato da `UID()`.\n\nReturns: `Boolean`\n\nIl metodo verifica il formato con `DEF.validators.uid` e poi il checksum che `UID()` scrive in ogni identificatore, quindi una stringa casuale con i caratteri giusti non viene accettata.\n\nExample: Validare un id dall'URL\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nVerifica se la stringa sembra un JSON.\n\nReturns: `Boolean`\n\nVengono controllati solo il primo e l'ultimo carattere non bianco: `{...}`, `[...]`, `\"...\"` o un numero. Il contenuto non viene analizzato; per questo usa `String.parseJSON()`.\n\nExample: Test rapido\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nCrea un hash della stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | L'algoritmo, oppure `true` per un hash numerico senza segno. |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String|Number` Una stringa esadecimale per md5/sha*, altrimenti un numero.\n\n`type` sceglie l'algoritmo: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (stringhe esadecimali), `'crc32'` o `'crc32unsigned'` (numeri). Senza tipo, il metodo restituisce un hash numerico veloce a 32 bit; `true` lo rende senza segno. Il `salt` viene aggiunto alla stringa prima del calcolo dell'hash.\n\nExample: Hash diversi\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nRestituisce l'hash MD5 come stringa esadecimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String` Una stringa esadecimale di 32 caratteri.\n\nIl `salt` viene aggiunto alla stringa prima del calcolo dell'hash. Usalo per checksum e chiavi di cache, non per le password.\n\nExample: Chiave di cache\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nRestituisce l'hash SHA-256 come stringa esadecimale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String` Una stringa esadecimale di 64 caratteri.\n\nIl `salt` viene aggiunto alla stringa prima del calcolo dell'hash. `String.sha1([salt])` e `String.sha512([salt])` funzionano allo stesso modo con gli altri algoritmi.\n\nExample: Hash con un salt\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nCodifica i caratteri speciali HTML.\n\nReturns: `String` Il testo codificato.\n\nSostituisce `<`, `>`, `\"`, `'` e `&` con entità HTML, così il testo può essere scritto in modo sicuro nell'HTML.\n\nExample: Escape dell'input dell'utente\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDecodifica le entità HTML riportandole a caratteri.\n\nReturns: `String` Il testo decodificato.\n\nVengono convertite le entità con nome e quelle numeriche (`&#65;`, `&#x41;`). È l'opposto di `String.encode()`.\n\nExample: Decodificare\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nCifra la stringa con una chiave.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave di cifratura. |\n| `isUnique` | `Boolean` | no | `false` | Rendere diverso ogni risultato. |\n| `secret` | `String` | no | `CONF.secret` | Un segreto aggiuntivo. |\n\nReturns: `String` La stringa cifrata.\n\nCon `isUnique` impostato su `true`, ogni chiamata dà un risultato diverso per lo stesso input. Il risultato contiene un checksum creato da `secret` (predefinito `CONF.secret`) e dalla chiave, che `String.decrypt()` verifica. Usalo per token e URL, non per salvare password.\n\nExample: Cifrare un token\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nDecifra una stringa creata da `String.encrypt()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave di cifratura. |\n| `secret` | `String` | no | `CONF.secret` | Il segreto aggiuntivo. |\n\nReturns: `String` La stringa originale, oppure `null`.\n\nUsa la stessa `key` e lo stesso `secret` della cifratura. Una chiave errata, un segreto errato o una stringa modificata restituiscono `null`.\n\nExample: Decifrare un token\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nEstrae le parole chiave dal testo, ordinate per frequenza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Normalizzare le parole per la ricerca. |\n| `alternative` | `Boolean` | no | `false` | Accorciare ogni parola all'80% della sua lunghezza. |\n| `max_count` | `Number` | no | `200` | Il numero massimo di parole lette. |\n| `max_length` | `Number` | no | `20` | La lunghezza massima di una parola. |\n| `min_length` | `Number` | no | `2` | La lunghezza minima di una parola. |\n\nReturns: `String[]` Parole univoche, prima le più frequenti.\n\nCon `forSearch` (predefinito `true`) il testo viene convertito in ASCII e `y` diventa `i`, il che rende la ricerca più tollerante. Con `alternative`, ogni parola viene accorciata all'80% della sua lunghezza. Le parole più corte di `min_length` o più lunghe di `max_length` vengono saltate. `String.toKeywords()` è un alias.\n\nExample: Parole chiave per un indice di ricerca\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormalizza il testo per una ricerca full-text.\n\nReturns: `String` Il testo normalizzato.\n\nIl testo viene convertito in minuscolo e in ASCII, i caratteri speciali vengono rimossi, `y` diventa `i` e le lettere ripetute vengono unite. Applicalo sia al testo salvato sia alla frase cercata.\n\nExample: Valore di ricerca\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nRimuove i segni diacritici dal testo.\n\nReturns: `String` Il testo senza segni diacritici.\n\nLe lettere accentate vengono sostituite con le loro lettere latine di base, per esempio `á` con `a`.\n\nExample: Rimuovere i segni diacritici\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nRimuove i tag HTML dal testo.\n\nReturns: `String` Il testo semplice.\n\nVengono rimossi solo i tag; il testo tra di essi resta. Le entità HTML non vengono decodificate.\n\nExample: Testo semplice\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nRiempie la stringa a sinistra fino alla lunghezza `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza finale. |\n| `c` | `String` | no | `' '` | Il carattere di riempimento. |\n\nReturns: `String` La stringa riempita.\n\nUna stringa che ha già `max` caratteri o più viene restituita invariata.\n\nExample: Zeri iniziali\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nRiempie la stringa a destra fino alla lunghezza `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza finale. |\n| `c` | `String` | no | `' '` | Il carattere di riempimento. |\n\nReturns: `String` La stringa riempita.\n\nUna stringa che ha già `max` caratteri o più viene restituita invariata.\n\nExample: Colonna a larghezza fissa\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nVerifica se la stringa inizia con `text`, eventualmente ignorando maiuscole e minuscole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Il testo da cercare. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true` per ignorare maiuscole e minuscole, oppure una posizione iniziale. |\n\nReturns: `Boolean`\n\nTotal.js sostituisce il metodo nativo. Con `ignoreCase` impostato su `true` il confronto ignora maiuscole e minuscole; un numero viene usato come posizione iniziale. `String.endsWith(text, [ignoreCase])` funziona allo stesso modo alla fine della stringa.\n\nExample: Ignorare maiuscole e minuscole\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nConverte Markdown in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | Le opzioni descritte sopra. |\n\nReturns: `String` L'HTML.\n\nIl risultato viene racchiuso in `<div class=\"markdown markdown-container\">` a meno che `opt.wrap` sia `false`. La maggior parte delle funzionalità è attiva per impostazione predefinita e ne disattivi una con `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Altre opzioni: `linetag` (il tag di un paragrafo, predefinito `'p'`), `prefix` (un prefisso per gli id generati), `custom` (una funzione che modifica ogni riga) e `html` (una funzione `function(html, type)` che modifica l'HTML generato).\n\nExample: Render del Markdown\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Senza contenitore e senza immagini\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nRimuove gli slash finali.\n\nReturns: `String` La stringa senza slash finali.\n\nTutti i caratteri `/` alla fine vengono rimossi, ma un singolo `/` viene mantenuto, quindi `'/'` resta `'/'`.\n\nExample: Pulire un URL\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nCrea un oggetto schema JSON da una definizione inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome dello schema usato in `$id`. |\n| `url` | `String` | no | `CONF.url` | L'URL di base di `$id`. |\n\nReturns: `Object` Lo schema JSON.\n\nLa definizione è un elenco di coppie `name:type` separate da virgole o da a capo. Un `*` o `!` prima del nome rende il campo obbligatorio. Tipi: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` imposta una lunghezza massima, `[string]` crea un array, `{draft|published}` un enum e `@name` usa un altro schema.\n\nL'`$id` viene costruito da `url` (predefinito `CONF.url`) e `name`.\n\nExample: Schema inline\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nFormatta il numero con un separatore delle migliaia e i decimali.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Il numero di decimali. |\n| `separator` | `String` | no | `' '` | Il separatore delle migliaia. |\n| `separatorDecimal` | `String` | no | `'.'` | Il separatore decimale. |\n\nReturns: `String` Il numero formattato.\n\nIl separatore delle migliaia predefinito è uno spazio. I decimali vengono troncati (non arrotondati) o completati con zeri fino a `decimals`. Il separatore decimale è `.`, oppure `,` quando il separatore delle migliaia è `.`. Puoi anche passare prima il separatore: `format(',', 2)`.\n\nExample: Formattare i prezzi\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nSceglie la forma di una parola in base al numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forma per 0, oppure tutte le forme separate da virgole. |\n| `one` | `String` | no |  | La forma per 1. |\n| `few` | `String` | no |  | La forma da 2 a 4. |\n| `other` | `String` | no |  | La forma per gli altri numeri. |\n\nReturns: `String` La forma scelta.\n\n`zero` si usa per 0, `one` per 1, `few` da 2 a 4 e `other` per il resto. Un `#` nella forma scelta viene sostituito con il numero. Puoi anche passare tutte le forme come un'unica stringa separata da virgole.\n\nExample: Numero di elementi\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nConverte il numero in una stringa riempita a sinistra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza finale. |\n| `c` | `String` | no | `'0'` | Il carattere di riempimento. |\n\nReturns: `String` Il numero riempito.\n\nIl carattere di riempimento predefinito è `0`.\n\nExample: Numero di fattura\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nConverte il numero in una stringa riempita a destra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La lunghezza finale. |\n| `c` | `String` | no | `'0'` | Il carattere di riempimento. |\n\nReturns: `String` Il numero riempito.\n\nIl carattere di riempimento predefinito è `0`.\n\nExample: Riempimento a destra\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nArrotonda il numero a un certo numero di decimali.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | Il numero di decimali. |\n\nReturns: `Number` Il numero arrotondato.\n\nSenza `precision` il numero viene arrotondato a un intero.\n\nExample: Arrotondare\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nArrotonda il numero per difetto a un certo numero di decimali.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Il numero di decimali. |\n\nReturns: `Number` Il numero arrotondato per difetto.\n\nFunziona come `Math.floor()` con i decimali.\n\nExample: Arrotondamento per difetto\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nRestituisce un valore da una mappa di intervalli numerici.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Intervalli come chiavi e risultati come valori. |\n| `otherwise` | `Object` | yes |  | Il valore quando nessun intervallo corrisponde. |\n\nReturns: `Object` Il valore dell'intervallo corrispondente.\n\nLe chiavi di `condition` sono intervalli: `'1-5'` (da 1 a 5), `'10-'` (10 e oltre) o `'-5'` (5 e meno). Viene restituito il valore del primo intervallo corrispondente, altrimenti `otherwise`.\n\nExample: Etichetta di valutazione\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nApplica un'operazione matematica scritta come stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Un numero, oppure un'operazione come `'-5'` o `'+20%'`. |\n| `decimals` | `Number` | no |  | Arrotondare il risultato per difetto a questi decimali. |\n\nReturns: `Number` Il risultato.\n\nUn numero viene sommato. Una stringa inizia con un operatore `+`, `-`, `*` o `/` seguito da un numero, per esempio `'+10'`. Con `%` alla fine l'operando è una percentuale del numero: `'+20%'` aggiunge il 20%. Con `decimals` il risultato viene arrotondato per difetto a quel numero di decimali.\n\nExample: Operazioni\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nAggiunge l'IVA al prezzo, oppure la rimuove.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | L'aliquota IVA in percentuale. |\n| `decimals` | `Number` | no | `2` | Il numero di decimali. |\n| `includedVAT` | `Boolean` | no | `false` | Il numero include già l'IVA. |\n\nReturns: `Number` Il prezzo.\n\nSenza `includedVAT` il metodo restituisce il prezzo con IVA. Con `includedVAT` impostato su `true`, il numero è un prezzo con IVA e il metodo restituisce il prezzo senza IVA. Il risultato viene arrotondato a `decimals`.\n\nExample: Con e senza IVA\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nSottrae uno sconto in percentuale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Lo sconto in percentuale. |\n| `decimals` | `Number` | no | `2` | Il numero di decimali. |\n\nReturns: `Number` Il numero scontato.\n\nIl risultato viene arrotondato per difetto a `decimals`.\n\nExample: Sconto\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nFormatta un numero di byte come dimensione di file leggibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Il numero di decimali. |\n| `type` | `String` | no |  | L'unità: `'bytes'`, `'KB'`, `'MB'`, `'GB'` o `'TB'`. |\n\nReturns: `String` La dimensione con l'unità.\n\nSenza `type` l'unità viene scelta automaticamente (`bytes`, `KB`, `MB`, `GB` o `TB`). Con `type` il valore viene convertito in quell'unità. Senza `decimals` il valore ha fino a 2 decimali.\n\nExample: Dimensione del file\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nEsegue una funzione asincrona il numero indicato di volte, con un conto alla rovescia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | La funzione `function(number, next)`. |\n| `callback` | `Function` | no |  | Chiamata dopo l'ultima esecuzione. |\n\nReturns: `Number`\n\nLa funzione riceve il numero corrente (dal valore iniziale fino a 1) e `next`. L'esecuzione successiva inizia dopo che chiami `next()`. Quando il conteggio arriva a zero, viene chiamata `callback`.\n\nExample: Tre esecuzioni\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nRestituisce una nuova data spostata di un periodo di tempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | L'unità, un'espressione come `'5 days'`, oppure millisecondi. |\n| `value` | `Number` | no |  | La quantità. |\n\nReturns: `Date` Una nuova data.\n\nPassa un tipo e un valore (`add('days', 5)`) o un'unica espressione (`add('5 days')`). Tipi: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, anche nelle forme brevi `s`, `m`, `h`, `d`, `w`, `M`, `y`. I valori negativi spostano indietro. Un numero aggiunge millisecondi. La data originale non viene modificata.\n\nExample: Spostare le date\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nFormatta la data come stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Il formato, per esempio `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | Il file di risorse con i nomi tradotti di mesi e giorni. |\n\nReturns: `String` La data formattata.\n\nSenza `format` la data viene restituita come stringa ISO in UTC. I token di formato usano l'ora locale: `yyyy`, `yy`, `MM`, `M`, `MMM` (nome breve del mese), `MMMM` (nome del mese), `dd`, `d`, `ddd` (nome breve del giorno), `dddd` (nome del giorno), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (settimana ISO), `a` (AM/PM). I nomi di mesi e giorni sono in inglese; con `resource` vengono letti da quel file di risorse.\n\nExample: Formati\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nRestituisce la differenza tra due date in un'unità.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | La data con cui confrontare. |\n| `type` | `String` | yes |  | L'unità. |\n\nReturns: `Number` La differenza.\n\nLa differenza è `this - date`, arrotondata per eccesso. Senza `date` il metodo confronta con l'istante attuale. Unità: `seconds`, `minutes`, `hours`, `days`, `months`, `years` e le forme brevi `s`, `m`, `h`, `d`, `M`, `y`. Un mese vale 28 giorni. Un'unità sconosciuta restituisce `NaN`.\n\nExample: Giorni rimanenti\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nSposta la data dell'offset del fuso orario locale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Restituire millisecondi. |\n\nReturns: `Date|Number`\n\nIl risultato mostra l'ora UTC nei campi locali della data. Con `ticks` impostato su `true`, il metodo restituisce millisecondi invece di una data.\n\nExample: Data UTC\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nRestituisce una nuova data con alcune parti impostate da una stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Le parti di data o ora, per esempio `'12:00'` o `'2024-12-24 18:00'`. |\n\nReturns: `Date` Una nuova data.\n\nLa stringa può contenere una data (`yyyy-MM-dd` o `dd.MM.yyyy`) e un'ora (`HH:mm` o `HH:mm:ss`). Vengono modificate solo le parti indicate; sono impostate in UTC.\n\nExample: Impostare l'ora\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nRestituisce una nuova data convertita in un fuso orario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | Il nome IANA del fuso orario. |\n\nReturns: `Date` Una nuova data.\n\n`timezone` è un nome IANA come `'Europe/Bratislava'`.\n\nExample: Ora a New York\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nRestituisce il primo elemento corrispondente, oppure `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |\n| `value` | `Object` | no |  | Il valore della proprietà. |\n\nReturns: `Object` L'elemento, oppure `null`.\n\n`cb` è una funzione `function(item, index)`, oppure il nome di una proprietà confrontata con `value` (`===`). Con un unico argomento che non è una funzione vengono confrontati gli elementi stessi.\n\nExample: Per proprietà e per funzione\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nRestituisce tutti gli elementi corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una funzione `function(item, index)` o il nome di una proprietà. |\n| `value` | `Object` | no |  | Il valore della proprietà. |\n\nReturns: `Array` Gli elementi corrispondenti.\n\nGli argomenti sono gli stessi di `Array.findItem()`. Il risultato è un nuovo array.\n\nExample: Filtrare\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nRestituisce l'indice del primo elemento corrispondente, oppure `-1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |\n| `value` | `Object` | no |  | Il valore della proprietà. |\n\nReturns: `Number` L'indice, oppure `-1`.\n\nTotal.js sostituisce il metodo nativo in modo che accetti anche il nome di una proprietà e un valore. Una funzione viene chiamata come `function(item, index)`. `Array.TfindIndex()` è lo stesso metodo con un nome che gli altri moduli non sovrascrivono.\n\nExample: Indice per proprietà\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nUn alias di `Array.findIndex()` che gli altri moduli non sovrascrivono.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |\n| `value` | `Object` | no |  | Il valore della proprietà. |\n\nReturns: `Number` L'indice, oppure `-1`.\n\nAlcuni moduli NPM sostituiscono `Array.prototype.findIndex` con una propria versione. In quel caso `TfindIndex()` mantiene il comportamento di Total.js (nome di proprietà e valore). `findItem()` e `findValue()` lo usano internamente.\n\nExample: Indice sicuro\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nTrova un elemento e ne restituisce una proprietà.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Una funzione o il nome di una proprietà. |\n| `value` | `Object` | yes |  | Il valore della proprietà. |\n| `path` | `String` | yes |  | La proprietà da restituire. |\n| `def` | `Object` | no |  | Il valore predefinito. |\n\nReturns: `Object` Il valore della proprietà, oppure `def`.\n\nL'elemento viene trovato come in `Array.findItem()`; poi viene restituita la sua proprietà `path`. Quando non c'è alcun elemento o la proprietà è `null`/`undefined`, viene restituito `def`.\n\nExample: Nome tramite id\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nRestituisce un nuovo array senza gli elementi corrispondenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | Una funzione, il nome di una proprietà o un elemento. |\n| `value` | `Object` | no |  | Il valore della proprietà. |\n\nReturns: `Array` Un nuovo array.\n\nGli argomenti sono gli stessi di `Array.findItem()`. L'array originale non viene modificato, quindi assegna il risultato.\n\nExample: Rimuovere elementi\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nRestituisce i primi `count` elementi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero di elementi. |\n\nReturns: `Array` Un nuovo array.\n\nIl risultato è un nuovo array.\n\nExample: I primi tre\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nRestituisce gli elementi che seguono i primi `count` elementi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero di elementi saltati. |\n\nReturns: `Array` Un nuovo array.\n\nInsieme ad `Array.take()` permette una semplice paginazione.\n\nExample: Paginazione\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nRestituisce il primo elemento, oppure `def` per un array vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Il valore per un array vuoto. |\n\nReturns: `Object`\n\nExample: Primo elemento\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nRestituisce l'ultimo elemento, oppure `def` per un array vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Il valore per un array vuoto. |\n\nReturns: `Object`\n\nExample: Ultimo elemento\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nOrdina l'array sul posto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Le proprietà in base a cui ordinare, oppure `true` per valori primitivi in ordine decrescente. |\n| `desc` | `Boolean` | no | `false` | Ordinare in modo decrescente. |\n\nReturns: `Array` Lo stesso array.\n\n`sort` è il nome di una proprietà con un suffisso facoltativo `_asc` o `_desc`, per esempio `'name'` o `'price_desc'`. Più proprietà sono separate da virgole (`'name_asc,price_desc'`) e le proprietà annidate usano i punti. Stringhe, numeri, booleani e date vengono confrontati in base al loro tipo. Con `desc` impostato su `true`, l'ordine viene invertito.\n\nSenza argomenti, i valori primitivi vengono ordinati in modo crescente; `quicksort(true)` li ordina in modo decrescente.\n\nExample: Ordinare oggetti\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nCrea un oggetto (una mappa di lookup) dall'array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | La proprietà usata come chiave. |\n\nReturns: `Object` L'oggetto di lookup.\n\nCon `name`, ogni elemento viene salvato sotto il valore della sua proprietà `name`. Senza di esso, ogni elemento diventa una chiave con il valore `true`.\n\nExample: Lookup\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nRimuove gli spazi esterni dalle stringhe ed elimina gli elementi vuoti.\n\nReturns: `Array` Un nuovo array.\n\nLe stringhe vengono private degli spazi esterni, e gli elementi vuoti dopo questa operazione (o che sono `null`, `0`, `false`) vengono rimossi. Restituisce un nuovo array.\n\nExample: Pulire un elenco\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nElabora gli elementi uno alla volta con una funzione asincrona.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | La funzione `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Chiamata dopo l'ultimo elemento. |\n| `thread` | `Number|Boolean` | no | `1` | Il numero di elementi in parallelo, oppure `true` per rimuovere gli elementi. |\n\nReturns: `Array` Lo stesso array.\n\n`onItem(item, next, index)` viene chiamata per ogni elemento; chiama `next()` per continuare. `callback` viene chiamata dopo l'ultimo elemento. `thread` imposta quanti elementi vengono elaborati contemporaneamente (predefinito 1). Con `thread` impostato su `true`, gli elementi vengono rimossi dall'array mentre vengono elaborati. Chiama `next('cancel')` per fermarti; `callback` riceve allora `'cancel'`.\n\nExample: Inviare email una alla volta\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nEsegue un array di funzioni asincrone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Il numero di funzioni in parallelo. |\n| `callback` | `Function` | no |  | Chiamata alla fine. |\n\nReturns: `Array` Lo stesso array.\n\nOgni elemento è una funzione `function(next)`. Gli elementi vengono rimossi dall'array mentre vengono eseguiti. `thread` imposta quante funzioni vengono eseguite contemporaneamente (predefinito 1). `callback` viene chiamata dopo l'ultima funzione, oppure con `'cancel'` quando una funzione chiama `next('cancel')`.\n\nExample: Un elenco di attività\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nElabora l'array a blocchi di `max` elementi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | La dimensione di un blocco. |\n| `fn` | `Function` | yes |  | La funzione `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Chiamata dopo l'ultimo blocco. |\n\nReturns: `Array` Lo stesso array.\n\n`fn(items, next, beg, end)` riceve il blocco successivo; chiama `next()` per continuare con il blocco seguente. `callback` viene chiamata dopo l'ultimo blocco.\n\nExample: Inserire a blocchi\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nMescola l'array, oppure restituisce un elemento casuale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Restituire un elemento casuale. |\n\nReturns: `Array|Object`\n\nSenza argomenti l'array viene mescolato sul posto (Fisher-Yates) e restituito. Con `item` impostato su `true`, viene restituito un elemento casuale e l'array non viene modificato.\n\nExample: Mescolare e scegliere\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nAnalizza un testo CSV e lo trasforma in un array di oggetti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Il delimitatore delle colonne. |\n\nReturns: `Object[]` Un oggetto per riga, con le chiavi `a`, `b`, `c`...\n\nOgni riga diventa un oggetto. Le colonne sono denominate con lettere: la prima è `a`, la seconda `b` e così via. I valori tra virgolette doppie possono contenere il delimitatore e degli a capo, e `\"\"` tra virgolette è una virgoletta con escape. Tutti i valori restano stringhe, e una colonna vuota non ha alcuna chiave nell'oggetto. Una riga di intestazione non viene riconosciuta, quindi viene restituita come primo oggetto.\n\nExample: Leggere un file CSV\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nLegge il sistema operativo, il browser e il tipo di dispositivo da una stringa user agent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Restituire un oggetto invece di un testo. |\n\nReturns: `String|Object` I nomi rilevati, oppure `{ os, browser, device }`.\n\nSenza argomenti il metodo restituisce un breve testo con i nomi rilevati, come `Mac Chrome` o `iOS iPhone Mobile Safari`. Con `structured` impostato su `true` restituisce un oggetto `{ os, browser, device }`, dove `device` è `desktop`, `mobile`, `tablet` o `tv`. Una stringa vuota restituisce una stringa vuota.\n\nExample: Rilevare il client\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nAnalizza un testo `application/x-www-form-urlencoded` e lo trasforma in un oggetto.\n\nReturns: `Object` Le chiavi e i valori analizzati.\n\nIl testo ha l'aspetto di una query string: `key=value&key2=value2`. `+` diventa uno spazio e le sequenze `%xx` vengono decodificate. Tutti i valori restano stringhe; una chiave ripetuta unisce i suoi valori con una virgola. Le chiavi possono contenere solo lettere, cifre e `-`, `_`, `.`, `[`, `]`, e l'analisi si ferma al primo altro carattere in una chiave. Il numero di chiavi è limitato da `CONF.default_request_maxkeys` e la lunghezza di una chiave da `CONF.default_request_maxkey`.\n\nExample: Analizzare il corpo di un form\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nAnalizza un XML e lo trasforma in un oggetto piatto di percorsi e valori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Sostituire con `_` i caratteri speciali nelle chiavi. |\n\nReturns: `Object` L'oggetto piatto dei percorsi.\n\nOgni elemento con testo diventa una chiave composta dai nomi degli elementi uniti da punti, per esempio `book.title`. Un elemento ripetuto produce un array di valori. Gli attributi di un elemento vengono salvati come oggetto sotto il percorso seguito da `[]`. Le sezioni `CDATA` vengono lette come testo e i commenti vengono saltati. Con `replace` impostato su `true`, i caratteri `[`, `]`, `:`, `.` e `_` nelle chiavi vengono sostituiti con `_`.\n\nExample: Leggere un feed XML\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nAnalizza un HTML e lo trasforma in un albero di elementi che puoi cercare e modificare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Rimuovere gli spazi esterni dal contenuto testuale. |\n\nReturns: `HTMLElement` L'elemento radice del documento analizzato.\n\nIl metodo usa il parser HTML integrato e restituisce l'elemento radice. Gli elementi hanno `tagName`, `attrs`, `children` e `parentNode`, e i metodi `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` e `html([formatted])`. Con `trim` impostato su `true`, il testo all'interno degli elementi viene privato degli spazi esterni.\n\nExample: Leggere e modificare HTML\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nEstrae blocchi delimitati da tag da un testo e ne restituisce il contenuto per nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | Il nome e il tag di apertura di ogni blocco. |\n\nReturns: `Object` Il contenuto di ogni blocco trovato.\n\n`tags` associa un nome a un tag di apertura, per esempio `{ js: '<script>', css: '<style>' }`. Per ogni nome viene restituito il contenuto tra il tag di apertura e il relativo tag di chiusura (i tag annidati dello stesso tipo vengono contati). Un tag mancante non produce alcuna chiave. Total.js lo usa per leggere la parte `<script total>` dei plugin e dei componenti `.html`.\n\nExample: Dividere un file di componente\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nAnalizza riga per riga l'output a colonne di un comando del terminale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Nomi delle intestazioni o espressioni regolari delle colonne. |\n| `fn` | `Function` | yes |  | Chiamata come `fn(values, index, count, line)` per ogni riga. |\n| `skip` | `Number` | no | `0` | Il numero di righe da saltare. |\n| `take` | `Number` | no | `all` | Il numero di righe da leggere. |\n\nReturns: `String` La stessa stringa.\n\nCon `fields`, la prima riga non vuota (tra le prime tre) è l'intestazione. Ogni campo è il nome di un'intestazione (`String`) o una `RegExp` che trova la colonna nella riga di intestazione, e `fn` riceve i valori di quelle colonne per ogni riga successiva. Senza `fields`, ogni riga viene divisa in parole e `fn` riceve l'array delle parole. `fn(values, index, count, line)` riceve i valori, l'indice della riga analizzata, l'indice finale e il numero di riga. `skip` e `take` limitano le righe. Il metodo restituisce la stringa stessa.\n\nExample: Leggere l'output di df\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nAnalizza un testo nel formato di configurazione di Total.js e lo trasforma in un oggetto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Valori predefiniti copiati nel risultato. |\n| `onerror` | `Function` | no |  | Chiamata come `onerror(err, line)` quando un valore `object` o `eval` fallisce. |\n\nReturns: `Object` I valori analizzati.\n\nOgni riga è `key : value`, e le righe che iniziano con `#` o `//` vengono saltate. Il valore inizia due caratteri dopo il primo `:`, quindi scrivi uno spazio dopo i due punti. Un tipo tra parentesi dopo la chiave converte il valore: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (separato da virgole), `(json)`, `(object)` o `(eval)` (valutato come JavaScript), `(date)`, `(env)` (una variabile d'ambiente), `(config)` (un'altra chiave di `CONF`) e `(random)` (una stringa casuale della lunghezza indicata). `def` fornisce i valori predefiniti. `onerror(err, line)` gestisce un valore che non può essere valutato; senza di essa il metodo solleva un'eccezione.\n\nExample: Analizzare un testo di configurazione\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nTrasforma un testo come `5 minutes` in una data futura.\n\nReturns: `Date` La data corrente più il tempo indicato.\n\nIl testo viene letto come coppie di un numero e un'unità, separate da spazi, per esempio `1 day 12 hours`. Ogni coppia viene aggiunta alla data corrente con `Date.add()`, quindi funzionano le stesse unità (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Una coppia con il numero `0` viene ignorata.\n\nExample: Scadenza di un cookie\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nLegge le informazioni salvate in un identificatore creato da `UID()`.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nIl risultato ha `version` (l'ultimo carattere dell'UID), `date` (quando è stato creato), `century`, `index` (il contatore), `hash` e `valid`. Per la versione casuale `r` (`CONF.default_uid = 'r'`) il risultato non ha data, e gli identificatori vengono validati con `String.isUID()`.\n\nExample: Quando è stato creato un record\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nTrova il primo numero decimale in un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Il valore restituito quando non viene trovato alcun numero. |\n\nReturns: `Number` Il numero trovato.\n\nA differenza di `String.parseFloat()`, il testo può contenere altri caratteri: viene usato il primo gruppo di cifre, punti e virgole, e le virgole diventano punti. Un `-` iniziale lo rende negativo. Senza un numero il metodo restituisce `def`.\n\nExample: Prezzo da un'etichetta\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nVerifica se la stringa è un GUID (UUID).\n\nReturns: `Boolean`\n\nLa stringa deve avere 36 caratteri nella forma `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, dove `M` è una versione da 1 a 5. Sono accettate lettere maiuscole e minuscole.\n\nExample: Validare un UUID\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nVerifica se la stringa è una data nel formato JSON (ISO 8601 UTC).\n\nReturns: `Boolean`\n\nIl metodo verifica la forma del testo, come `2024-05-01T10:30:00.000Z`: la lunghezza, la `T`, i trattini e i due punti e la `Z` finale. Non verifica che la data esista.\n\nExample: Ripristinare le date\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nVerifica se la stringa contiene solo cifre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Consentire un separatore decimale. |\n\nReturns: `Boolean`\n\nCon `decimal` impostato su `true`, è consentito anche un `.` o una `,`. Segni, spazi ed esponenti non sono accettati, e una stringa vuota restituisce `false`.\n\nExample: Verificare l'input dell'utente\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nVerifica se la stringa è `true` o `false`.\n\nReturns: `Boolean`\n\nIl confronto non distingue tra maiuscole e minuscole. Altri valori come `1` o `on` restituiscono `false`; questi li legge `String.parseBoolean()`.\n\nExample: Verificare un valore della query\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nVerifica se la stringa sembra un codice postale (CAP).\n\nReturns: `Boolean`\n\nLa stringa viene verificata con `DEF.validators.zip`, per impostazione predefinita da 3 a 20 lettere, cifre, spazi o trattini. Modifica `DEF.validators.zip` per usare una tua regola.\n\nExample: Validare un codice postale\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nVerifica se la stringa contiene un tag HTML.\n\nReturns: `Boolean`\n\nIl test è semplice: restituisce `true` quando il testo contiene `<` seguito più avanti da `>`. Usalo per rifiutare l'HTML nei campi di testo semplice.\n\nExample: Rifiutare l'HTML\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nVerifica se la stringa contiene un testo tra virgolette o una parola chiave SQL.\n\nReturns: `Boolean`\n\nIl metodo restituisce `true` per un testo tra virgolette singole o per le parole maiuscole `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` e `UNION`. È un controllo approssimativo; usa comunque i parametri nelle tue query.\n\nExample: Verificare una frase di ricerca\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nVerifica se la stringa è codificata in base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Accettare un prefisso data URI. |\n\nReturns: `Boolean`\n\nLa lunghezza deve essere divisibile per 4 e il testo deve contenere solo caratteri base64. Con `data` impostato su `true`, viene accettato un data URI come `data:image/png;base64,...` e viene verificata solo la lunghezza della parte codificata.\n\nExample: Verificare un upload\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nScrive dati base64 in un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il percorso del file. |\n| `callback` | `Function` | no |  | Chiamata come `callback(err)` quando il file è stato scritto. |\n\nReturns: `String` La stessa stringa.\n\nUn prefisso data URI (tutto fino alla prima virgola) viene rimosso, e il resto viene decodificato e scritto con `fs.writeFile()`. Il metodo restituisce la stringa stessa; il risultato della scrittura arriva a `callback(err)`.\n\nExample: Salvare un'immagine caricata\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDecodifica dati base64 in un `Buffer`.\n\nReturns: `Buffer` I dati decodificati.\n\nUn prefisso data URI (tutto fino alla prima virgola) viene rimosso prima della decodifica.\n\nExample: Decodificare un data URI\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nRestituisce il content type di un data URI.\n\nReturns: `String` Il content type, per esempio `image/png`.\n\nViene restituito il testo tra `data:` e il primo `;`. Una stringa senza `;` restituisce una stringa vuota.\n\nExample: Verificare il tipo di un upload\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nCalcola il checksum CRC32 della stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Restituire un numero senza segno. |\n\nReturns: `Number` Il checksum.\n\nIl risultato è un numero a 32 bit con segno, oppure senza segno quando `unsigned` è `true`. `String.hash('crc32')` e `String.hash('crc32unsigned')` danno gli stessi risultati.\n\nExample: Checksum di un testo\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nCrea un hash SHA-1 della stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String` L'hash in esadecimale.\n\nIl `salt` viene aggiunto alla stringa prima del calcolo dell'hash.\n\nExample: Hash SHA-1\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nCrea un hash SHA-512 della stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Testo aggiunto prima del calcolo dell'hash. |\n\nReturns: `String` L'hash in esadecimale.\n\nIl `salt` viene aggiunto alla stringa prima del calcolo dell'hash.\n\nExample: Hash di un token\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nCrea un id breve dalla stringa.\n\nReturns: `String` L'id.\n\nL'id è un hash veloce senza segno della stringa scritto in base 36. La stessa stringa produce sempre lo stesso id. Non è un hash crittografico.\n\nExample: Id per una chiave di cache\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nAggiunge un checksum veloce alla stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Un segreto mescolato nel checksum. |\n\nReturns: `String` La stringa con il checksum.\n\nIl risultato è la stringa, un trattino e un hash in base 36 della stringa con `key`. Per verificare un valore, firma di nuovo la parte prima dell'ultimo trattino e confronta. È un checksum veloce, non una firma crittografica.\n\nExample: Firmare e verificare un valore\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nProtegge un identificatore con un checksum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Il segreto. |\n\nReturns: `String` L'identificatore protetto.\n\nIl risultato è `x`, un checksum e `x` seguiti dal valore originale, quindi il valore resta leggibile ma non può essere modificato senza la chiave. Il checksum usa `key` (predefinito `CONF.secret`) e `CONF.secret_uid`. Rileggilo con `String.decrypt_uid()`. La stessa funzione per i numeri è `U.encrypt_uid(value, [key])`.\n\nExample: Id protetto in un link\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nLegge un identificatore protetto con `String.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Il segreto usato per `encrypt_uid()`. |\n\nReturns: `String|Number` Il valore originale, oppure `null` quando il checksum è errato.\n\nIl checksum viene ricreato con `key` (predefinito `CONF.secret`). Quando corrisponde, viene restituito il valore originale, altrimenti `null`. Un valore creato da un numero viene restituito come numero.\n\nExample: Verificare un link\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nPulisce il nome di una persona: rimuove gli altri caratteri e rende maiuscola l'iniziale di ogni parola.\n\nReturns: `String` Il nome pulito.\n\nCifre e punteggiatura ASCII vengono rimosse, gli spazi vengono mantenuti e la prima lettera di ogni parola diventa maiuscola. Le lettere con segni diacritici vengono mantenute. Gli spazi finali vengono eliminati, ma quelli iniziali e ripetuti no, quindi rimuovi prima gli spazi esterni dall'input.\n\nExample: Pulire un nome da un form\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nEsegue l'escape dei caratteri al di fuori dell'ASCII stampabile come `\\uXXXX`.\n\nReturns: `String` La stringa con escape.\n\nI caratteri con un codice inferiore a 32 o superiore a 126 vengono scritti come `\\u` e quattro cifre esadecimali. `String.fromUnicode()` esegue l'operazione inversa.\n\nExample: Escape di un testo\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nRitrasforma gli escape `\\uXXXX` in caratteri.\n\nReturns: `String` La stringa senza escape.\n\nOgni `\\u` seguito da quattro cifre esadecimali viene sostituito con il carattere. È l'operazione inversa di `String.toUnicode()`.\n\nExample: Rimuovere l'escape da un testo\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nVerifica se la stringa termina con un testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Il testo da cercare. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true` per ignorare maiuscole e minuscole, oppure un offset dalla fine. |\n\nReturns: `Boolean`\n\nTotal.js sostituisce il metodo nativo. Con `ignoreCase` impostato su `true`, maiuscole e minuscole vengono ignorate. Un numero al posto di `ignoreCase` verifica il testo che si trova quel numero di caratteri prima della fine.\n\nExample: Verificare l'estensione di un file\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nSostituisce la prima occorrenza di un testo, senza espressioni regolari.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | Il testo da sostituire. |\n| `text` | `String` | yes |  | Il nuovo testo. |\n\nReturns: `String` La nuova stringa.\n\n`find` è testo semplice, quindi caratteri come `$` o `.` non hanno alcun significato speciale né in esso né in `text`. Quando `find` non viene trovato, la stringa viene restituita invariata.\n\nExample: Inserire un prezzo in un template\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nInserisce un valore in una posizione della stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | La posizione. |\n| `value` | `Object` | yes |  | Il valore da inserire. |\n\nReturns: `String` La nuova stringa.\n\nIl valore viene convertito in stringa con `toString()`.\n\nExample: Formattare un codice\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nAggiunge un carattere all'inizio della stringa un certo numero di volte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Quanti caratteri aggiungere. |\n| `char` | `String` | no | `' '` | Il carattere. |\n\nReturns: `String` La stringa indentata.\n\nA differenza di `String.padLeft()`, i caratteri vengono sempre aggiunti, qualunque sia la lunghezza della stringa.\n\nExample: Indentare una riga\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nSceglie la forma di una parola in base al numero nella stringa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | La forma per 0, oppure tutte le forme separate da virgole. |\n| `one` | `String` | no |  | La forma per 1. |\n| `few` | `String` | no |  | La forma da 2 a 4. |\n| `other` | `String` | no |  | La forma per gli altri numeri. |\n\nReturns: `String` La forma scelta.\n\nLa stringa viene letta con `String.parseInt()` e passata a `Number.pluralize()`, quindi le regole e il segnaposto `#` sono gli stessi.\n\nExample: Conteggio da una query\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nSostituisce i segnaposto `[key]` con i valori di configurazione.\n\nReturns: `String` La stringa con i valori.\n\nOgni `[key]` (lettere, cifre e `_`) viene sostituito con `CONF[key]`; una chiave mancante produce una stringa vuota.\n\nExample: Costruire un URL dalla configurazione\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nTrova blocchi in una stringa e passa ciascuno a una callback.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | Il delimitatore iniziale, oppure il separatore quando `end` manca. |\n| `end` | `String` | no |  | Il delimitatore finale. |\n| `callback` | `Function` | yes |  | Chiamata come `callback(value, index)`; restituisci `false` per fermarti. |\n| `skip` | `Number` | no | `0` | Il numero di blocchi da saltare. |\n\nReturns: `undefined`\n\nCon `beg` ed `end`, viene passato ogni blocco che inizia con `beg` e termina con `end`, delimitatori inclusi. Senza `end`, la stringa viene divisa dopo ogni `beg`, e ogni parte termina con `beg`. `callback(value, index)` può restituire `false` per fermarsi. `skip` salta i primi blocchi.\n\nExample: Leggere elementi da un XML\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nArrotonda il numero a un certo numero di decimali e restituisce un numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Il numero di decimali. |\n\nReturns: `Number` Il numero arrotondato.\n\nEquivale a `+number.toFixed(decimals)`: a differenza di `toFixed()`, il risultato è un numero, non una stringa.\n\nExample: Arrotondare un prezzo\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nFormatta il numero con un formattatore di valuta da `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | La chiave in `DEF.currencies`. |\n| `a` | `Object` | no |  | Passato al formattatore, come `b` e `c`. |\n\nReturns: `String` Il prezzo formattato.\n\n`DEF.currencies` è vuoto per impostazione predefinita; aggiungi una funzione `function(value, a, b, c)` per ogni codice di valuta che ti serve, e `default` per le chiamate senza codice. Gli argomenti aggiuntivi le vengono passati. Senza un formattatore il numero viene formattato con `Number.format(2)`.\n\nExample: Registrare e usare valute\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nConverte il numero in esadecimale maiuscolo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | La lunghezza minima. |\n\nReturns: `String` Il valore esadecimale.\n\nIl risultato viene completato con zeri iniziali fino a `length` caratteri.\n\nExample: Componente di un colore\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nCrea una data da un timestamp in millisecondi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Millisecondi da aggiungere. |\n\nReturns: `Date` La data.\n\nAl numero vengono aggiunti `plus` millisecondi prima di creare la data.\n\nExample: Data da un timestamp\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nConverte i gradi in radianti.\n\nReturns: `Number` L'angolo in radianti.\n\nDefinito solo quando `Number.prototype.toRad` non esiste ancora.\n\nExample: Distanza tra due punti GPS\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nRestituisce la data stessa.\n\nReturns: `Date` La stessa data.\n\nTi permette di chiamare `parseDate()` su un valore che può essere una stringa, un numero o una data, senza verificarne prima il tipo.\n\nExample: Valore di tipo sconosciuto\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JablpX1uW61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/prototypes/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Prototypy","summary":"Metódy String, Number, Date a Array pridané v Total.js 4.","markdown":"---\ntitle: Prototypy\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/prototypes/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Prototypy\n\n> Metódy String, Number, Date a Array pridané v Total.js 4.\n\nMetódy, ktoré Total.js 4 pridáva do `String`, `Number`, `Date` a `Array`. Návod [Prototypy](../../guides/prototypes/) vysvetľuje, ako ich používať, s príkladmi; táto stránka je presná referencia.\n\n## API\n\n### String.format([arg0], [arg1], [...])\n\nType: `method`\n\nNahradí indexované zástupné symboly `{0}`, `{1}`... argumentmi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `arg0` | `Object` | no |  | Hodnota pre `{0}`. Môže nasledovať ľubovoľný počet argumentov. |\n\nReturns: `String` Naformátovaný reťazec.\n\nKaždý `{n}` sa nahradí argumentom na indexe `n`. Argument `null` alebo `undefined` dá prázdny reťazec. Pre pomenované zástupné symboly použi `String.args()`.\n\nExample: Indexované zástupné symboly\n```js\nvar text = 'Hello {0}, you have {1} new messages.'.format('Peter', 5);\n// Hello Peter, you have 5 new messages.\n```\n\n### String.args(obj, [encode], [def])\n\nType: `method`\n\nNahradí pomenované zástupné symboly `{key}` alebo `{{key}}` hodnotami objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Hodnoty. |\n| `encode` | `Boolean|String|Function` | no |  | `true` (URL kódovanie), `'html'`, `'json'` alebo funkcia `function(value, key)`. |\n| `def` | `String` | no |  | Text pre chýbajúcu hodnotu. Ignoruje sa, keď je `encode` reťazec. |\n\nReturns: `String` Reťazec s hodnotami.\n\nKľúče môžu obsahovať písmená, číslice, `_`, `$`, `.` a `-`. Chýbajúca hodnota ponechá zástupný symbol, alebo použije `def`, ak ho nastavíš.\n\nArgument `encode` mení spôsob zápisu hodnôt: `true` ich zakóduje cez `encodeURIComponent()`, `'html'` zakóduje HTML entity, `'json'` zapíše `JSON.stringify(value)` a funkcia `function(value, key)` vráti text sama. `String.arg()` je alias.\n\nExample: Pomenované zástupné symboly\n```js\nvar model = { name: 'Peter', city: 'Bratislava' };\nvar text = 'Hello {name} from {{city}}'.args(model);\n// Hello Peter from Bratislava\n```\n\nExample: HTML kódovanie\n```js\nvar html = '<b>{name}</b>'.args({ name: '<Peter>' }, 'html');\n// <b>&lt;Peter&gt;</b>\n```\n\nExample: Predvolená hodnota pre chýbajúce hodnoty\n```js\n'{name} ({age})'.args({ name: 'Peter' }, null, '-');\n// Peter (-)\n```\n\n### String.slug([max])\n\nType: `method`\n\nVytvorí z textu slug vhodný pre URL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | no | `60` | Maximálna dĺžka. |\n\nReturns: `String` Slug.\n\nText sa oreže, prevedie na malé písmená a na ASCII (diakritika sa odstráni). Medzery a interpunkcia sa zmenia na jeden `-`; koncový `-` sa odstráni. Výsledok sa skráti na `max` znakov.\n\nKeď text nemá použiteľné latinské znaky (napríklad čínske alebo cyrilské), metóda namiesto toho vráti krátky hash vytvorený z textu.\n\nExample: Slug z titulku\n```js\nvar slug = 'Hello World: Total.js 4'.slug();\n// hello-world-total-js-4\n```\n\n### String.max(length, [chars])\n\nType: `method`\n\nSkráti text na maximálnu dĺžku a pridá tri bodky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | yes |  | Maximálna dĺžka výsledku. |\n| `chars` | `String` | no | `'...'` | Text pridaný ku skrátenému reťazcu. |\n\nReturns: `String` Skrátený text.\n\nKeď je text dlhší ako `length`, skráti sa tak, aby mal výsledok spolu s `chars` presne `length` znakov. Kratší text sa vráti nezmenený.\n\nExample: Skrátenie popisu\n```js\n'A long description'.max(10);\n// A long ...\n```\n\n### String.capitalize([first])\n\nType: `method`\n\nZmení prvé písmeno každého slova na veľké.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `first` | `Boolean` | no | `false` | Zmeniť na veľké iba prvé písmeno. |\n\nReturns: `String` Text s veľkými začiatočnými písmenami.\n\nText sa prevedie na malé písmená a každé písmeno za medzerou, tabulátorom alebo novým riadkom sa zmení na veľké. S `first` nastaveným na `true` sa na veľké zmení iba prvé písmeno celého textu.\n\nExample: Slová a prvé písmeno\n```js\n'hello WORLD'.capitalize();\t // Hello World\n'hello WORLD'.capitalize(true); // Hello world\n```\n\n### String.parseInt([def])\n\nType: `method`\n\nPrevedie celý reťazec na číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota vrátená, keď reťazec nie je číslo. |\n\nReturns: `Number` Číslo, alebo `def`.\n\nReťazec sa oreže a prevedie unárnym operátorom `+`, takže celý reťazec musí byť číslo: `'12px'` nie je číslo a dá `def`. Na prečítanie čísla z dlhšieho textu použi `String.parseInt2()`.\n\nExample: Parameter query\n```js\nvar page = (this.query.page || '').parseInt(1);\n'42'.parseInt();\t // 42\n'abc'.parseInt(-1); // -1\n```\n\n### String.parseInt2([def])\n\nType: `method`\n\nPrečíta prvé celé číslo nájdené v texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota vrátená, keď text neobsahuje žiadne číslo. |\n\nReturns: `Number` Číslo, alebo `def`.\n\nNa rozdiel od `String.parseInt()` môže byť číslo obklopené iným textom. Úvodné `-` sa zachová. `String.parseFloat2()` funguje rovnako pre desatinné čísla (desatinná čiarka `,` je akceptovaná).\n\nExample: Číslo v texte\n```js\n'Width: 120px'.parseInt2();   // 120\n'Price: 12,50 EUR'.parseFloat2(); // 12.5\n```\n\n### String.parseFloat([def])\n\nType: `method`\n\nPrevedie reťazec na desatinné číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota vrátená, keď reťazec nie je číslo. |\n\nReturns: `Number` Číslo, alebo `def`.\n\nReťazec sa oreže a desatinná čiarka `,` sa nahradí `.`. Celý reťazec musí byť číslo, inak sa vráti `def`.\n\nExample: Desatinná čiarka\n```js\n'12,5'.parseFloat();  // 12.5\n'x'.parseFloat(0.1); // 0.1\n```\n\n### String.parseBoolean()\n\nType: `method`\n\nPrevedie `true`, `1` alebo `on` na `true`.\n\nReturns: `Boolean`\n\nPorovnanie ignoruje veľkosť písmen. Každá iná hodnota dá `false`.\n\nExample: Hodnota checkboxu\n```js\nvar enabled = (this.body.enabled || '').parseBoolean();\n'ON'.parseBoolean(); // true\n```\n\n### String.parseDate([format])\n\nType: `method`\n\nPrevedie reťazec na `Date`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Formát vstupu, napríklad `'dd/MM/yyyy'`. |\n\nReturns: `Date` Spracovaný dátum.\n\nBez `format` metóda číta ISO reťazce (`2024-01-15T10:30:00.000Z`), `yyyy-MM-dd HH:mm:ss`, `dd.MM.yyyy HH:mm` a akúkoľvek hodnotu, ktorej rozumie `new Date()`. Za chýbajúcu časť dátumu sa použije dnešok.\n\nS `format` sa číslice reťazca čítajú v poradí písmen formátu (`yyyy`, `MM`, `dd`, `HH`, `mm`, `ss`). `pm` v texte pridá 12 hodín.\n\nExample: Spracovanie dátumov\n```js\nvar a = '2024-01-15 10:30'.parseDate();\nvar b = '15/01/2024'.parseDate('dd/MM/yyyy');\n```\n\n### String.parseJSON([date])\n\nType: `method`\n\nSpracuje JSON bez vyhodenia výnimky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Boolean` | no | `false` | Previesť ISO reťazce dátumov na dátumy. |\n\nReturns: `Object` Spracovaná hodnota, alebo `undefined` pre neplatný JSON.\n\nNeplatný JSON vráti namiesto chyby `undefined`. S `date` nastaveným na `true` sa ISO reťazce dátumov prevedú na objekty `Date`.\n\nExample: Bezpečné spracovanie\n```js\nvar obj = '{\"name\":\"Peter\",\"created\":\"2024-01-15T10:30:00.000Z\"}'.parseJSON(true);\n// obj.created instanceof Date === true\nvar bad = '{name'.parseJSON(); // undefined\n```\n\n### String.parseENV()\n\nType: `method`\n\nSpracuje riadky `KEY=value` (formát `.env`) do objektu.\n\nReturns: `Object` Kľúče a ich reťazcové hodnoty.\n\nPrázdne riadky a riadky začínajúce `#` alebo `//` sa preskočia. Hodnoty v dvojitých alebo jednoduchých úvodzovkách stratia úvodzovky a `\\n` sa zmení na nový riadok. Hodnoty bez úvodzoviek sa orežú.\n\nExample: Čítanie súboru .env\n```js\nrequire('fs').readFile(PATH.root('.env'), 'utf8', function(err, text) {\n\tif (!err) {\n\t\tvar env = text.parseENV();\n\t\tconsole.log(env.DATABASE);\n\t}\n});\n```\n\n### String.isEmail()\n\nType: `method`\n\nSkontroluje, či je reťazec e-mailová adresa.\n\nReturns: `Boolean`\n\nTest používa regulárny výraz `DEF.validators.email`, takže ho môžeš nahradiť. Reťazce so 4 alebo menej znakmi sú vždy `false`.\n\nExample: Validácia vstupu\n```js\nif (!this.body.email.isEmail()) {\n\tthis.invalid('Invalid email');\n\treturn;\n}\n```\n\n### String.isPhone()\n\nType: `method`\n\nSkontroluje, či je reťazec telefónne číslo.\n\nReturns: `Boolean`\n\nTest používa regulárny výraz `DEF.validators.phone`. Reťazce kratšie ako 6 znakov sú vždy `false`.\n\nExample: Telefónne číslo\n```js\n'+421903123456'.isPhone(); // true\n```\n\n### String.isURL()\n\nType: `method`\n\nSkontroluje, či je reťazec URL adresa.\n\nReturns: `Boolean`\n\nTest používa regulárny výraz `DEF.validators.url`. Reťazce so 7 alebo menej znakmi sú vždy `false`.\n\nExample: URL adresa\n```js\n'https://www.totaljs.com'.isURL(); // true\n```\n\n### String.isUID()\n\nType: `method`\n\nSkontroluje, či je reťazec platný identifikátor vytvorený cez `UID()`.\n\nReturns: `Boolean`\n\nMetóda otestuje formát cez `DEF.validators.uid` a potom kontrolný súčet, ktorý `UID()` zapisuje do každého identifikátora, takže náhodný reťazec so správnymi znakmi sa neprijme.\n\nExample: Validácia id z URL\n```js\nfunction detail(id) {\n\tif (!id.isUID()) {\n\t\tthis.throw404();\n\t\treturn;\n\t}\n\t// ...\n}\n```\n\n### String.isJSON()\n\nType: `method`\n\nSkontroluje, či reťazec vyzerá ako JSON.\n\nReturns: `Boolean`\n\nTestujú sa iba prvý a posledný nebiely znak: `{...}`, `[...]`, `\"...\"` alebo číslo. Obsah sa nespracúva; na to použi `String.parseJSON()`.\n\nExample: Rýchly test\n```js\n'{\"a\":1}'.isJSON(); // true\n'hello'.isJSON();   // false\n```\n\n### String.hash([type], [salt])\n\nType: `method`\n\nVytvorí hash reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Boolean` | no |  | Algoritmus, alebo `true` pre bezznamienkový číselný hash. |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String|Number` Hexadecimálny reťazec pre md5/sha*, inak číslo.\n\n`type` vyberá algoritmus: `'md5'`, `'sha1'`, `'sha256'`, `'sha512'` (hexadecimálne reťazce), `'crc32'` alebo `'crc32unsigned'` (čísla). Bez typu metóda vráti rýchly 32-bitový číselný hash; `true` ho urobí bezznamienkovým. `salt` sa pred hashovaním pripojí k reťazcu.\n\nExample: Rôzne hashe\n```js\n'hello'.hash();\t\t  // a 32-bit number\n'hello'.hash(true);\t  // an unsigned 32-bit number\n'hello'.hash('sha256');  // a hex string\n'hello'.hash('crc32unsigned');\n```\n\n### String.md5([salt])\n\nType: `method`\n\nVráti MD5 hash ako hexadecimálny reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` Hexadecimálny reťazec s 32 znakmi.\n\n`salt` sa pred hashovaním pripojí k reťazcu. Používaj ho pre kontrolné súčty a kľúče cache, nie pre heslá.\n\nExample: Kľúč cache\n```js\nvar key = JSON.stringify(this.query).md5();\n```\n\n### String.sha256([salt])\n\nType: `method`\n\nVráti SHA-256 hash ako hexadecimálny reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` Hexadecimálny reťazec so 64 znakmi.\n\n`salt` sa pred hashovaním pripojí k reťazcu. `String.sha1([salt])` a `String.sha512([salt])` fungujú rovnako s ostatnými algoritmami.\n\nExample: Hash so soľou\n```js\nvar hash = model.password.sha256(CONF.secret);\nvar short = 'hello'.sha1();\nvar long = 'hello'.sha512();\n```\n\n### String.encode()\n\nType: `method`\n\nZakóduje špeciálne HTML znaky.\n\nReturns: `String` Zakódovaný text.\n\nNahradí `<`, `>`, `\"`, `'` a `&` HTML entitami, takže text sa dá bezpečne zapísať do HTML.\n\nExample: Escapovanie vstupu používateľa\n```js\n'<script>alert(\"x\")</script>'.encode();\n// &lt;script&gt;alert(&quot;x&quot;)&lt;/script&gt;\n```\n\n### String.decode()\n\nType: `method`\n\nDekóduje HTML entity späť na znaky.\n\nReturns: `String` Dekódovaný text.\n\nPrevádzajú sa pomenované aj číselné entity (`&#65;`, `&#x41;`). Je to opak `String.encode()`.\n\nExample: Dekódovanie\n```js\n'&lt;b&gt;Hello&lt;/b&gt;'.decode(); // <b>Hello</b>\n```\n\n### String.encrypt(key, [isUnique], [secret])\n\nType: `method`\n\nZašifruje reťazec kľúčom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Šifrovací kľúč. |\n| `isUnique` | `Boolean` | no | `false` | Každý výsledok bude iný. |\n| `secret` | `String` | no | `CONF.secret` | Dodatočné tajomstvo. |\n\nReturns: `String` Zašifrovaný reťazec.\n\nS `isUnique` nastaveným na `true` dá každé volanie pre rovnaký vstup iný výsledok. Výsledok obsahuje kontrolný súčet vytvorený zo `secret` (predvolene `CONF.secret`) a kľúča, ktorý `String.decrypt()` kontroluje. Používaj ho pre tokeny a URL, nie na ukladanie hesiel.\n\nExample: Zašifrovanie tokenu\n```js\nvar token = JSON.stringify({ id: user.id }).encrypt('my-key', true);\n```\n\n### String.decrypt(key, [secret])\n\nType: `method`\n\nDešifruje reťazec vytvorený cez `String.encrypt()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Šifrovací kľúč. |\n| `secret` | `String` | no | `CONF.secret` | Dodatočné tajomstvo. |\n\nReturns: `String` Pôvodný reťazec, alebo `null`.\n\nPouži rovnaký `key` a `secret` ako pri šifrovaní. Nesprávny kľúč, nesprávne tajomstvo alebo zmenený reťazec vráti `null`.\n\nExample: Dešifrovanie tokenu\n```js\nvar data = (this.query.token || '').decrypt('my-key');\nvar obj = data ? data.parseJSON() : null;\n```\n\n### String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])\n\nType: `method`\n\nExtrahuje z textu kľúčové slová zoradené podľa frekvencie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `forSearch` | `Boolean` | no | `true` | Normalizovať slová pre vyhľadávanie. |\n| `alternative` | `Boolean` | no | `false` | Skrátiť každé slovo na 80 % jeho dĺžky. |\n| `max_count` | `Number` | no | `200` | Maximálny počet prečítaných slov. |\n| `max_length` | `Number` | no | `20` | Maximálna dĺžka slova. |\n| `min_length` | `Number` | no | `2` | Minimálna dĺžka slova. |\n\nReturns: `String[]` Unikátne slová, najčastejšie ako prvé.\n\nS `forSearch` (predvolene `true`) sa text prevedie na ASCII a `y` sa zmení na `i`, vďaka čomu je vyhľadávanie tolerantné. S `alternative` sa každé slovo skráti na 80 % svojej dĺžky. Slová kratšie ako `min_length` alebo dlhšie ako `max_length` sa preskočia. `String.toKeywords()` je alias.\n\nExample: Kľúčové slová pre vyhľadávací index\n```js\nvar words = (item.name + ' ' + item.description).keywords();\nitem.search = words.join(' ');\n```\n\n### String.toSearch()\n\nType: `method`\n\nNormalizuje text pre fulltextové vyhľadávanie.\n\nReturns: `String` Normalizovaný text.\n\nText sa prevedie na malé písmená a na ASCII, špeciálne znaky sa odstránia, `y` sa zmení na `i` a opakované písmená sa zlúčia. Použi to na uložený text aj na hľadanú frázu.\n\nExample: Hodnota pre vyhľadávanie\n```js\nvar q = (this.query.q || '').toSearch();\n```\n\n### String.toASCII()\n\nType: `method`\n\nOdstráni z textu diakritiku.\n\nReturns: `String` Text bez diakritiky.\n\nPísmená s diakritikou sa nahradia základnými latinskými písmenami, napríklad `á` za `a`.\n\nExample: Odstránenie diakritiky\n```js\n'Žltý kôň'.toASCII(); // Zlty kon\n```\n\n### String.removeTags()\n\nType: `method`\n\nOdstráni z textu HTML tagy.\n\nReturns: `String` Čistý text.\n\nOdstránia sa iba tagy; text medzi nimi zostane. HTML entity sa nedekódujú.\n\nExample: Čistý text\n```js\n'<p>Hello <b>world</b></p>'.removeTags(); // Hello world\n```\n\n### String.padLeft(max, [c])\n\nType: `method`\n\nDoplní reťazec zľava na dĺžku `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Výsledná dĺžka. |\n| `c` | `String` | no | `' '` | Znak na doplnenie. |\n\nReturns: `String` Doplnený reťazec.\n\nReťazec, ktorý už má `max` znakov alebo viac, sa vráti nezmenený.\n\nExample: Úvodné nuly\n```js\n'7'.padLeft(3, '0'); // 007\n```\n\n### String.padRight(max, [c])\n\nType: `method`\n\nDoplní reťazec sprava na dĺžku `max`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Výsledná dĺžka. |\n| `c` | `String` | no | `' '` | Znak na doplnenie. |\n\nReturns: `String` Doplnený reťazec.\n\nReťazec, ktorý už má `max` znakov alebo viac, sa vráti nezmenený.\n\nExample: Stĺpec s pevnou šírkou\n```js\n'Name'.padRight(10) + '|'; // 'Name\t  |'\n```\n\n### String.startsWith(text, [ignoreCase])\n\nType: `method`\n\nSkontroluje, či reťazec začína na `text`, voliteľne bez ohľadu na veľkosť písmen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Hľadaný text. |\n| `ignoreCase` | `Boolean|Number` | no |  | `true` na ignorovanie veľkosti písmen, alebo počiatočná pozícia. |\n\nReturns: `Boolean`\n\nTotal.js nahrádza natívnu metódu. S `ignoreCase` nastaveným na `true` porovnanie ignoruje veľkosť písmen; číslo sa použije ako počiatočná pozícia. `String.endsWith(text, [ignoreCase])` funguje rovnako na konci reťazca.\n\nExample: Ignorovanie veľkosti písmen\n```js\n'Hello World'.startsWith('hello', true); // true\n'photo.JPG'.endsWith('.jpg', true);\t // true\n```\n\n### String.markdown([opt])\n\nType: `method` · Since: `0.0.92`\n\nPrevedie Markdown na HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no |  | Voľby popísané vyššie. |\n\nReturns: `String` HTML.\n\nVýsledok sa zabalí do `<div class=\"markdown markdown-container\">`, pokiaľ `opt.wrap` nie je `false`. Väčšina funkcií je predvolene zapnutá a jednotlivú vypneš cez `false`: `ul`, `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `headlines`, `hr`, `blockquotes`, `sections`, `footnotes`, `urlify`, `keywords`, `emptynewline`, `bookmarks`. Ďalšie voľby: `linetag` (tag odseku, predvolene `'p'`), `prefix` (prefix pre generované id), `custom` (funkcia, ktorá mení každý riadok) a `html` (funkcia `function(html, type)`, ktorá mení vygenerované HTML).\n\nExample: Vykreslenie Markdownu\n```js\nvar html = '# Title\\n\\nSome **bold** text.'.markdown();\n```\n\nExample: Bez obalu a obrázkov\n```js\nvar html = text.markdown({ wrap: false, images: false });\n```\n\n### String.tslash()\n\nType: `method` · Since: `0.0.95`\n\nOdstráni koncové lomky.\n\nReturns: `String` Reťazec bez koncových lomiek.\n\nOdstránia sa všetky znaky `/` na konci, ale jedna `/` sa zachová, takže `'/'` zostane `'/'`.\n\nExample: Vyčistenie URL\n```js\n'https://www.totaljs.com/'.tslash(); // https://www.totaljs.com\n'/products//'.tslash();\t\t\t// /products\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method`\n\nVytvorí objekt JSON schémy z inline definície.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov schémy použitý v `$id`. |\n| `url` | `String` | no | `CONF.url` | Základná URL pre `$id`. |\n\nReturns: `Object` JSON schéma.\n\nDefinícia je zoznam párov `name:type` oddelených čiarkami alebo novými riadkami. `*` alebo `!` pred názvom urobí pole povinným. Typy: `string`, `email`, `phone`, `url`, `uid`, `name`, `zip`, `lower`, `upper`, `capitalize`, `color`, `icon`, `base64`, `number`, `int`, `float`, `boolean`, `date`, `object`. `string(50)` nastaví maximálnu dĺžku, `[string]` vytvorí pole, `{draft|published}` enum a `@name` použije inú schému.\n\n`$id` sa zostaví z `url` (predvolene `CONF.url`) a `name`.\n\nExample: Inline schéma\n```js\nvar schema = '*name:string(50), *email:email, age:number, tags:[string], status:{draft|published}'.toJSONSchema('user');\n// schema.required: ['name', 'email']\n```\n\n### Number.format([decimals], [separator], [separatorDecimal])\n\nType: `method`\n\nNaformátuje číslo s oddeľovačom tisícov a desatinnými miestami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Počet desatinných miest. |\n| `separator` | `String` | no | `' '` | Oddeľovač tisícov. |\n| `separatorDecimal` | `String` | no | `'.'` | Desatinný oddeľovač. |\n\nReturns: `String` Naformátované číslo.\n\nPredvolený oddeľovač tisícov je medzera. Desatinné miesta sa orežú (nezaokrúhľujú) alebo doplnia nulami na `decimals`. Desatinný oddeľovač je `.`, alebo `,`, keď je oddeľovač tisícov `.`. Oddeľovač môžeš odovzdať aj ako prvý: `format(',', 2)`.\n\nExample: Formátovanie cien\n```js\n(1234567.891).format(2);\t\t   // 1 234 567.89\n(1234.5).format(2, '.');\t\t  // 1.234,50\n(1234.5).format(2, ',', '.');\t // 1,234.50\n```\n\n### Number.pluralize(zero, one, few, other)\n\nType: `method`\n\nVyberie tvar slova podľa čísla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Tvar pre 0, alebo všetky tvary oddelené čiarkami. |\n| `one` | `String` | no |  | Tvar pre 1. |\n| `few` | `String` | no |  | Tvar pre 2 až 4. |\n| `other` | `String` | no |  | Tvar pre ostatné čísla. |\n\nReturns: `String` Vybraný tvar.\n\n`zero` sa použije pre 0, `one` pre 1, `few` pre 2 až 4 a `other` pre ostatné. `#` vo vybranom tvare sa nahradí číslom. Všetky tvary môžeš odovzdať aj ako jeden reťazec oddelený čiarkami.\n\nExample: Počet položiek\n```js\nvar count = 3;\ncount.pluralize('no items', '# item', '# items', '# items'); // 3 items\ncount.pluralize('no items,# item,# items,# items');\t\t  // 3 items\n```\n\n### Number.padLeft(max, [c])\n\nType: `method`\n\nPrevedie číslo na reťazec doplnený zľava.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Výsledná dĺžka. |\n| `c` | `String` | no | `'0'` | Znak na doplnenie. |\n\nReturns: `String` Doplnené číslo.\n\nPredvolený znak na doplnenie je `0`.\n\nExample: Číslo faktúry\n```js\n(42).padLeft(6); // 000042\n```\n\n### Number.padRight(max, [c])\n\nType: `method`\n\nPrevedie číslo na reťazec doplnený sprava.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Výsledná dĺžka. |\n| `c` | `String` | no | `'0'` | Znak na doplnenie. |\n\nReturns: `String` Doplnené číslo.\n\nPredvolený znak na doplnenie je `0`.\n\nExample: Doplnenie sprava\n```js\n(42).padRight(5); // 42000\n```\n\n### Number.round([precision])\n\nType: `method`\n\nZaokrúhli číslo na daný počet desatinných miest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `precision` | `Number` | no | `0` | Počet desatinných miest. |\n\nReturns: `Number` Zaokrúhlené číslo.\n\nBez `precision` sa číslo zaokrúhli na celé číslo.\n\nExample: Zaokrúhlenie\n```js\n(3.14159).round(2); // 3.14\n(2.5).round();\t  // 3\n```\n\n### Number.floor(decimals)\n\nType: `method`\n\nZaokrúhli číslo nadol na daný počet desatinných miest.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Počet desatinných miest. |\n\nReturns: `Number` Číslo zaokrúhlené nadol.\n\nFunguje ako `Math.floor()` s desatinnými miestami.\n\nExample: Zaokrúhlenie nadol\n```js\n(3.14959).floor(2); // 3.14\n```\n\n### Number.between(condition, otherwise)\n\nType: `method`\n\nVráti hodnotu z mapy číselných rozsahov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `condition` | `Object` | yes |  | Rozsahy ako kľúče a výsledky ako hodnoty. |\n| `otherwise` | `Object` | yes |  | Hodnota, keď nezodpovedá žiadny rozsah. |\n\nReturns: `Object` Hodnota zodpovedajúceho rozsahu.\n\nKľúče `condition` sú rozsahy: `'1-5'` (od 1 do 5), `'10-'` (10 a viac) alebo `'-5'` (5 a menej). Vráti sa hodnota prvého zodpovedajúceho rozsahu, inak `otherwise`.\n\nExample: Označenie hodnotenia\n```js\nvar label = (4).between({ '1-2': 'bad', '3-4': 'good', '5-': 'excellent' }, 'none');\n// good\n```\n\n### Number.add(value, [decimals])\n\nType: `method`\n\nPoužije matematickú operáciu zapísanú ako reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Číslo, alebo operácia ako `'-5'` či `'+20%'`. |\n| `decimals` | `Number` | no |  | Zaokrúhliť výsledok nadol na tento počet desatinných miest. |\n\nReturns: `Number` Výsledok.\n\nČíslo sa pripočíta. Reťazec začína operátorom `+`, `-`, `*` alebo `/`, za ktorým nasleduje číslo, napríklad `'+10'`. S `%` na konci je operand percentom z čísla: `'+20%'` pridá 20 %. S `decimals` sa výsledok zaokrúhli nadol na tento počet desatinných miest.\n\nExample: Operácie\n```js\n(100).add('+20%'); // 120\n(100).add('-5');   // 95\n(100).add('*2');   // 200\n```\n\n### Number.VAT(percentage, [decimals], [includedVAT])\n\nType: `method`\n\nPridá k cene DPH, alebo ju odoberie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Sadzba DPH v percentách. |\n| `decimals` | `Number` | no | `2` | Počet desatinných miest. |\n| `includedVAT` | `Boolean` | no | `false` | Číslo už obsahuje DPH. |\n\nReturns: `Number` Cena.\n\nBez `includedVAT` metóda vráti cenu s DPH. S `includedVAT` nastaveným na `true` je číslo cenou s DPH a metóda vráti cenu bez nej. Výsledok sa zaokrúhli na `decimals`.\n\nExample: S DPH a bez DPH\n```js\n(100).VAT(20);\t\t  // 120\n(120).VAT(20, 2, true); // 100\n```\n\n### Number.discount(percentage, [decimals])\n\nType: `method`\n\nOdpočíta percentuálnu zľavu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | yes |  | Zľava v percentách. |\n| `decimals` | `Number` | no | `2` | Počet desatinných miest. |\n\nReturns: `Number` Číslo po zľave.\n\nVýsledok sa zaokrúhli nadol na `decimals`.\n\nExample: Zľava\n```js\n(80).discount(15); // 68\n```\n\n### Number.filesize([decimals], [type])\n\nType: `method`\n\nNaformátuje počet bajtov ako čitateľnú veľkosť súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | no |  | Počet desatinných miest. |\n| `type` | `String` | no |  | Jednotka: `'bytes'`, `'KB'`, `'MB'`, `'GB'` alebo `'TB'`. |\n\nReturns: `String` Veľkosť s jednotkou.\n\nBez `type` sa jednotka vyberie automaticky (`bytes`, `KB`, `MB`, `GB` alebo `TB`). S `type` sa hodnota prevedie na túto jednotku. Bez `decimals` má hodnota najviac 2 desatinné miesta.\n\nExample: Veľkosť súboru\n```js\n(1536).filesize();\t\t // 1.50 KB\n(5242880).filesize(0, 'MB'); // 5 MB\n```\n\n### Number.async(fn, [callback])\n\nType: `method`\n\nSpustí asynchrónnu funkciu daný počet krát s odpočítavaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | Funkcia `function(number, next)`. |\n| `callback` | `Function` | no |  | Zavolá sa po poslednom behu. |\n\nReturns: `Number`\n\nFunkcia dostane aktuálne číslo (od počiatočnej hodnoty nadol po 1) a `next`. Ďalší beh začne, keď zavoláš `next()`. Keď počet dosiahne nulu, zavolá sa `callback`.\n\nExample: Tri behy\n```js\n(3).async(function(number, next) {\n\tconsole.log(number); // 3, 2, 1\n\tsetTimeout(next, 100);\n}, function() {\n\tconsole.log('Done');\n});\n```\n\n### Date.add(type, [value])\n\nType: `method`\n\nVráti nový dátum posunutý o časové obdobie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String|Number` | yes |  | Jednotka, výraz ako `'5 days'`, alebo milisekundy. |\n| `value` | `Number` | no |  | Množstvo. |\n\nReturns: `Date` Nový dátum.\n\nOdovzdaj typ a hodnotu (`add('days', 5)`) alebo jeden výraz (`add('5 days')`). Typy: `seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`, aj krátke tvary `s`, `m`, `h`, `d`, `w`, `M`, `y`. Záporné hodnoty posúvajú dozadu. Číslo pridá milisekundy. Pôvodný dátum sa nezmení.\n\nExample: Posun dátumov\n```js\nvar expire = NOW.add('1 month');\nvar yesterday = NOW.add('days', -1);\nvar later = NOW.add('2 hours');\n```\n\n### Date.format([format], [resource])\n\nType: `method`\n\nNaformátuje dátum ako reťazec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `format` | `String` | no |  | Formát, napríklad `'dd.MM.yyyy HH:mm'`. |\n| `resource` | `String` | no |  | Súbor zdroja s preloženými názvami mesiacov a dní. |\n\nReturns: `String` Naformátovaný dátum.\n\nBez `format` sa dátum vráti ako ISO reťazec v UTC. Tokeny formátu používajú lokálny čas: `yyyy`, `yy`, `MM`, `M`, `MMM` (krátky názov mesiaca), `MMMM` (názov mesiaca), `dd`, `d`, `ddd` (krátky názov dňa), `dddd` (názov dňa), `HH`, `H`, `mm`, `m`, `ss`, `s`, `ww` (ISO týždeň), `a` (AM/PM). Názvy mesiacov a dní sú anglické; s `resource` sa čítajú z tohto súboru zdroja.\n\nExample: Formáty\n```js\nvar dt = new Date(2024, 0, 15, 9, 5);\ndt.format('yyyy-MM-dd');\t\t// 2024-01-15\ndt.format('dd.MM.yyyy HH:mm');  // 15.01.2024 09:05\ndt.format('dddd, d. MMMM');\t // Monday, 15. January\ndt.format();\t\t\t\t\t// ISO string in UTC\n```\n\n### Date.diff([date], type)\n\nType: `method`\n\nVráti rozdiel medzi dvoma dátumami v danej jednotke.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `Date|Number|String` | no | `now` | Dátum na porovnanie. |\n| `type` | `String` | yes |  | Jednotka. |\n\nReturns: `Number` Rozdiel.\n\nRozdiel je `this - date`, zaokrúhlený nahor. Bez `date` metóda porovnáva s aktuálnym časom. Jednotky: `seconds`, `minutes`, `hours`, `days`, `months`, `years` a krátke tvary `s`, `m`, `h`, `d`, `M`, `y`. Mesiac sa počíta ako 28 dní. Neznáma jednotka dá `NaN`.\n\nExample: Zostávajúce dni\n```js\nvar left = item.expire.diff('days');\nvar age = NOW.diff(user.dtcreated, 'hours');\n```\n\n### Date.toUTC([ticks])\n\nType: `method`\n\nPosunie dátum o posun lokálneho časového pásma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `ticks` | `Boolean` | no | `false` | Vrátiť milisekundy. |\n\nReturns: `Date|Number`\n\nVýsledok zobrazuje UTC čas v lokálnych poliach dátumu. S `ticks` nastaveným na `true` metóda namiesto dátumu vráti milisekundy.\n\nExample: UTC dátum\n```js\nvar utc = new Date().toUTC();\nvar ticks = new Date().toUTC(true);\n```\n\n### Date.extend(date)\n\nType: `method`\n\nVráti nový dátum s časťami nastavenými z reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `date` | `String` | yes |  | Časti dátumu alebo času, napríklad `'12:00'` alebo `'2024-12-24 18:00'`. |\n\nReturns: `Date` Nový dátum.\n\nReťazec môže obsahovať dátum (`yyyy-MM-dd` alebo `dd.MM.yyyy`) a čas (`HH:mm` alebo `HH:mm:ss`). Zmenia sa iba zadané časti; nastavujú sa v UTC.\n\nExample: Nastavenie času\n```js\nvar noon = NOW.extend('12:00');\nvar eve = NOW.extend('2024-12-24 18:00');\n```\n\n### Date.setTimeZone(timezone)\n\nType: `method`\n\nVráti nový dátum prevedený do časového pásma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timezone` | `String` | yes |  | IANA názov časového pásma. |\n\nReturns: `Date` Nový dátum.\n\n`timezone` je IANA názov ako `'Europe/Bratislava'`.\n\nExample: Čas v New Yorku\n```js\nvar dt = new Date().setTimeZone('America/New_York');\n```\n\n### Array.findItem(cb, [value])\n\nType: `method`\n\nVráti prvú zodpovedajúcu položku, alebo `null`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Funkcia alebo názov vlastnosti. |\n| `value` | `Object` | no |  | Hodnota vlastnosti. |\n\nReturns: `Object` Položka, alebo `null`.\n\n`cb` je funkcia `function(item, index)`, alebo názov vlastnosti porovnávaný s `value` (`===`). S jediným argumentom, ktorý nie je funkcia, sa porovnávajú samotné položky.\n\nExample: Podľa vlastnosti a podľa funkcie\n```js\nvar user = users.findItem('id', id);\nvar admin = users.findItem(item => item.role === 'admin');\n```\n\n### Array.findAll(cb, [value])\n\nType: `method`\n\nVráti všetky zodpovedajúce položky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Funkcia `function(item, index)` alebo názov vlastnosti. |\n| `value` | `Object` | no |  | Hodnota vlastnosti. |\n\nReturns: `Array` Zodpovedajúce položky.\n\nArgumenty sú rovnaké ako v `Array.findItem()`. Výsledkom je nové pole.\n\nExample: Filter\n```js\nvar active = users.findAll('active', true);\nvar adults = users.findAll(item => item.age >= 18);\n```\n\n### Array.findIndex(cb, [value])\n\nType: `method`\n\nVráti index prvej zodpovedajúcej položky, alebo `-1`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Funkcia alebo názov vlastnosti. |\n| `value` | `Object` | no |  | Hodnota vlastnosti. |\n\nReturns: `Number` Index, alebo `-1`.\n\nTotal.js nahrádza natívnu metódu, aby akceptovala aj názov vlastnosti a hodnotu. Funkcia sa volá ako `function(item, index)`. `Array.TfindIndex()` je tá istá metóda pod názvom, ktorý iné moduly neprepisujú.\n\nExample: Index podľa vlastnosti\n```js\nvar index = users.findIndex('id', id);\nif (index !== -1)\n\tusers.splice(index, 1);\n```\n\n### Array.TfindIndex(cb, [value])\n\nType: `method` · Since: `0.0.95`\n\nAlias `Array.findIndex()`, ktorý iné moduly neprepisujú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Funkcia alebo názov vlastnosti. |\n| `value` | `Object` | no |  | Hodnota vlastnosti. |\n\nReturns: `Number` Index, alebo `-1`.\n\nNiektoré NPM moduly nahrádzajú `Array.prototype.findIndex` vlastnou verziou. `TfindIndex()` v takom prípade zachová správanie Total.js (názov vlastnosti a hodnota). `findItem()` a `findValue()` ho interne používajú.\n\nExample: Bezpečný index\n```js\nvar index = users.TfindIndex('id', id);\n```\n\n### Array.findValue(cb, value, path, [def])\n\nType: `method`\n\nNájde položku a vráti jednu z jej vlastností.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String` | yes |  | Funkcia alebo názov vlastnosti. |\n| `value` | `Object` | yes |  | Hodnota vlastnosti. |\n| `path` | `String` | yes |  | Vlastnosť, ktorá sa vráti. |\n| `def` | `Object` | no |  | Predvolená hodnota. |\n\nReturns: `Object` Hodnota vlastnosti, alebo `def`.\n\nPoložka sa nájde ako v `Array.findItem()`; potom sa vráti jej vlastnosť `path`. Keď položka neexistuje alebo je vlastnosť `null`/`undefined`, vráti sa `def`.\n\nExample: Názov podľa id\n```js\nvar name = users.findValue('id', id, 'name', 'Unknown');\n```\n\n### Array.remove(cb, [value])\n\nType: `method`\n\nVráti nové pole bez zodpovedajúcich položiek.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cb` | `Function|String|Object` | yes |  | Funkcia, názov vlastnosti alebo položka. |\n| `value` | `Object` | no |  | Hodnota vlastnosti. |\n\nReturns: `Array` Nové pole.\n\nArgumenty sú rovnaké ako v `Array.findItem()`. Pôvodné pole sa nezmení, preto výsledok priraď.\n\nExample: Odstránenie položiek\n```js\nusers = users.remove('id', id);\nnumbers = [1, 2, 3, 2].remove(2); // [1, 3]\n```\n\n### Array.take(count)\n\nType: `method`\n\nVráti prvých `count` položiek.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet položiek. |\n\nReturns: `Array` Nové pole.\n\nVýsledkom je nové pole.\n\nExample: Prvé tri\n```js\n[1, 2, 3, 4, 5].take(3); // [1, 2, 3]\n```\n\n### Array.skip(count)\n\nType: `method`\n\nVráti položky za prvými `count` položkami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Počet preskočených položiek. |\n\nReturns: `Array` Nové pole.\n\nSpolu s `Array.take()` vytvára jednoduché stránkovanie.\n\nExample: Stránkovanie\n```js\nvar page = 2;\nvar limit = 10;\nvar items = all.skip((page - 1) * limit).take(limit);\n```\n\n### Array.first([def])\n\nType: `method`\n\nVráti prvú položku, alebo `def` pre prázdne pole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Hodnota pre prázdne pole. |\n\nReturns: `Object`\n\nExample: Prvá položka\n```js\nvar item = response.items.first(null);\n```\n\n### Array.last([def])\n\nType: `method`\n\nVráti poslednú položku, alebo `def` pre prázdne pole.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Hodnota pre prázdne pole. |\n\nReturns: `Object`\n\nExample: Posledná položka\n```js\n[1, 2, 3].last(); // 3\n```\n\n### Array.quicksort([sort], [desc])\n\nType: `method`\n\nZoradí pole na mieste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sort` | `String|Boolean` | no |  | Vlastnosti na zoradenie, alebo `true` pre zostupné primitívne hodnoty. |\n| `desc` | `Boolean` | no | `false` | Zoradiť zostupne. |\n\nReturns: `Array` To isté pole.\n\n`sort` je názov vlastnosti s voliteľnou príponou `_asc` alebo `_desc`, napríklad `'name'` alebo `'price_desc'`. Viac vlastností sa oddeľuje čiarkami (`'name_asc,price_desc'`) a vnorené vlastnosti používajú bodky. Reťazce, čísla, booleany a dátumy sa porovnávajú podľa svojho typu. S `desc` nastaveným na `true` sa poradie obráti.\n\nBez argumentov sa primitívne hodnoty zoradia vzostupne; `quicksort(true)` ich zoradí zostupne.\n\nExample: Zoradenie objektov\n```js\nproducts.quicksort('price_desc');\nproducts.quicksort('category,name');\nusers.quicksort('dtcreated', true);\n```\n\n### Array.toObject([name])\n\nType: `method`\n\nVytvorí z poľa objekt (vyhľadávaciu mapu).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Vlastnosť použitá ako kľúč. |\n\nReturns: `Object` Vyhľadávací objekt.\n\nS `name` sa každá položka uloží pod hodnotou svojej vlastnosti `name`. Bez neho sa každá položka stane kľúčom s hodnotou `true`.\n\nExample: Vyhľadávacie objekty\n```js\nvar byid = users.toObject('id');\nvar user = byid[id];\n\nvar allowed = ['admin', 'editor'].toObject();\n// { admin: true, editor: true }\n```\n\n### Array.trim()\n\nType: `method`\n\nOreže reťazce a odstráni prázdne položky.\n\nReturns: `Array` Nové pole.\n\nReťazce sa orežú a položky, ktoré sú po orezaní prázdne (alebo sú `null`, `0`, `false`), sa odstránia. Vracia nové pole.\n\nExample: Vyčistenie zoznamu\n```js\n'a, b, ,c'.split(',').trim(); // ['a', 'b', 'c']\n```\n\n### Array.wait(onItem, [callback], [thread])\n\nType: `method`\n\nSpracuje položky jednu po druhej asynchrónnou funkciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `onItem` | `Function` | yes |  | Funkcia `function(item, next, index)`. |\n| `callback` | `Function` | no |  | Zavolá sa po poslednej položke. |\n| `thread` | `Number|Boolean` | no | `1` | Počet paralelných položiek, alebo `true` na odstraňovanie položiek. |\n\nReturns: `Array` To isté pole.\n\n`onItem(item, next, index)` sa volá pre každú položku; zavolaj `next()`, aby si pokračoval. `callback` sa zavolá po poslednej položke. `thread` nastavuje, koľko položiek sa spracúva naraz (predvolene 1). S `thread` nastaveným na `true` sa položky počas spracovania odstraňujú z poľa. Zavolaj `next('cancel')` na zastavenie; `callback` potom dostane `'cancel'`.\n\nExample: Posielanie e-mailov jeden po druhom\n```js\nusers.wait(function(user, next) {\n\tMAIL(user.email, 'News', '=mails/news', user, next);\n}, function() {\n\tconsole.log('All sent');\n});\n```\n\n### Array.async([thread], [callback])\n\nType: `method`\n\nSpustí pole asynchrónnych funkcií.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `thread` | `Number` | no | `1` | Počet paralelných funkcií. |\n| `callback` | `Function` | no |  | Zavolá sa na konci. |\n\nReturns: `Array` To isté pole.\n\nKaždá položka je funkcia `function(next)`. Položky sa z poľa odstraňujú, ako sa spúšťajú. `thread` nastavuje, koľko funkcií beží naraz (predvolene 1). `callback` sa zavolá po poslednej funkcii, alebo s `'cancel'`, keď niektorá funkcia zavolá `next('cancel')`.\n\nExample: Zoznam úloh\n```js\nvar tasks = [];\n\ntasks.push(function(next) {\n\t// load something\n\tnext();\n});\n\ntasks.push(function(next) {\n\t// save something\n\tnext();\n});\n\ntasks.async(function() {\n\tconsole.log('Done');\n});\n```\n\n### Array.limit(max, fn, [callback])\n\nType: `method`\n\nSpracuje pole po dávkach s `max` položkami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `max` | `Number` | yes |  | Veľkosť dávky. |\n| `fn` | `Function` | yes |  | Funkcia `function(items, next, beg, end)`. |\n| `callback` | `Function` | no |  | Zavolá sa po poslednej dávke. |\n\nReturns: `Array` To isté pole.\n\n`fn(items, next, beg, end)` dostane ďalšiu dávku; zavolaj `next()`, aby si pokračoval nasledujúcou dávkou. `callback` sa zavolá po poslednej dávke.\n\nExample: Vkladanie po dávkach\n```js\nrows.limit(100, function(items, next) {\n\t// insert 100 items at once\n\tnext();\n}, function() {\n\tconsole.log('Imported');\n});\n```\n\n### Array.random([item])\n\nType: `method`\n\nZamieša pole, alebo vráti náhodnú položku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `item` | `Boolean` | no | `false` | Vrátiť jednu náhodnú položku. |\n\nReturns: `Array|Object`\n\nBez argumentov sa pole zamieša na mieste (Fisher-Yates) a vráti sa. S `item` nastaveným na `true` sa vráti jedna náhodná položka a pole sa nezmení.\n\nExample: Zamiešanie a výber\n```js\nvar deck = [1, 2, 3, 4, 5].random();\nvar winner = users.random(true);\n```\n\n### String.parseCSV([delimiter])\n\nType: `method`\n\nSpracuje CSV text do poľa objektov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `delimiter` | `String` | no | `','` | Oddeľovač stĺpcov. |\n\nReturns: `Object[]` Jeden objekt na riadok s kľúčmi `a`, `b`, `c`...\n\nKaždý riadok sa stane jedným objektom. Stĺpce sú pomenované písmenami: prvý je `a`, druhý `b` a tak ďalej. Hodnoty v dvojitých úvodzovkách môžu obsahovať oddeľovač a nové riadky a `\"\"` v úvodzovkách je escapovaná úvodzovka. Všetky hodnoty zostanú reťazcami a prázdny stĺpec nemá v objekte kľúč. Hlavičkový riadok sa nerozpoznáva, takže sa vráti ako prvý objekt.\n\nExample: Čítanie CSV súboru\n```js\nvar csv = 'Peter,30,\"Bratislava, SK\"\\nAnna,25,Prague';\nvar rows = csv.parseCSV();\n// [{ a: 'Peter', b: '30', c: 'Bratislava, SK' }, { a: 'Anna', b: '25', c: 'Prague' }]\n\n'name;age\\nPeter;30'.parseCSV(';');\n```\n\n### String.parseUA([structured])\n\nType: `method`\n\nPrečíta z reťazca user agent operačný systém, prehliadač a typ zariadenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `structured` | `Boolean` | no | `false` | Vrátiť objekt namiesto textu. |\n\nReturns: `String|Object` Rozpoznané názvy, alebo `{ os, browser, device }`.\n\nBez argumentu metóda vráti krátky text s rozpoznanými názvami, napríklad `Mac Chrome` alebo `iOS iPhone Mobile Safari`. S `structured` nastaveným na `true` vráti objekt `{ os, browser, device }`, kde `device` je `desktop`, `mobile`, `tablet` alebo `tv`. Prázdny reťazec vráti prázdny reťazec.\n\nExample: Rozpoznanie klienta\n```js\nvar ua = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36';\nua.parseUA();\t\t// Mac Chrome\nua.parseUA(true);\t// { os: 'Mac', browser: 'Chrome', device: 'desktop' }\n\n// in a controller\nvar info = (self.req.headers['user-agent'] || '').parseUA(true);\n```\n\n### String.parseEncoded()\n\nType: `method`\n\nSpracuje text `application/x-www-form-urlencoded` do objektu.\n\nReturns: `Object` Spracované kľúče a hodnoty.\n\nText vyzerá ako query string: `key=value&key2=value2`. `+` sa zmení na medzeru a sekvencie `%xx` sa dekódujú. Všetky hodnoty zostanú reťazcami; opakovaný kľúč spojí svoje hodnoty čiarkou. Kľúče môžu obsahovať iba písmená, číslice a `-`, `_`, `.`, `[`, `]` a spracovanie sa zastaví pri prvom inom znaku v kľúči. Počet kľúčov obmedzuje `CONF.default_request_maxkeys` a dĺžku kľúča `CONF.default_request_maxkey`.\n\nExample: Spracovanie tela formulára\n```js\nvar data = 'name=Peter+Sirka&tags=a&tags=b&city=Bratislava%2C%20SK'.parseEncoded();\n// { name: 'Peter Sirka', tags: 'a,b', city: 'Bratislava, SK' }\n```\n\n### String.parseXML([replace])\n\nType: `method`\n\nSpracuje XML do plochého objektu ciest a hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `replace` | `Boolean` | no | `false` | Nahradiť špeciálne znaky v kľúčoch znakom `_`. |\n\nReturns: `Object` Plochý objekt ciest.\n\nKaždý element s textom sa stane kľúčom zloženým z názvov elementov spojených bodkami, napríklad `book.title`. Opakovaný element dá pole hodnôt. Atribúty elementu sa ukladajú ako objekt pod cestou, za ktorou nasleduje `[]`. Sekcie `CDATA` sa čítajú ako text a komentáre sa preskočia. S `replace` nastaveným na `true` sa znaky `[`, `]`, `:`, `.` a `_` v kľúčoch nahradia `_`.\n\nExample: Čítanie XML feedu\n```js\nvar xml = '<book id=\"1\"><title>Total.js</title><tag>node</tag><tag>web</tag></book>';\nvar obj = xml.parseXML();\n// obj['book.title'] === 'Total.js'\n// obj['book.tag'] => ['node', 'web']\n// obj['book[]'] => { id: '1' }\n```\n\n### String.parseHTML([trim])\n\nType: `method` · Since: `0.0.67`\n\nSpracuje HTML do stromu elementov, v ktorom môžeš vyhľadávať a meniť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Orezať textový obsah. |\n\nReturns: `HTMLElement` Koreňový element spracovaného dokumentu.\n\nMetóda používa vstavaný HTML parser a vráti koreňový element. Elementy majú `tagName`, `attrs`, `children` a `parentNode` a metódy `find(selector)`, `closest(selector)`, `parent()`, `attr()`, `aclass()`, `rclass()`, `hclass()`, `tclass()`, `css()`, `append()`, `prepend()`, `remove()`, `text()` a `html([formatted])`. S `trim` nastaveným na `true` sa text v elementoch oreže.\n\nExample: Čítanie a zmena HTML\n```js\nvar dom = '<div><a href=\"/docs/\" class=\"link\">Docs</a></div>'.parseHTML(true);\nvar links = dom.find('a');\n\nfor (var i = 0; i < links.length; i++)\n\tlinks[i].attr('target', '_blank');\n\nconsole.log(dom.html());\n```\n\n### String.parseComponent(tags)\n\nType: `method`\n\nVystrihne z textu označené bloky a vráti ich obsah podľa názvu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `tags` | `Object` | yes |  | Názov a otvárací tag každého bloku. |\n\nReturns: `Object` Obsah každého nájdeného bloku.\n\n`tags` mapuje názov na otvárací tag, napríklad `{ js: '<script>', css: '<style>' }`. Pre každý názov sa vráti obsah medzi otváracím tagom a jeho uzatváracím tagom (vnorené tagy rovnakého druhu sa započítavajú). Chýbajúci tag nedá žiadny kľúč. Total.js to používa na čítanie časti `<script total>` z `.html` pluginov a komponentov.\n\nExample: Rozdelenie súboru komponentu\n```js\nvar html = '<style>.box { color: red; }</style>\\n<script>console.log(1);</script>\\n<div class=\"box\"></div>';\nvar parts = html.parseComponent({ css: '<style>', js: '<script>' });\n// parts.css === '.box { color: red; }'\n// parts.js === 'console.log(1);'\n```\n\n### String.parseTerminal([fields], fn, [skip], [take])\n\nType: `method`\n\nSpracuje stĺpcový výstup príkazu terminálu riadok po riadku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `Array` | no |  | Názvy z hlavičky alebo regulárne výrazy stĺpcov. |\n| `fn` | `Function` | yes |  | Volá sa ako `fn(values, index, count, line)` pre každý riadok. |\n| `skip` | `Number` | no | `0` | Počet riadkov na preskočenie. |\n| `take` | `Number` | no | `all` | Počet riadkov na prečítanie. |\n\nReturns: `String` Ten istý reťazec.\n\nS `fields` je prvý neprázdny riadok (z prvých troch) hlavičkou. Každé pole je názov z hlavičky (`String`) alebo `RegExp`, ktorý nájde stĺpec v riadku hlavičky, a `fn` dostane hodnoty týchto stĺpcov pre každý nasledujúci riadok. Bez `fields` sa každý riadok rozdelí na slová a `fn` dostane pole slov. `fn(values, index, count, line)` dostane hodnoty, index spracovaného riadka, koncový index a číslo riadka. `skip` a `take` obmedzujú riadky. Metóda vracia samotný reťazec.\n\nExample: Čítanie výstupu df\n```js\nvar Exec = require('child_process').exec;\n\nExec('df -h', function(err, output) {\n\toutput.parseTerminal(['Filesystem', 'Size', 'Used'], function(values) {\n\t\tconsole.log(values[0], values[1], values[2]);\n\t});\n});\n```\n\n### String.parseConfig([def], [onerror])\n\nType: `method`\n\nSpracuje text vo formáte konfigurácie Total.js do objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Object` | no |  | Predvolené hodnoty skopírované do výsledku. |\n| `onerror` | `Function` | no |  | Volá sa ako `onerror(err, line)`, keď hodnota `object` alebo `eval` zlyhá. |\n\nReturns: `Object` Sparsované hodnoty.\n\nKaždý riadok je `key : value` a riadky začínajúce `#` alebo `//` sa preskočia. Hodnota začína dva znaky za prvou `:`, preto za dvojbodku napíš medzeru. Typ v zátvorkách za kľúčom prevedie hodnotu: `(string)`, `(number)`, `(float)`, `(currency)`, `(boolean)`, `(array)` (oddelené čiarkami), `(json)`, `(object)` alebo `(eval)` (vyhodnotí sa ako JavaScript), `(date)`, `(env)` (premenná prostredia), `(config)` (iný kľúč `CONF`) a `(random)` (náhodný reťazec zadanej dĺžky). `def` dáva predvolené hodnoty. `onerror(err, line)` spracuje hodnotu, ktorú nemožno vyhodnotiť; bez neho metóda vyhodí výnimku.\n\nExample: Spracovanie konfiguračného textu\n```js\nvar text = 'name : Eshop\\nport (number) : 8000\\nallow (boolean) : true\\nlanguages (array) : en, sk';\nvar cfg = text.parseConfig({ port: 80 });\n// { port: 8000, name: 'Eshop', allow: true, languages: ['en', 'sk'] }\n```\n\n### String.parseDateExpiration()\n\nType: `method`\n\nZmení text ako `5 minutes` na dátum v budúcnosti.\n\nReturns: `Date` Aktuálny dátum plus zadaný čas.\n\nText sa číta ako páry čísla a jednotky oddelené medzerami, napríklad `1 day 12 hours`. Každý pár sa pripočíta k aktuálnemu dátumu cez `Date.add()`, takže fungujú rovnaké jednotky (`seconds`, `minutes`, `hours`, `days`, `weeks`, `months`, `years`). Pár s číslom `0` sa ignoruje.\n\nExample: Expirácia cookie\n```js\nvar expire = '7 days'.parseDateExpiration();\nself.cookie('token', token, expire);\n\n'1 day 12 hours'.parseDateExpiration();\n```\n\n### String.parseUID()\n\nType: `method`\n\nPrečíta informácie uložené v identifikátore vytvorenom cez `UID()`.\n\nReturns: `Object` `{ version, date, century, index, hash, valid }`.\n\nVýsledok má `version` (posledný znak UID), `date` (kedy bol vytvorený), `century`, `index` (počítadlo), `hash` a `valid`. Pre náhodnú verziu `r` (`CONF.default_uid = 'r'`) výsledok nemá dátum a identifikátory sa validujú cez `String.isUID()`.\n\nExample: Kedy bol záznam vytvorený\n```js\nvar id = UID();\nvar info = id.parseUID();\nconsole.log(info.date, info.index, info.valid);\n```\n\n### String.parseFloat2([def])\n\nType: `method`\n\nNájde prvé desatinné číslo v texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `def` | `Number` | no | `0` | Hodnota vrátená, keď sa nenájde žiadne číslo. |\n\nReturns: `Number` Nájdené číslo.\n\nNa rozdiel od `String.parseFloat()` môže text obsahovať iné znaky: použije sa prvá skupina číslic, bodiek a čiarok a čiarky sa zmenia na bodky. Úvodné `-` ho urobí záporným. Bez čísla metóda vráti `def`.\n\nExample: Cena zo štítku\n```js\n'Price: 12,50 EUR'.parseFloat2();\t// 12.5\n'no number'.parseFloat2(-1);\t\t// -1\n```\n\n### String.isGUID()\n\nType: `method` · Since: `0.0.48`\n\nSkontroluje, či je reťazec GUID (UUID).\n\nReturns: `Boolean`\n\nReťazec musí mať 36 znakov v tvare `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`, kde `M` je verzia od 1 do 5. Akceptujú sa veľké aj malé písmená.\n\nExample: Validácia UUID\n```js\n'550e8400-e29b-41d4-a716-446655440000'.isGUID();\t// true\n'550e8400'.isGUID();\t\t\t\t\t\t\t\t// false\n```\n\n### String.isJSONDate()\n\nType: `method`\n\nSkontroluje, či je reťazec dátum vo formáte JSON (ISO 8601 UTC).\n\nReturns: `Boolean`\n\nMetóda kontroluje tvar textu, napríklad `2024-05-01T10:30:00.000Z`: dĺžku, `T`, pomlčky a dvojbodky a koncové `Z`. Nekontroluje, či dátum existuje.\n\nExample: Obnovenie dátumov\n```js\nvar value = '2024-05-01T10:30:00.000Z';\nif (value.isJSONDate())\n\tvalue = new Date(value);\n```\n\n### String.isNumber([decimal])\n\nType: `method`\n\nSkontroluje, či reťazec obsahuje iba číslice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimal` | `Boolean` | no | `false` | Povoliť jeden desatinný oddeľovač. |\n\nReturns: `Boolean`\n\nS `decimal` nastaveným na `true` je povolená aj jedna `.` alebo `,`. Znamienka, medzery a exponenty sa neakceptujú a prázdny reťazec vráti `false`.\n\nExample: Kontrola vstupu používateľa\n```js\n'12345'.isNumber();\t\t// true\n'12.5'.isNumber();\t\t// false\n'12.5'.isNumber(true);\t// true\n'-1'.isNumber();\t\t// false\n```\n\n### String.isBoolean()\n\nType: `method`\n\nSkontroluje, či je reťazec `true` alebo `false`.\n\nReturns: `Boolean`\n\nPorovnanie ignoruje veľkosť písmen. Iné hodnoty ako `1` alebo `on` vrátia `false`; tie číta `String.parseBoolean()`.\n\nExample: Kontrola hodnoty z query\n```js\n'TRUE'.isBoolean();\t// true\n'on'.isBoolean();\t// false\n```\n\n### String.isZIP()\n\nType: `method`\n\nSkontroluje, či reťazec vyzerá ako PSČ (ZIP kód).\n\nReturns: `Boolean`\n\nReťazec sa testuje cez `DEF.validators.zip`, predvolene 3 až 20 písmen, číslic, medzier alebo pomlčiek. Zmeň `DEF.validators.zip`, ak chceš vlastné pravidlo.\n\nExample: Validácia PSČ\n```js\n'821 08'.isZIP();\t// true\n'12'.isZIP();\t\t// false\n```\n\n### String.isXSS()\n\nType: `method`\n\nSkontroluje, či reťazec obsahuje HTML tag.\n\nReturns: `Boolean`\n\nTest je jednoduchý: vráti `true`, keď text obsahuje `<`, za ktorým neskôr nasleduje `>`. Použi ho na odmietnutie HTML v textových poliach.\n\nExample: Odmietnutie HTML\n```js\n'Hello world'.isXSS();\t\t\t\t// false\n'<script>alert(1)</script>'.isXSS();\t// true\n```\n\n### String.isSQLInjection()\n\nType: `method`\n\nSkontroluje, či reťazec obsahuje text v úvodzovkách alebo SQL kľúčové slovo.\n\nReturns: `Boolean`\n\nMetóda vráti `true` pre text v jednoduchých úvodzovkách alebo pre slová veľkými písmenami `ALTER`, `CREATE`, `DELETE`, `DROP`, `EXEC`, `EXECUTE`, `INSERT`, `MERGE`, `SELECT`, `UPDATE` a `UNION`. Je to hrubá kontrola; v dotazoch aj tak používaj parametre.\n\nExample: Kontrola hľadanej frázy\n```js\n'shoes'.isSQLInjection();\t\t\t\t\t// false\n\"1; DROP TABLE users\".isSQLInjection();\t// true\n```\n\n### String.isBase64([data])\n\nType: `method`\n\nSkontroluje, či je reťazec zakódovaný v base64.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Boolean` | no | `false` | Akceptovať prefix data URI. |\n\nReturns: `Boolean`\n\nDĺžka musí byť deliteľná 4 a text musí obsahovať iba znaky base64. S `data` nastaveným na `true` sa akceptuje data URI ako `data:image/png;base64,...` a kontroluje sa iba dĺžka zakódovanej časti.\n\nExample: Kontrola nahraného súboru\n```js\n'SGVsbG8='.isBase64();\t\t\t\t\t\t// true\n'data:image/png;base64,iVBORw0K'.isBase64(true);\t// true\n```\n\n### String.base64ToFile(filename, [callback])\n\nType: `method`\n\nZapíše base64 dáta do súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Cesta k súboru. |\n| `callback` | `Function` | no |  | Volá sa ako `callback(err)`, keď je súbor zapísaný. |\n\nReturns: `String` Ten istý reťazec.\n\nPrefix data URI (všetko po prvú čiarku) sa odstráni a zvyšok sa dekóduje a zapíše cez `fs.writeFile()`. Metóda vracia samotný reťazec; výsledok zápisu príde do `callback(err)`.\n\nExample: Uloženie nahraného obrázka\n```js\nmodel.photo.base64ToFile(PATH.public('photos/' + UID() + '.png'), function(err) {\n\terr && console.log(err);\n});\n```\n\n### String.base64ToBuffer()\n\nType: `method`\n\nDekóduje base64 dáta do `Buffer`.\n\nReturns: `Buffer` Dekódované dáta.\n\nPrefix data URI (všetko po prvú čiarku) sa pred dekódovaním odstráni.\n\nExample: Dekódovanie data URI\n```js\nvar buffer = 'data:text/plain;base64,SGVsbG8='.base64ToBuffer();\nbuffer.toString(); // Hello\n```\n\n### String.base64ContentType()\n\nType: `method`\n\nVráti content type data URI.\n\nReturns: `String` Content type, napríklad `image/png`.\n\nVráti sa text medzi `data:` a prvou `;`. Reťazec bez `;` vráti prázdny reťazec.\n\nExample: Kontrola typu nahraného súboru\n```js\nvar type = 'data:image/png;base64,iVBORw0K'.base64ContentType(); // image/png\nif (type !== 'image/png' && type !== 'image/jpeg')\n\t$.invalid('@photo');\n```\n\n### String.crc32([unsigned])\n\nType: `method`\n\nVypočíta kontrolný súčet CRC32 reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `unsigned` | `Boolean` | no | `false` | Vrátiť číslo bez znamienka. |\n\nReturns: `Number` Kontrolný súčet.\n\nVýsledkom je 32-bitové číslo so znamienkom, alebo bez znamienka, keď je `unsigned` `true`. `String.hash('crc32')` a `String.hash('crc32unsigned')` dávajú rovnaké výsledky.\n\nExample: Kontrolný súčet textu\n```js\nvar checksum = 'Hello world'.crc32(true);\nvar key = checksum.toString(36);\n```\n\n### String.sha1([salt])\n\nType: `method`\n\nVytvorí SHA-1 hash reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` Hash v hexadecimálnom tvare.\n\n`salt` sa pred hashovaním pripojí k reťazcu.\n\nExample: SHA-1 hash\n```js\nvar hash = 'Hello world'.sha1();\nvar salted = 'Hello world'.sha1(CONF.secret);\n```\n\n### String.sha512([salt])\n\nType: `method`\n\nVytvorí SHA-512 hash reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `salt` | `String` | no |  | Text pripojený pred hashovaním. |\n\nReturns: `String` Hash v hexadecimálnom tvare.\n\n`salt` sa pred hashovaním pripojí k reťazcu.\n\nExample: Hash tokenu\n```js\nvar hash = token.sha512(CONF.secret);\n```\n\n### String.makeid()\n\nType: `method`\n\nVytvorí z reťazca krátke id.\n\nReturns: `String` Id.\n\nId je rýchly bezznamienkový hash reťazca zapísaný v sústave 36. Rovnaký reťazec dá vždy rovnaké id. Nie je to kryptografický hash.\n\nExample: Id pre kľúč cache\n```js\nvar key = ('products_' + JSON.stringify(query)).makeid();\n```\n\n### String.sign([key])\n\nType: `method` · Since: `0.0.81`\n\nPridá k reťazcu rýchly kontrolný súčet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no |  | Tajomstvo primiešané do kontrolného súčtu. |\n\nReturns: `String` Reťazec s kontrolným súčtom.\n\nVýsledkom je reťazec, pomlčka a hash reťazca s `key` v sústave 36. Na overenie hodnoty znova podpíš časť pred poslednou pomlčkou a porovnaj. Je to rýchly kontrolný súčet, nie kryptografický podpis.\n\nExample: Podpísanie a overenie hodnoty\n```js\nvar signed = '12345'.sign(CONF.secret); // 12345-xxxxxx\n\nvar value = signed.substring(0, signed.lastIndexOf('-'));\nvar ok = value.sign(CONF.secret) === signed;\n```\n\n### String.encrypt_uid([key])\n\nType: `method`\n\nOchráni identifikátor kontrolným súčtom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Tajomstvo. |\n\nReturns: `String` Chránený identifikátor.\n\nVýsledkom je `x`, kontrolný súčet a `x`, za ktorými nasleduje pôvodná hodnota, takže hodnota zostane čitateľná, ale bez kľúča sa nedá zmeniť. Kontrolný súčet používa `key` (predvolene `CONF.secret`) a `CONF.secret_uid`. Späť ho prečítaš cez `String.decrypt_uid()`. Rovnaká funkcia pre čísla je `U.encrypt_uid(value, [key])`.\n\nExample: Chránené id v odkaze\n```js\nvar token = user.id.encrypt_uid();\nvar link = '/unsubscribe/?id=' + token;\n```\n\n### String.decrypt_uid([key])\n\nType: `method`\n\nPrečíta identifikátor chránený cez `String.encrypt_uid()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | no | `CONF.secret` | Tajomstvo použité pre `encrypt_uid()`. |\n\nReturns: `String|Number` Pôvodná hodnota, alebo `null`, keď je kontrolný súčet nesprávny.\n\nKontrolný súčet sa znova vytvorí s `key` (predvolene `CONF.secret`). Keď sa zhoduje, vráti sa pôvodná hodnota, inak `null`. Hodnota vytvorená z čísla sa vráti ako číslo.\n\nExample: Overenie odkazu\n```js\nvar id = (self.query.id || '').decrypt_uid();\nif (!id) {\n\tself.invalid('@id');\n\treturn;\n}\n```\n\n### String.toName()\n\nType: `method`\n\nVyčistí meno osoby: odstráni iné znaky a každé slovo začne veľkým písmenom.\n\nReturns: `String` Vyčistené meno.\n\nČíslice a ASCII interpunkcia sa odstránia, medzery sa zachovajú a prvé písmeno každého slova sa zmení na veľké. Písmená s diakritikou sa zachovajú. Koncové medzery sa zahodia, ale úvodné a opakované nie, preto vstup najprv orež.\n\nExample: Vyčistenie mena z formulára\n```js\n'peter sirka2'.toName();\t// Peter Sirka\n\"john o'neil\".toName();\t// John Oneil\n```\n\n### String.toUnicode()\n\nType: `method`\n\nEscapuje znaky mimo tlačiteľného ASCII ako `\\uXXXX`.\n\nReturns: `String` Escapovaný reťazec.\n\nZnaky s kódom pod 32 alebo nad 126 sa zapíšu ako `\\u` a štyri hexadecimálne číslice. `String.fromUnicode()` to vráti späť.\n\nExample: Escapovanie textu\n```js\n'Žltý kôň'.toUnicode(); // \\u017dlt\\u00fd k\\u00f4\\u0148\n```\n\n### String.fromUnicode()\n\nType: `method`\n\nZmení escape sekvencie `\\uXXXX` späť na znaky.\n\nReturns: `String` Reťazec bez escapovania.\n\nKaždé `\\u`, za ktorým nasledujú štyri hexadecimálne číslice, sa nahradí znakom. Je to opak `String.toUnicode()`.\n\nExample: Zrušenie escapovania textu\n```js\n'\\\\u017dlt\\\\u00fd'.fromUnicode(); // Žltý\n```\n\n### String.endsWith(text, [ignoreCase])\n\nType: `method`\n\nSkontroluje, či reťazec končí textom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `text` | `String` | yes |  | Hľadaný text. |\n| `ignoreCase` | `Boolean|Number` | no | `false` | `true` na ignorovanie veľkosti písmen, alebo posun od konca. |\n\nReturns: `Boolean`\n\nTotal.js nahrádza natívnu metódu. S `ignoreCase` nastaveným na `true` sa veľkosť písmen ignoruje. Číslo namiesto `ignoreCase` kontroluje text o toľko znakov pred koncom.\n\nExample: Kontrola prípony súboru\n```js\n'Photo.JPG'.endsWith('.jpg', true);\t// true\n'Photo.JPG'.endsWith('.jpg');\t\t// false\n```\n\n### String.replacer(find, text)\n\nType: `method`\n\nNahradí prvý výskyt textu, bez regulárnych výrazov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `find` | `String` | yes |  | Text, ktorý sa nahradí. |\n| `text` | `String` | yes |  | Nový text. |\n\nReturns: `String` Nový reťazec.\n\n`find` je obyčajný text, takže znaky ako `$` alebo `.` v ňom ani v `text` nemajú špeciálny význam. Keď sa `find` nenájde, reťazec sa vráti nezmenený.\n\nExample: Vloženie ceny do šablóny\n```js\n'Total: {price}'.replacer('{price}', '$ 25'); // Total: $ 25\n```\n\n### String.insert(index, value)\n\nType: `method`\n\nVloží hodnotu na pozíciu v reťazci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | yes |  | Pozícia. |\n| `value` | `Object` | yes |  | Hodnota na vloženie. |\n\nReturns: `String` Nový reťazec.\n\nHodnota sa prevedie na reťazec cez `toString()`.\n\nExample: Formátovanie kódu\n```js\n'ABCDEF'.insert(3, '-'); // ABC-DEF\n```\n\n### String.indent(count, [char])\n\nType: `method`\n\nPridá znak na začiatok reťazca daný počet krát.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Koľko znakov pridať. |\n| `char` | `String` | no | `' '` | Znak. |\n\nReturns: `String` Odsadený reťazec.\n\nNa rozdiel od `String.padLeft()` sa znaky pridajú vždy, bez ohľadu na dĺžku reťazca.\n\nExample: Odsadenie riadka\n```js\n'item'.indent(2, '\\t'); // \\t\\titem\n'item'.indent(4);\t\t// '    item'\n```\n\n### String.pluralize(zero, one, few, other)\n\nType: `method`\n\nVyberie tvar slova podľa čísla v reťazci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `zero` | `String` | yes |  | Tvar pre 0, alebo všetky tvary oddelené čiarkami. |\n| `one` | `String` | no |  | Tvar pre 1. |\n| `few` | `String` | no |  | Tvar pre 2 až 4. |\n| `other` | `String` | no |  | Tvar pre ostatné čísla. |\n\nReturns: `String` Vybraný tvar.\n\nReťazec sa prečíta cez `String.parseInt()` a odovzdá do `Number.pluralize()`, takže pravidlá aj zástupný symbol `#` sú rovnaké.\n\nExample: Počet z query stringu\n```js\nvar count = self.query.count || '0';\ncount.pluralize('no items', '# item', '# items', '# items');\n```\n\n### String.env()\n\nType: `method`\n\nNahradí zástupné symboly `[key]` hodnotami konfigurácie.\n\nReturns: `String` Reťazec s hodnotami.\n\nKaždý `[key]` (písmená, číslice a `_`) sa nahradí `CONF[key]`; chýbajúci kľúč dá prázdny reťazec.\n\nExample: Zostavenie URL z konfigurácie\n```js\n// CONF.url = 'https://www.example.com'\n'[url]/api/products/'.env(); // https://www.example.com/api/products/\n```\n\n### String.streamer(beg, [end], callback, [skip])\n\nType: `method` · Since: `0.0.63`\n\nNájde v reťazci bloky a každý odovzdá callbacku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `beg` | `String` | yes |  | Počiatočný oddeľovač, alebo separátor, keď chýba `end`. |\n| `end` | `String` | no |  | Koncový oddeľovač. |\n| `callback` | `Function` | yes |  | Volá sa ako `callback(value, index)`; vráť `false` na zastavenie. |\n| `skip` | `Number` | no | `0` | Počet blokov na preskočenie. |\n\nReturns: `undefined`\n\nS `beg` a `end` sa odovzdá každý blok, ktorý začína `beg` a končí `end`, vrátane oddeľovačov. Bez `end` sa reťazec rozdelí za každým `beg` a každá časť končí `beg`. `callback(value, index)` môže vrátiť `false` na zastavenie. `skip` preskočí prvé bloky.\n\nExample: Čítanie položiek z XML\n```js\nvar xml = '<items><item>A</item><item>B</item></items>';\nxml.streamer('<item>', '</item>', function(value, index) {\n\tconsole.log(index, value); // 0 <item>A</item>, 1 <item>B</item>\n});\n```\n\n### Number.fixed(decimals)\n\nType: `method`\n\nZaokrúhli číslo na daný počet desatinných miest a vráti číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `decimals` | `Number` | yes |  | Počet desatinných miest. |\n\nReturns: `Number` Zaokrúhlené číslo.\n\nTo isté ako `+number.toFixed(decimals)`: na rozdiel od `toFixed()` je výsledkom číslo, nie reťazec.\n\nExample: Zaokrúhlenie ceny\n```js\n(12.3456).fixed(2); // 12.35\n```\n\n### Number.currency([currency], [a], [b], [c])\n\nType: `method`\n\nNaformátuje číslo formátovačom meny z `DEF.currencies`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `currency` | `String` | no | `'default'` | Kľúč v `DEF.currencies`. |\n| `a` | `Object` | no |  | Odovzdá sa formátovaču, rovnako ako `b` a `c`. |\n\nReturns: `String` Naformátovaná cena.\n\n`DEF.currencies` je predvolene prázdny; pridaj funkciu `function(value, a, b, c)` pre každý kód meny, ktorý potrebuješ, a `default` pre volania bez kódu. Ďalšie argumenty sa jej odovzdajú. Bez formátovača sa číslo naformátuje cez `Number.format(2)`.\n\nExample: Registrácia a použitie mien\n```js\nDEF.currencies.eur = function(value) {\n\treturn value.format(2, ' ', ',') + ' €';\n};\n\nDEF.currencies.usd = function(value) {\n\treturn '$' + value.format(2);\n};\n\n(1250.5).currency('eur'); // 1 250,50 €\n```\n\n### Number.hex([length])\n\nType: `method`\n\nPrevedie číslo na hexadecimálny tvar veľkými písmenami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `length` | `Number` | no |  | Minimálna dĺžka. |\n\nReturns: `String` Hexadecimálna hodnota.\n\nVýsledok sa doplní úvodnými nulami na `length` znakov.\n\nExample: Zložka farby\n```js\n(255).hex();\t// FF\n(10).hex(2);\t// 0A\n```\n\n### Number.parseDate([plus])\n\nType: `method`\n\nVytvorí dátum z časovej značky v milisekundách.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `plus` | `Number` | no | `0` | Milisekundy na pripočítanie. |\n\nReturns: `Date` Dátum.\n\nK číslu sa pred vytvorením dátumu pripočíta `plus` milisekúnd.\n\nExample: Dátum z časovej značky\n```js\nvar created = (1714559400000).parseDate();\nvar tomorrow = Date.now().parseDate(24 * 60 * 60 * 1000);\n```\n\n### Number.toRad()\n\nType: `method`\n\nPrevedie stupne na radiány.\n\nReturns: `Number` Uhol v radiánoch.\n\nDefinuje sa iba vtedy, keď `Number.prototype.toRad` ešte neexistuje.\n\nExample: Vzdialenosť medzi dvoma GPS bodmi\n```js\nvar dlat = (lat2 - lat1).toRad();\nvar dlon = (lon2 - lon1).toRad();\n```\n\n### Date.parseDate()\n\nType: `method`\n\nVráti samotný dátum.\n\nReturns: `Date` Ten istý dátum.\n\nUmožňuje zavolať `parseDate()` na hodnotu, ktorá môže byť reťazec, číslo alebo dátum, bez toho, aby si najprv kontroloval jej typ.\n\nExample: Hodnota neznámeho typu\n```js\nvar value = model.date; // String, Number or Date\nvar date = value.parseDate();\n```\n","entries":[{"type":"method","name":"String.format()","signature":"String.format([arg0], [arg1], [...])","since":"","deprecated":false},{"type":"method","name":"String.args()","signature":"String.args(obj, [encode], [def])","since":"","deprecated":false},{"type":"method","name":"String.slug()","signature":"String.slug([max])","since":"","deprecated":false},{"type":"method","name":"String.max()","signature":"String.max(length, [chars])","since":"","deprecated":false},{"type":"method","name":"String.capitalize()","signature":"String.capitalize([first])","since":"","deprecated":false},{"type":"method","name":"String.parseInt()","signature":"String.parseInt([def])","since":"","deprecated":false},{"type":"method","name":"String.parseInt2()","signature":"String.parseInt2([def])","since":"","deprecated":false},{"type":"method","name":"String.parseFloat()","signature":"String.parseFloat([def])","since":"","deprecated":false},{"type":"method","name":"String.parseBoolean()","signature":"String.parseBoolean()","since":"","deprecated":false},{"type":"method","name":"String.parseDate()","signature":"String.parseDate([format])","since":"","deprecated":false},{"type":"method","name":"String.parseJSON()","signature":"String.parseJSON([date])","since":"","deprecated":false},{"type":"method","name":"String.parseENV()","signature":"String.parseENV()","since":"","deprecated":false},{"type":"method","name":"String.isEmail()","signature":"String.isEmail()","since":"","deprecated":false},{"type":"method","name":"String.isPhone()","signature":"String.isPhone()","since":"","deprecated":false},{"type":"method","name":"String.isURL()","signature":"String.isURL()","since":"","deprecated":false},{"type":"method","name":"String.isUID()","signature":"String.isUID()","since":"","deprecated":false},{"type":"method","name":"String.isJSON()","signature":"String.isJSON()","since":"","deprecated":false},{"type":"method","name":"String.hash()","signature":"String.hash([type], [salt])","since":"","deprecated":false},{"type":"method","name":"String.md5()","signature":"String.md5([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha256()","signature":"String.sha256([salt])","since":"","deprecated":false},{"type":"method","name":"String.encode()","signature":"String.encode()","since":"","deprecated":false},{"type":"method","name":"String.decode()","signature":"String.decode()","since":"","deprecated":false},{"type":"method","name":"String.encrypt()","signature":"String.encrypt(key, [isUnique], [secret])","since":"","deprecated":false},{"type":"method","name":"String.decrypt()","signature":"String.decrypt(key, [secret])","since":"","deprecated":false},{"type":"method","name":"String.keywords()","signature":"String.keywords([forSearch], [alternative], [max_count], [max_length], [min_length])","since":"","deprecated":false},{"type":"method","name":"String.toSearch()","signature":"String.toSearch()","since":"","deprecated":false},{"type":"method","name":"String.toASCII()","signature":"String.toASCII()","since":"","deprecated":false},{"type":"method","name":"String.removeTags()","signature":"String.removeTags()","since":"","deprecated":false},{"type":"method","name":"String.padLeft()","signature":"String.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.padRight()","signature":"String.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"String.startsWith()","signature":"String.startsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"0.0.92","deprecated":false},{"type":"method","name":"String.tslash()","signature":"String.tslash()","since":"0.0.95","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"","deprecated":false},{"type":"method","name":"Number.format()","signature":"Number.format([decimals], [separator], [separatorDecimal])","since":"","deprecated":false},{"type":"method","name":"Number.pluralize()","signature":"Number.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Number.padLeft()","signature":"Number.padLeft(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.padRight()","signature":"Number.padRight(max, [c])","since":"","deprecated":false},{"type":"method","name":"Number.round()","signature":"Number.round([precision])","since":"","deprecated":false},{"type":"method","name":"Number.floor()","signature":"Number.floor(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.between()","signature":"Number.between(condition, otherwise)","since":"","deprecated":false},{"type":"method","name":"Number.add()","signature":"Number.add(value, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.VAT()","signature":"Number.VAT(percentage, [decimals], [includedVAT])","since":"","deprecated":false},{"type":"method","name":"Number.discount()","signature":"Number.discount(percentage, [decimals])","since":"","deprecated":false},{"type":"method","name":"Number.filesize()","signature":"Number.filesize([decimals], [type])","since":"","deprecated":false},{"type":"method","name":"Number.async()","signature":"Number.async(fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Date.add()","signature":"Date.add(type, [value])","since":"","deprecated":false},{"type":"method","name":"Date.format()","signature":"Date.format([format], [resource])","since":"","deprecated":false},{"type":"method","name":"Date.diff()","signature":"Date.diff([date], type)","since":"","deprecated":false},{"type":"method","name":"Date.toUTC()","signature":"Date.toUTC([ticks])","since":"","deprecated":false},{"type":"method","name":"Date.extend()","signature":"Date.extend(date)","since":"","deprecated":false},{"type":"method","name":"Date.setTimeZone()","signature":"Date.setTimeZone(timezone)","since":"","deprecated":false},{"type":"method","name":"Array.findItem()","signature":"Array.findItem(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findAll()","signature":"Array.findAll(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.findIndex()","signature":"Array.findIndex(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.TfindIndex()","signature":"Array.TfindIndex(cb, [value])","since":"0.0.95","deprecated":false},{"type":"method","name":"Array.findValue()","signature":"Array.findValue(cb, value, path, [def])","since":"","deprecated":false},{"type":"method","name":"Array.remove()","signature":"Array.remove(cb, [value])","since":"","deprecated":false},{"type":"method","name":"Array.take()","signature":"Array.take(count)","since":"","deprecated":false},{"type":"method","name":"Array.skip()","signature":"Array.skip(count)","since":"","deprecated":false},{"type":"method","name":"Array.first()","signature":"Array.first([def])","since":"","deprecated":false},{"type":"method","name":"Array.last()","signature":"Array.last([def])","since":"","deprecated":false},{"type":"method","name":"Array.quicksort()","signature":"Array.quicksort([sort], [desc])","since":"","deprecated":false},{"type":"method","name":"Array.toObject()","signature":"Array.toObject([name])","since":"","deprecated":false},{"type":"method","name":"Array.trim()","signature":"Array.trim()","since":"","deprecated":false},{"type":"method","name":"Array.wait()","signature":"Array.wait(onItem, [callback], [thread])","since":"","deprecated":false},{"type":"method","name":"Array.async()","signature":"Array.async([thread], [callback])","since":"","deprecated":false},{"type":"method","name":"Array.limit()","signature":"Array.limit(max, fn, [callback])","since":"","deprecated":false},{"type":"method","name":"Array.random()","signature":"Array.random([item])","since":"","deprecated":false},{"type":"method","name":"String.parseCSV()","signature":"String.parseCSV([delimiter])","since":"","deprecated":false},{"type":"method","name":"String.parseUA()","signature":"String.parseUA([structured])","since":"","deprecated":false},{"type":"method","name":"String.parseEncoded()","signature":"String.parseEncoded()","since":"","deprecated":false},{"type":"method","name":"String.parseXML()","signature":"String.parseXML([replace])","since":"","deprecated":false},{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"0.0.67","deprecated":false},{"type":"method","name":"String.parseComponent()","signature":"String.parseComponent(tags)","since":"","deprecated":false},{"type":"method","name":"String.parseTerminal()","signature":"String.parseTerminal([fields], fn, [skip], [take])","since":"","deprecated":false},{"type":"method","name":"String.parseConfig()","signature":"String.parseConfig([def], [onerror])","since":"","deprecated":false},{"type":"method","name":"String.parseDateExpiration()","signature":"String.parseDateExpiration()","since":"","deprecated":false},{"type":"method","name":"String.parseUID()","signature":"String.parseUID()","since":"","deprecated":false},{"type":"method","name":"String.parseFloat2()","signature":"String.parseFloat2([def])","since":"","deprecated":false},{"type":"method","name":"String.isGUID()","signature":"String.isGUID()","since":"0.0.48","deprecated":false},{"type":"method","name":"String.isJSONDate()","signature":"String.isJSONDate()","since":"","deprecated":false},{"type":"method","name":"String.isNumber()","signature":"String.isNumber([decimal])","since":"","deprecated":false},{"type":"method","name":"String.isBoolean()","signature":"String.isBoolean()","since":"","deprecated":false},{"type":"method","name":"String.isZIP()","signature":"String.isZIP()","since":"","deprecated":false},{"type":"method","name":"String.isXSS()","signature":"String.isXSS()","since":"","deprecated":false},{"type":"method","name":"String.isSQLInjection()","signature":"String.isSQLInjection()","since":"","deprecated":false},{"type":"method","name":"String.isBase64()","signature":"String.isBase64([data])","since":"","deprecated":false},{"type":"method","name":"String.base64ToFile()","signature":"String.base64ToFile(filename, [callback])","since":"","deprecated":false},{"type":"method","name":"String.base64ToBuffer()","signature":"String.base64ToBuffer()","since":"","deprecated":false},{"type":"method","name":"String.base64ContentType()","signature":"String.base64ContentType()","since":"","deprecated":false},{"type":"method","name":"String.crc32()","signature":"String.crc32([unsigned])","since":"","deprecated":false},{"type":"method","name":"String.sha1()","signature":"String.sha1([salt])","since":"","deprecated":false},{"type":"method","name":"String.sha512()","signature":"String.sha512([salt])","since":"","deprecated":false},{"type":"method","name":"String.makeid()","signature":"String.makeid()","since":"","deprecated":false},{"type":"method","name":"String.sign()","signature":"String.sign([key])","since":"0.0.81","deprecated":false},{"type":"method","name":"String.encrypt_uid()","signature":"String.encrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.decrypt_uid()","signature":"String.decrypt_uid([key])","since":"","deprecated":false},{"type":"method","name":"String.toName()","signature":"String.toName()","since":"","deprecated":false},{"type":"method","name":"String.toUnicode()","signature":"String.toUnicode()","since":"","deprecated":false},{"type":"method","name":"String.fromUnicode()","signature":"String.fromUnicode()","since":"","deprecated":false},{"type":"method","name":"String.endsWith()","signature":"String.endsWith(text, [ignoreCase])","since":"","deprecated":false},{"type":"method","name":"String.replacer()","signature":"String.replacer(find, text)","since":"","deprecated":false},{"type":"method","name":"String.insert()","signature":"String.insert(index, value)","since":"","deprecated":false},{"type":"method","name":"String.indent()","signature":"String.indent(count, [char])","since":"","deprecated":false},{"type":"method","name":"String.pluralize()","signature":"String.pluralize(zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"String.env()","signature":"String.env()","since":"","deprecated":false},{"type":"method","name":"String.streamer()","signature":"String.streamer(beg, [end], callback, [skip])","since":"0.0.63","deprecated":false},{"type":"method","name":"Number.fixed()","signature":"Number.fixed(decimals)","since":"","deprecated":false},{"type":"method","name":"Number.currency()","signature":"Number.currency([currency], [a], [b], [c])","since":"","deprecated":false},{"type":"method","name":"Number.hex()","signature":"Number.hex([length])","since":"","deprecated":false},{"type":"method","name":"Number.parseDate()","signature":"Number.parseDate([plus])","since":"","deprecated":false},{"type":"method","name":"Number.toRad()","signature":"Number.toRad()","since":"","deprecated":false},{"type":"method","name":"Date.parseDate()","signature":"Date.parseDate()","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm0n1nr60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"FlowStream","summary":"The Flow module, FlowStream instances, component definitions, component instances and messages.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> The Flow module, FlowStream instances, component definitions, component instances and messages.\n\nFlowStreams are graphs of components loaded from `.flow` files in `/flowstreams/` or with `Flow.load()`. This page lists the `Flow` object, the FlowStream instance, the component definition (`exports`), the component instance and the message (`$`). The guide [FlowStream](../../guides/flowstream/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nThe directory with `.flow` files that are loaded when the app starts.\n\nEvery file with the `.flow` extension in this directory is read as JSON and passed to `Flow.load()` when the app starts. Files whose name contains `-bk` or `_bk` are skipped, so you can keep backups next to them. The directory `plugins/{name}/flowstreams/` of each plugin is loaded the same way.\n\nIn debug mode the watcher restarts the app when a `.flow` file changes. The default is `/flowstreams/`; an empty value turns the loading off.\n\nExample: Directory layout\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nThe JSON object stored in a `.flow` file and passed to `Flow.load()`.\n\n- `id` {String}: the identifier, the key in `Flow.instances`. A random one is generated when it is missing.\n- `name` {String}: a readable name (default: the `id`).\n- `components` {Object}: component id → the component as an HTML string with a `<script total>` block.\n- `design` {Object}: instance id → `{ component, config, connections, x, y }`. `connections` maps an output id to an array of `{ id: 'instanceid', index: 'inputid' }`.\n- `variables` {Object}: values that components read with `instance.replace()` or `$.variables()`.\n- `worker` {String/Boolean}: `'worker'` runs the FlowStream in a worker thread, another truthy value (for example `'fork'`) in a child process; `false` (default) in the main process.\n- `memory` {Number}: the heap limit in MB for a child process (`--max-old-space-size`).\n- `cloning` {Boolean}: clones the message data for every connection (default `true`).\n- `paused` {Boolean}: starts the FlowStream paused.\n- `readonly` {Boolean}: no `save` events are emitted.\n- `origin` {String}: the public URL of the app, used by `instance.href()` and the `{hostname}` variable.\n\n`flowstream.export()` returns the same shape, so you can write it back to the `.flow` file.\n\nExample: A minimal .flow file\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nLoads a FlowStream from its schema and starts it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The FlowStream schema (the content of a `.flow` file). |\n| `callback` | `Function` | no |  | `function(err, instance)`; `instance` is the FlowStream instance. |\n\nCreates the FlowStream, registers its components, creates the instances of the design and calls `callback` when everything is ready. The instance is stored in `Flow.instances[schema.id]` and the schema in `Flow.db[schema.id]`.\n\nWhen a FlowStream with the same `id` is already loaded, it is updated with the new schema instead (components, design and variables are replaced) and the callback gets the existing instance.\n\nA schema without `name`, `components`, `design`, `sources` or `variables` gets empty defaults, so an empty flow loads.\n\nExample: Load a flow from code\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nLoads all `.flow` files of a directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | An absolute path. |\n| `callback` | `Function` | no |  | Called when all files are loaded. |\n\nReads every `.flow` file of `directory` (default `flowstreams/` in the app root), skips names with `-bk` or `_bk` and loads each one with `Flow.load()`. A missing directory is not an error. The framework calls it for `/flowstreams/` at startup; call it yourself for another directory.\n\nExample: Another directory\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nThe loaded FlowStream instances by their `id`.\n\nReturns: `Object`\n\nAn object where each key is the `id` of a schema and each value is the FlowStream instance returned by `Flow.load()`. Use it to send data to a FlowStream from routes, schemas or jobs.\n\nExample: Send from a route\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nThe schemas of the loaded FlowStreams by their `id`.\n\nReturns: `Object`\n\nHolds the schema passed to `Flow.load()`; it is replaced by the exported schema each time the FlowStream saves itself (see `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nDestroys a FlowStream and removes it from `Flow.instances` and `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The FlowStream id. |\n\nStops all instances, closes a worker, removes the FlowStream and emits `remove` with its schema. The `.flow` file is not deleted.\n\nExample: Remove\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nUpdates a loaded FlowStream with a new schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The new schema; `id` selects the FlowStream. |\n\nReturns: `Boolean` `true` when the FlowStream exists.\n\nFinds the FlowStream by `schema.id`, stores the schema in `Flow.db` and rewrites the running FlowStream with it (components, design and variables). Returns `false` when no FlowStream with this `id` is loaded. `Flow.load()` calls it for an `id` that is already loaded.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nConnects a WebSocket controller to a FlowStream for the Flow designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The FlowStream id (or the FlowStream itself). |\n| `websocket` | `WebSocket` | yes |  | The WebSocket controller (`this` in a `SOCKET` route). |\n| `check` | `Function` | no |  | `function(client, next)`; call `next()` to let the client in. |\n\nThe designer talks to the FlowStream through this WebSocket: it reads components, the design and the stats, and sends changes back. `check(client, next)` runs for each new client; call `next()` to accept it. The socket is detached when the WebSocket controller is destroyed. An unknown `id` destroys the socket.\n\nExample: Designer endpoint\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nHandles errors of all FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | The error. |\n| `source` | `String` | yes |  | Where it happened, for example `instance_message` or `instance_make`. |\n| `id` | `String` | yes |  | The instance id. |\n| `componentid` | `String` | yes |  | The component id. |\n| `stack` | `String` | no |  | The stack, for FlowStreams in a worker. |\n\nThe default prints a block with the FlowStream name, the source, the instance id and the component id to the console. Assign your own function before the FlowStreams are loaded; `this` is the FlowStream instance (`this.id` is its id).\n\nExample: Log errors\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nA FlowStream was loaded and is ready.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | The FlowStream instance. |\n| `schema` | `Object` | yes |  | The schema. |\n\nEmitted after `Flow.load()` finished, before its callback.\n\nExample: Log\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nA FlowStream changed and its schema should be stored.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | The exported schema with `id`, `components`, `design`, `variables` and the other fields. |\n\nEmitted about five seconds after the last change: an edit in the designer, `flowstream.variables()`, `flowstream.reconfigure()` or `instance.save()`. The framework does not write `.flow` files itself; store the schema here. Nothing is emitted for a schema with `readonly: true`.\n\nExample: Write the .flow file\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nCreates or returns a FlowStream engine by name, without workers or the designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | The engine name. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` The engine.\n\nReturns the engine that runs components and messages. The same `name` returns the same engine (default name `default`). It has no `.flow` file, no worker and no saving; `Flow.load()` builds on it. Main methods:\n\n- `add(id, html, [callback])` registers a component from its HTML.\n- `use(design, [callback])` creates instances from a design object (returns a Promise without callback); `insert(design, [callback])` adds instances; `remove(keys, [callback])` removes them.\n- `trigger('instanceid__inputid', data)` sends data to an input; `send('instanceid__outputid', data)` sends data from an output.\n- `find(id)` returns an instance; `pause(is)`; `reconfigure(id, config)`; `destroy()`.\n- Events: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: A local engine\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nSends data to one instance and waits for the end of the message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The target instance. |\n| `data` | `Object` | yes |  | The message data. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` is an instance id, `@componentid` (the first instance of the component) or `#name` (the first instance whose component has this name). Add `/inputid` to set `$.input`. The data goes to `instance.message` of the target, so it must define `instance.message`.\n\nThe callback runs when the message and all its copies are destroyed. It gets `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, where `data` is the data of the last message. An unknown target calls `callback(404)`.\n\nExample: Wait for the result\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nSends a message to one or more instances with a repository, variables and a timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Options. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` has `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` is an instance id, `@componentid` (all instances of the component) or `#name` (all instances with the component name). Each target must define `instance.message`. The callback runs for each target when its message ends; an unknown target gives `404`.\n\n- `opt.data` {Object}: the data (default `{}`).\n- `opt.repo` {Object}: the initial `$.repo`.\n- `opt.vars` {Object}: the initial `$.vars`.\n- `opt.timeout` {Number}: ms; then the message ends with `error` `408`.\n- `opt.uid`, `opt.ref`: returned back in the response.\n\nExample: With a timeout\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nCalls the `instance.trigger` handler of instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The target. |\n| `data` | `Object` | no |  | Passed to `instance.trigger(data)`. |\n\nReturns: `FlowStreamInstance` The instance.\n\n`id` is an instance id, `@componentid` (all instances of the component) or `#name`. Only instances that define `instance.trigger` are called; nothing happens while the FlowStream is paused.\n\nExample: Run all timers\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nPauses or resumes the FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` pauses, `false` resumes. |\n\nReturns: `FlowStreamInstance` The instance.\n\nA paused FlowStream drops new messages and calls `instance.pause(is)` of each instance that defines it. Without an argument it toggles the state.\n\nExample: Pause\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nChanges the configuration of one instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The instance id. |\n| `config` | `Object` | yes |  | The keys to change. |\n\nReturns: `FlowStreamInstance` The instance.\n\nThe keys of `config` are merged into the instance configuration, then `instance.configure(config)` is called and the FlowStream saves itself.\n\nExample: Change a field\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nReplaces the variables of the FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | The new variables. |\n\nReturns: `FlowStreamInstance` The instance.\n\nCalls `instance.variables(variables)` and `instance.vary('variables')` of each instance that defines them and saves the FlowStream.\n\nExample: Set variables\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nReads the registered components.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` The instance.\n\nThe callback gets an array with `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` and `settings` of each component.\n\nExample: List names\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nRegisters or replaces a component at runtime.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The component id. |\n| `html` | `String` | yes |  | The component source. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` The instance.\n\n`html` is the component file with a `<script total>` block. Existing instances of the component are created again with the new code. Use `flowstream.rem(id, [callback])` to unregister a component and remove its instances.\n\nExample: Add a component\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nExports the current schema of the FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` The instance.\n\nThe callback gets the schema in the `.flow` format: `components` (raw HTML), `design`, `variables`, `sources`, `paused` and the other fields of the loaded schema.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nStatistics of the FlowStream.\n\nReturns: `Object`\n\nContains `messages` (messages sent), `pending` (messages in progress), `minutes` (minutes running), `mm` (messages in the last minute), `errors` (count of the last errors, at most 10), `memory` and `paused`. `memory` (heap in bytes) is measured only in a worker or child process. For a FlowStream in a worker the object comes from the worker about every 15 seconds and also contains `pid`; before the first report it is `undefined`.\n\nExample: Read stats\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nDestroys this FlowStream and removes it from `Flow`.\n\nThe same as `Flow.remove(flowstream.id)`. `flowstream.destroy()` only stops the FlowStream and its worker; it stays in `Flow.instances`.\n\nExample: Remove\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nCreates one instance of the component.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | The new instance. |\n| `config` | `Object` | yes |  | The instance configuration. |\n\nA component is an HTML file whose `<script total>` block is the server code; `exports` is the component. `make` runs for each instance of the design, with `this` and `instance` both the instance and `config` its configuration (`exports.config` merged with the design `config`). Assign handlers such as `instance.message` here.\n\nThe other blocks of the file are for the designer: `<readme>`, `<settings>`, `<style>`, `<script>` (client code), `<body>` and `<template>`.\n\nExample: A complete component\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nThe inputs and outputs of the component.\n\nReturns: `Array`\n\n`exports.inputs` and `exports.outputs` are arrays of `{ id, name }`. Connections in the design refer to these ids: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. A connection to an input that the target component does not declare is removed. A component without inputs only sends (for example a timer); one without outputs ends the messages.\n\nExample: Two outputs\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nThe default configuration of each instance.\n\nReturns: `Object`\n\nA copy is merged with the `config` of the instance in the design and passed to `exports.make()` as `config`.\n\nExample: Defaults\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nThe name and the other metadata of the component.\n\nReturns: `String`\n\nMetadata for the designer and for `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` and `exports.meta`. The `#name` selector of `send()`, `exec()` and `trigger()` matches `exports.name`. The component id is the key in the `components` object of the schema.\n\nExample: Metadata\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nNPM packages that the component needs.\n\nReturns: `Array`\n\nThe packages are installed with `NPMINSTALL()` before the component is registered.\n\nExample: Use a package\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nReceives the messages that arrive at the inputs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | The message. |\n\n`$` is the message; `$.input` is the id of the input. Instead of one handler you can define `instance.message_INPUTID` for one input. A message that no handler takes is destroyed. Each message must end: send it on with `$.send()` or call `$.destroy()`.\n\nExample: Two inputs\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nSends data from an output of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | The output id. |\n| `data` | `Object` | yes |  | The data or a message. |\n| `controller` | `Controller` | no |  | Makes `$.user`, `$.body` and the other request properties available. |\n\nReturns: `Number` Count of sent messages.\n\nCreates a new message for each connection of `output`. When `data` is a message, its copies keep the repository and the callbacks of that message. Returns the number of messages sent (`0` when the output has no connection or the FlowStream is paused).\n\nExample: A timer\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCreates a new message owned by this instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | The data. |\n\nReturns: `Message` The message.\n\nSend it with `$.send(output)`. Unlike `instance.send()`, you can add listeners and a repository before sending.\n\nExample: Wait for the end\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nShows a status of the instance in the designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | The status. |\n| `delay` | `Number` | no |  | Delay in ms. |\n\n`data` is any value that the component design (`<body>`, `<script>`) can render. With `delay` (ms) the status is sent once after this time, which avoids flooding the designer. Without arguments the last status is sent again.\n\nExample: Count messages\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nSends data to the dashboard of the designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Dashboard data. |\n\nLike `instance.status()`, but for dashboard widgets. The last value is kept and sent again when called without arguments.\n\nExample: Temperature\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nReports an error of the instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | The error. |\n\nThe error is stored in the last ten errors of the FlowStream (counted in `stats.errors`), shown in the designer and passed to `Flow.onerror`. `$.throw(err)` does the same and also sets `$.error`. Neither ends the message.\n\nExample: Invalid data\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nThe configuration of the instance.\n\nReturns: `Object`\n\nThe default `exports.config` merged with the `config` of the design. A change from the designer or `flowstream.reconfigure()` updates the same object and calls `instance.configure(config)`.\n\nExample: Read a value\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nRuns when the configuration of the instance changes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | The new configuration. |\n\nCalled after the designer, a new design or `flowstream.reconfigure()` changed `instance.config`. Not called for the first configuration; use `exports.make()` for that.\n\nExample: Restart a timer\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nRuns when the instance stops.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true` when the instance is removed, not only re-created. |\n\nCalled when the instance is removed from the design, its component is replaced or removed, or the FlowStream is unloaded. Clear timers and close connections here. Other optional handlers: `instance.init()` (once, after the design is created), `instance.refresh()` (after each design change), `instance.pause(is)` and `instance.variables(variables)`.\n\nExample: Clean up\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nRuns when the instance is triggered.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | The trigger data. |\n\nCalled by `flowstream.trigger()` and by the trigger button of the designer. Typically it starts a new message.\n\nExample: Start on demand\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nReplaces `{key}` placeholders with variables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | The text. |\n| `data` | `Object` | no |  | Additional values. |\n| `encoding` | `String/Function` | no |  | How to encode each value. |\n\nReturns: `String` The text with values.\n\nEach `{key}` (or `{{key}}`) is looked up in the FlowStream variables, then `variables2`, then the secrets, then `{hostname}`, then in `data` (nested keys such as `{user.name}` work). Unknown keys stay as they are. `encoding` is `'url'`, `'json'`, `'querify'` or `function(value, key)`. An object as `str` replaces all its string values.\n\nExample: A URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nSaves changes of the instance and redraws it in the designer.\n\nUse it after you change `instance.config` or other design properties in code. The FlowStream then emits `save`.\n\nExample: Remember a value\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nThe FlowStream engine that runs the instance.\n\nReturns: `FlowStream`\n\nUseful properties: `instance.main.variables` (the variables), `instance.main.paused`, `instance.main.stats` and `instance.main.id`. `instance.instances` holds all instances of the design and `instance.components` all registered components. `instance.id` is the instance id, `instance.component` the component id and `instance.module` the component.\n\nExample: Read a variable\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nThe data of the message.\n\nReturns: `Object`\n\nAny value. Each connection gets its own copy of objects and Buffers when cloning is on (the default). The request properties `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` and `$.files` exist only when the message was started with a controller.\n\nExample: Read and change\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nSends the message on from an output of the current instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | The output id. |\n| `data` | `Object` | no |  | New data. |\n| `clone` | `Boolean` | no | `cloning` | Clones the data for each connection. |\n\nReturns: `Number` Count of sent messages.\n\nWithout `output` it is sent from all outputs. Without `data` it keeps its data. When nothing is connected to the output, the message is destroyed. `clone` overrides the `cloning` option of the FlowStream for this call. Returns the number of sent messages.\n\nExample: Route by a condition\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nEnds the message.\n\nCall it in the last component of a chain. When the last copy of a message ends, `end` is emitted and the callback of `flowstream.send()` or `flowstream.exec()` runs. `$.end()` is an alias.\n\nExample: Last component\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nAn object shared by the message and all its copies.\n\nReturns: `Object`\n\nUse it to pass values along the whole chain without changing `$.data`. It is returned as `repo` to the callback of `flowstream.send()` and `flowstream.exec()`. `$.vars` is another shared object.\n\nExample: Keep a value\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nReplaces `{key}` placeholders with variables and message values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | The text. |\n| `data` | `Object` | no | `the message` | Values. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` or a function. |\n\nReturns: `String`\n\nThe same as `instance.replace()`, but without `data` the message itself is used, so `{data.id}` reads `$.data.id`. `$.replace()` is an alias.\n\nExample: Build a URL\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nListens to events of the message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` The message.\n\nEvents: `end` (the last copy ended), `destroy` (same moment), `terminate` (any copy ended), `message` (a copy reached an instance), `timeout`. The listeners are shared by all copies. `$.once()` and `$.off()` exist too.\n\nExample: Measure the chain\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nLimits how long each next step of the message may take.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Milliseconds. |\n\nReturns: `Message` The message.\n\nEvery copy sent after this call ends with `$.error = 408` when it is not processed within `time` ms; `callback` is called with that copy. `$.totaltimeout([callback], time)` limits the whole chain instead.\n\nExample: Five seconds for the whole chain\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0n1nr60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"FlowStream","summary":"Das Flow-Modul, FlowStream-Instanzen, Komponentendefinitionen, Komponenteninstanzen und Nachrichten.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Das Flow-Modul, FlowStream-Instanzen, Komponentendefinitionen, Komponenteninstanzen und Nachrichten.\n\nFlowStreams sind Graphen aus Komponenten, die aus `.flow`-Dateien in `/flowstreams/` oder mit `Flow.load()` geladen werden. Diese Seite listet das `Flow`-Objekt, die FlowStream-Instanz, die Komponentendefinition (`exports`), die Komponenteninstanz und die Nachricht (`$`) auf. Die Anleitung [FlowStream](../../guides/flowstream/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nDas Verzeichnis mit `.flow`-Dateien, die beim Start der App geladen werden.\n\nJede Datei mit der Endung `.flow` in diesem Verzeichnis wird als JSON gelesen und beim Start der App an `Flow.load()` übergeben. Dateien, deren Name `-bk` oder `_bk` enthält, werden übersprungen, sodass du Backups daneben aufbewahren kannst. Das Verzeichnis `plugins/{name}/flowstreams/` jedes Plugins wird auf die gleiche Weise geladen.\n\nIm Debug-Modus startet der Watcher die App neu, wenn sich eine `.flow`-Datei ändert. Der Standardwert ist `/flowstreams/`; ein leerer Wert schaltet das Laden ab.\n\nExample: Verzeichnisstruktur\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nDas JSON-Objekt, das in einer `.flow`-Datei gespeichert und an `Flow.load()` übergeben wird.\n\n- `id` {String}: der Bezeichner, der Schlüssel in `Flow.instances`. Fehlt er, wird ein zufälliger erzeugt.\n- `name` {String}: ein lesbarer Name (Standard: die `id`).\n- `components` {Object}: Komponenten-ID → die Komponente als HTML-String mit einem Block `<script total>`.\n- `design` {Object}: Instanz-ID → `{ component, config, connections, x, y }`. `connections` ordnet einer Ausgangs-ID ein Array aus `{ id: 'instanceid', index: 'inputid' }` zu.\n- `variables` {Object}: Werte, die Komponenten mit `instance.replace()` oder `$.variables()` lesen.\n- `worker` {String/Boolean}: `'worker'` führt den FlowStream in einem Worker-Thread aus, ein anderer truthy Wert (zum Beispiel `'fork'`) in einem Kindprozess; `false` (Standard) im Hauptprozess.\n- `memory` {Number}: das Heap-Limit in MB für einen Kindprozess (`--max-old-space-size`).\n- `cloning` {Boolean}: klont die Daten der Nachricht für jede Verbindung (Standard `true`).\n- `paused` {Boolean}: startet den FlowStream pausiert.\n- `readonly` {Boolean}: es werden keine `save`-Events ausgegeben.\n- `origin` {String}: die öffentliche URL der App, verwendet von `instance.href()` und der Variable `{hostname}`.\n\n`flowstream.export()` gibt dieselbe Form zurück, sodass du sie zurück in die `.flow`-Datei schreiben kannst.\n\nExample: Eine minimale .flow-Datei\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nLädt einen FlowStream aus seinem Schema und startet ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das FlowStream-Schema (der Inhalt einer `.flow`-Datei). |\n| `callback` | `Function` | no |  | `function(err, instance)`; `instance` ist die FlowStream-Instanz. |\n\nErstellt den FlowStream, registriert seine Komponenten, erstellt die Instanzen des Designs und ruft `callback` auf, wenn alles bereit ist. Die Instanz wird in `Flow.instances[schema.id]` gespeichert und das Schema in `Flow.db[schema.id]`.\n\nIst bereits ein FlowStream mit derselben `id` geladen, wird er stattdessen mit dem neuen Schema aktualisiert (Komponenten, Design und Variablen werden ersetzt), und der Callback erhält die bestehende Instanz.\n\nEin Schema ohne `name`, `components`, `design`, `sources` oder `variables` bekommt leere Standardwerte, sodass auch ein leerer Flow geladen wird.\n\nExample: Einen Flow aus dem Code laden\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nLädt alle `.flow`-Dateien eines Verzeichnisses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | Ein absoluter Pfad. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn alle Dateien geladen sind. |\n\nLiest jede `.flow`-Datei aus `directory` (Standard `flowstreams/` im Stammverzeichnis der App), überspringt Namen mit `-bk` oder `_bk` und lädt jede Datei mit `Flow.load()`. Ein fehlendes Verzeichnis ist kein Fehler. Das Framework ruft die Methode beim Start für `/flowstreams/` auf; für ein anderes Verzeichnis rufst du sie selbst auf.\n\nExample: Ein anderes Verzeichnis\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nDie geladenen FlowStream-Instanzen nach ihrer `id`.\n\nReturns: `Object`\n\nEin Objekt, in dem jeder Schlüssel die `id` eines Schemas und jeder Wert die von `Flow.load()` zurückgegebene FlowStream-Instanz ist. Verwende es, um aus Routen, Schemas oder Jobs Daten an einen FlowStream zu senden.\n\nExample: Aus einer Route senden\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nDie Schemas der geladenen FlowStreams nach ihrer `id`.\n\nReturns: `Object`\n\nEnthält das an `Flow.load()` übergebene Schema; es wird jedes Mal durch das exportierte Schema ersetzt, wenn sich der FlowStream speichert (siehe `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nZerstört einen FlowStream und entfernt ihn aus `Flow.instances` und `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die FlowStream-ID. |\n\nStoppt alle Instanzen, beendet einen Worker, entfernt den FlowStream und sendet `remove` mit seinem Schema. Die `.flow`-Datei wird nicht gelöscht.\n\nExample: Entfernen\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nAktualisiert einen geladenen FlowStream mit einem neuen Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das neue Schema; `id` wählt den FlowStream aus. |\n\nReturns: `Boolean` `true`, wenn der FlowStream existiert.\n\nSucht den FlowStream anhand von `schema.id`, speichert das Schema in `Flow.db` und schreibt den laufenden FlowStream damit neu (Komponenten, Design und Variablen). Gibt `false` zurück, wenn kein FlowStream mit dieser `id` geladen ist. `Flow.load()` ruft die Methode für eine bereits geladene `id` auf.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nVerbindet einen WebSocket-Controller mit einem FlowStream für den Flow-Designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die FlowStream-ID (oder der FlowStream selbst). |\n| `websocket` | `WebSocket` | yes |  | Der WebSocket-Controller (`this` in einer `SOCKET`-Route). |\n| `check` | `Function` | no |  | `function(client, next)`; rufe `next()` auf, um den Client hereinzulassen. |\n\nDer Designer kommuniziert über diesen WebSocket mit dem FlowStream: Er liest Komponenten, das Design und die Statistiken und sendet Änderungen zurück. `check(client, next)` läuft für jeden neuen Client; rufe `next()` auf, um ihn zu akzeptieren. Der Socket wird getrennt, wenn der WebSocket-Controller zerstört wird. Eine unbekannte `id` zerstört den Socket.\n\nExample: Endpunkt für den Designer\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nBehandelt Fehler aller FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | Der Fehler. |\n| `source` | `String` | yes |  | Wo er aufgetreten ist, zum Beispiel `instance_message` oder `instance_make`. |\n| `id` | `String` | yes |  | Die Instanz-ID. |\n| `componentid` | `String` | yes |  | Die Komponenten-ID. |\n| `stack` | `String` | no |  | Der Stack, für FlowStreams in einem Worker. |\n\nStandardmäßig wird ein Block mit dem FlowStream-Namen, der Quelle, der Instanz-ID und der Komponenten-ID in der Konsole ausgegeben. Weise deine eigene Funktion zu, bevor die FlowStreams geladen werden; `this` ist die FlowStream-Instanz (`this.id` ist ihre ID).\n\nExample: Fehler protokollieren\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nEin FlowStream wurde geladen und ist bereit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Die FlowStream-Instanz. |\n| `schema` | `Object` | yes |  | Das Schema. |\n\nWird gesendet, nachdem `Flow.load()` fertig ist, vor dessen Callback.\n\nExample: Protokollieren\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nEin FlowStream hat sich geändert, und sein Schema sollte gespeichert werden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Das exportierte Schema mit `id`, `components`, `design`, `variables` und den anderen Feldern. |\n\nWird etwa fünf Sekunden nach der letzten Änderung gesendet: eine Bearbeitung im Designer, `flowstream.variables()`, `flowstream.reconfigure()` oder `instance.save()`. Das Framework schreibt `.flow`-Dateien nicht selbst; speichere das Schema hier. Für ein Schema mit `readonly: true` wird nichts gesendet.\n\nExample: Die .flow-Datei schreiben\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nErstellt eine FlowStream-Engine nach Namen oder gibt sie zurück, ohne Worker oder Designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Der Name der Engine. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` Die Engine.\n\nGibt die Engine zurück, die Komponenten und Nachrichten ausführt. Derselbe `name` gibt dieselbe Engine zurück (Standardname `default`). Sie hat keine `.flow`-Datei, keinen Worker und kein Speichern; `Flow.load()` baut auf ihr auf. Die wichtigsten Methoden:\n\n- `add(id, html, [callback])` registriert eine Komponente aus ihrem HTML.\n- `use(design, [callback])` erstellt Instanzen aus einem Design-Objekt (gibt ohne Callback eine Promise zurück); `insert(design, [callback])` fügt Instanzen hinzu; `remove(keys, [callback])` entfernt sie.\n- `trigger('instanceid__inputid', data)` sendet Daten an einen Eingang; `send('instanceid__outputid', data)` sendet Daten von einem Ausgang.\n- `find(id)` gibt eine Instanz zurück; `pause(is)`; `reconfigure(id, config)`; `destroy()`.\n- Events: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: Eine lokale Engine\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nSendet Daten an eine Instanz und wartet auf das Ende der Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Die Zielinstanz. |\n| `data` | `Object` | yes |  | Die Nachrichtendaten. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` ist eine Instanz-ID, `@componentid` (die erste Instanz der Komponente) oder `#name` (die erste Instanz, deren Komponente diesen Namen hat). Hänge `/inputid` an, um `$.input` zu setzen. Die Daten gehen an `instance.message` des Ziels, daher muss es `instance.message` definieren.\n\nDer Callback läuft, wenn die Nachricht und alle ihre Kopien zerstört sind. Er erhält `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, wobei `data` die Daten der letzten Nachricht sind. Ein unbekanntes Ziel ruft `callback(404)` auf.\n\nExample: Auf das Ergebnis warten\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nSendet eine Nachricht an eine oder mehrere Instanzen, mit einem Repository, Variablen und einem Timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Optionen. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` hat `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` ist eine Instanz-ID, `@componentid` (alle Instanzen der Komponente) oder `#name` (alle Instanzen mit dem Komponentennamen). Jedes Ziel muss `instance.message` definieren. Der Callback läuft für jedes Ziel, wenn dessen Nachricht endet; ein unbekanntes Ziel ergibt `404`.\n\n- `opt.data` {Object}: die Daten (Standard `{}`).\n- `opt.repo` {Object}: das anfängliche `$.repo`.\n- `opt.vars` {Object}: das anfängliche `$.vars`.\n- `opt.timeout` {Number}: ms; danach endet die Nachricht mit `error` `408`.\n- `opt.uid`, `opt.ref`: werden in der Antwort zurückgegeben.\n\nExample: Mit einem Timeout\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nRuft den Handler `instance.trigger` von Instanzen auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Das Ziel. |\n| `data` | `Object` | no |  | Wird an `instance.trigger(data)` übergeben. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\n`id` ist eine Instanz-ID, `@componentid` (alle Instanzen der Komponente) oder `#name`. Nur Instanzen, die `instance.trigger` definieren, werden aufgerufen; solange der FlowStream pausiert ist, passiert nichts.\n\nExample: Alle Timer ausführen\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nPausiert den FlowStream oder setzt ihn fort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` pausiert, `false` setzt fort. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\nEin pausierter FlowStream verwirft neue Nachrichten und ruft `instance.pause(is)` jeder Instanz auf, die es definiert. Ohne Argument wird der Zustand umgeschaltet.\n\nExample: Pausieren\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nÄndert die Konfiguration einer Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die Instanz-ID. |\n| `config` | `Object` | yes |  | Die zu ändernden Schlüssel. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\nDie Schlüssel von `config` werden in die Konfiguration der Instanz übernommen, dann wird `instance.configure(config)` aufgerufen, und der FlowStream speichert sich.\n\nExample: Ein Feld ändern\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nErsetzt die Variablen des FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | Die neuen Variablen. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\nRuft `instance.variables(variables)` und `instance.vary('variables')` jeder Instanz auf, die sie definiert, und speichert den FlowStream.\n\nExample: Variablen setzen\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nLiest die registrierten Komponenten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\nDer Callback erhält ein Array mit `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` und `settings` jeder Komponente.\n\nExample: Namen auflisten\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nRegistriert oder ersetzt eine Komponente zur Laufzeit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die Komponenten-ID. |\n| `html` | `String` | yes |  | Der Quellcode der Komponente. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\n`html` ist die Komponentendatei mit einem `<script total>`-Block. Bestehende Instanzen der Komponente werden mit dem neuen Code neu erstellt. Verwende `flowstream.rem(id, [callback])`, um eine Komponente abzumelden und ihre Instanzen zu entfernen.\n\nExample: Eine Komponente hinzufügen\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nExportiert das aktuelle Schema des FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` Die Instanz.\n\nDer Callback erhält das Schema im `.flow`-Format: `components` (rohes HTML), `design`, `variables`, `sources`, `paused` und die anderen Felder des geladenen Schemas.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nStatistiken des FlowStream.\n\nReturns: `Object`\n\nEnthält `messages` (gesendete Nachrichten), `pending` (Nachrichten in Bearbeitung), `minutes` (Laufzeit in Minuten), `mm` (Nachrichten in der letzten Minute), `errors` (Anzahl der letzten Fehler, höchstens 10), `memory` und `paused`. `memory` (Heap in Bytes) wird nur in einem Worker oder Kindprozess gemessen. Bei einem FlowStream in einem Worker kommt das Objekt etwa alle 15 Sekunden vom Worker und enthält außerdem `pid`; vor dem ersten Bericht ist es `undefined`.\n\nExample: Statistiken lesen\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nZerstört diesen FlowStream und entfernt ihn aus `Flow`.\n\nDasselbe wie `Flow.remove(flowstream.id)`. `flowstream.destroy()` stoppt nur den FlowStream und seinen Worker; er bleibt in `Flow.instances`.\n\nExample: Entfernen\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nErstellt eine Instanz der Komponente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Die neue Instanz. |\n| `config` | `Object` | yes |  | Die Konfiguration der Instanz. |\n\nEine Komponente ist eine HTML-Datei, deren `<script total>`-Block der Servercode ist; `exports` ist die Komponente. `make` läuft für jede Instanz des Designs, wobei `this` und `instance` beide die Instanz sind und `config` ihre Konfiguration (`exports.config` zusammengeführt mit der `config` des Designs). Weise hier Handler wie `instance.message` zu.\n\nDie anderen Blöcke der Datei sind für den Designer: `<readme>`, `<settings>`, `<style>`, `<script>` (Client-Code), `<body>` und `<template>`.\n\nExample: Eine vollständige Komponente\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nDie Eingänge und Ausgänge der Komponente.\n\nReturns: `Array`\n\n`exports.inputs` und `exports.outputs` sind Arrays aus `{ id, name }`. Verbindungen im Design verweisen auf diese IDs: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. Eine Verbindung zu einem Eingang, den die Zielkomponente nicht deklariert, wird entfernt. Eine Komponente ohne Eingänge sendet nur (zum Beispiel ein Timer); eine ohne Ausgänge beendet die Nachrichten.\n\nExample: Zwei Ausgänge\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nDie Standardkonfiguration jeder Instanz.\n\nReturns: `Object`\n\nEine Kopie wird mit der `config` der Instanz im Design zusammengeführt und als `config` an `exports.make()` übergeben.\n\nExample: Standardwerte\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nDer Name und die anderen Metadaten der Komponente.\n\nReturns: `String`\n\nMetadaten für den Designer und für `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` und `exports.meta`. Der Selektor `#name` von `send()`, `exec()` und `trigger()` vergleicht mit `exports.name`. Die Komponenten-ID ist der Schlüssel im Objekt `components` des Schemas.\n\nExample: Metadaten\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nNPM-Pakete, die die Komponente benötigt.\n\nReturns: `Array`\n\nDie Pakete werden mit `NPMINSTALL()` installiert, bevor die Komponente registriert wird.\n\nExample: Ein Paket verwenden\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nEmpfängt die Nachrichten, die an den Eingängen ankommen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Die Nachricht. |\n\n`$` ist die Nachricht; `$.input` ist die ID des Eingangs. Statt eines einzigen Handlers kannst du `instance.message_INPUTID` für einen einzelnen Eingang definieren. Eine Nachricht, die kein Handler annimmt, wird zerstört. Jede Nachricht muss enden: Sende sie mit `$.send()` weiter oder rufe `$.destroy()` auf.\n\nExample: Zwei Eingänge\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nSendet Daten von einem Ausgang der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Die Ausgangs-ID. |\n| `data` | `Object` | yes |  | Die Daten oder eine Nachricht. |\n| `controller` | `Controller` | no |  | Macht `$.user`, `$.body` und die anderen Eigenschaften der Anfrage verfügbar. |\n\nReturns: `Number` Anzahl der gesendeten Nachrichten.\n\nErstellt für jede Verbindung von `output` eine neue Nachricht. Wenn `data` eine Nachricht ist, behalten ihre Kopien das Repository und die Callbacks dieser Nachricht. Gibt die Anzahl der gesendeten Nachrichten zurück (`0`, wenn der Ausgang keine Verbindung hat oder der FlowStream pausiert ist).\n\nExample: Ein Timer\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nErstellt eine neue Nachricht, die dieser Instanz gehört.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Die Daten. |\n\nReturns: `Message` Die Nachricht.\n\nSende sie mit `$.send(output)`. Anders als bei `instance.send()` kannst du vor dem Senden Listener und ein Repository hinzufügen.\n\nExample: Auf das Ende warten\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nZeigt einen Status der Instanz im Designer an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | Der Status. |\n| `delay` | `Number` | no |  | Verzögerung in ms. |\n\n`data` ist ein beliebiger Wert, den das Design der Komponente (`<body>`, `<script>`) darstellen kann. Mit `delay` (ms) wird der Status einmal nach dieser Zeit gesendet, was eine Überflutung des Designers vermeidet. Ohne Argumente wird der letzte Status erneut gesendet.\n\nExample: Nachrichten zählen\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nSendet Daten an das Dashboard des Designers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Dashboard-Daten. |\n\nWie `instance.status()`, aber für Dashboard-Widgets. Der letzte Wert wird behalten und erneut gesendet, wenn die Methode ohne Argumente aufgerufen wird.\n\nExample: Temperatur\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nMeldet einen Fehler der Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | Der Fehler. |\n\nDer Fehler wird unter den letzten zehn Fehlern des FlowStreams gespeichert (gezählt in `stats.errors`), im Designer angezeigt und an `Flow.onerror` übergeben. `$.throw(err)` macht dasselbe und setzt zusätzlich `$.error`. Keines von beiden beendet die Nachricht.\n\nExample: Ungültige Daten\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nDie Konfiguration der Instanz.\n\nReturns: `Object`\n\nDie Standard-`exports.config`, zusammengeführt mit der `config` des Designs. Eine Änderung aus dem Designer oder über `flowstream.reconfigure()` aktualisiert dasselbe Objekt und ruft `instance.configure(config)` auf.\n\nExample: Einen Wert lesen\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nLäuft, wenn sich die Konfiguration der Instanz ändert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Die neue Konfiguration. |\n\nWird aufgerufen, nachdem der Designer, ein neues Design oder `flowstream.reconfigure()` `instance.config` geändert hat. Wird für die erste Konfiguration nicht aufgerufen; verwende dafür `exports.make()`.\n\nExample: Einen Timer neu starten\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nLäuft, wenn die Instanz stoppt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true`, wenn die Instanz entfernt und nicht nur neu erstellt wird. |\n\nWird aufgerufen, wenn die Instanz aus dem Design entfernt wird, ihre Komponente ersetzt oder entfernt wird oder der FlowStream entladen wird. Räume hier Timer auf und schließe Verbindungen. Weitere optionale Handler: `instance.init()` (einmal, nachdem das Design erstellt wurde), `instance.refresh()` (nach jeder Änderung des Designs), `instance.pause(is)` und `instance.variables(variables)`.\n\nExample: Aufräumen\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nLäuft, wenn die Instanz ausgelöst wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Die Trigger-Daten. |\n\nWird von `flowstream.trigger()` und von der Trigger-Schaltfläche des Designers aufgerufen. Typischerweise startet sie eine neue Nachricht.\n\nExample: Bei Bedarf starten\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nErsetzt `{key}`-Platzhalter durch Variablen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Der Text. |\n| `data` | `Object` | no |  | Zusätzliche Werte. |\n| `encoding` | `String/Function` | no |  | Wie jeder Wert kodiert wird. |\n\nReturns: `String` Der Text mit den Werten.\n\nJeder `{key}` (oder `{{key}}`) wird zuerst in den Variablen des FlowStreams gesucht, dann in `variables2`, dann in den Secrets, dann in `{hostname}` und dann in `data` (verschachtelte Schlüssel wie `{user.name}` funktionieren). Unbekannte Schlüssel bleiben unverändert. `encoding` ist `'url'`, `'json'`, `'querify'` oder `function(value, key)`. Ein Objekt als `str` ersetzt alle seine String-Werte.\n\nExample: Eine URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nSpeichert Änderungen der Instanz und zeichnet sie im Designer neu.\n\nVerwende die Methode, nachdem du `instance.config` oder andere Eigenschaften des Designs im Code geändert hast. Der FlowStream sendet dann `save`.\n\nExample: Einen Wert merken\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nDie FlowStream-Engine, die die Instanz ausführt.\n\nReturns: `FlowStream`\n\nNützliche Eigenschaften: `instance.main.variables` (die Variablen), `instance.main.paused`, `instance.main.stats` und `instance.main.id`. `instance.instances` enthält alle Instanzen des Designs und `instance.components` alle registrierten Komponenten. `instance.id` ist die Instanz-ID, `instance.component` die Komponenten-ID und `instance.module` die Komponente.\n\nExample: Eine Variable lesen\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nDie Daten der Nachricht.\n\nReturns: `Object`\n\nEin beliebiger Wert. Jede Verbindung bekommt ihre eigene Kopie von Objekten und Buffern, wenn das Klonen eingeschaltet ist (der Standard). Die Request-Eigenschaften `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` und `$.files` gibt es nur, wenn die Nachricht mit einem Controller gestartet wurde.\n\nExample: Lesen und ändern\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nSendet die Nachricht von einem Ausgang der aktuellen Instanz weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | Die Ausgangs-ID. |\n| `data` | `Object` | no |  | Neue Daten. |\n| `clone` | `Boolean` | no | `cloning` | Klont die Daten für jede Verbindung. |\n\nReturns: `Number` Anzahl der gesendeten Nachrichten.\n\nOhne `output` wird sie von allen Ausgängen gesendet. Ohne `data` behält sie ihre Daten. Wenn nichts mit dem Ausgang verbunden ist, wird die Nachricht zerstört. `clone` überschreibt für diesen Aufruf die Option `cloning` des FlowStreams. Gibt die Anzahl der gesendeten Nachrichten zurück.\n\nExample: Nach einer Bedingung weiterleiten\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nBeendet die Nachricht.\n\nRufe sie in der letzten Komponente einer Kette auf. Wenn die letzte Kopie einer Nachricht endet, wird `end` gesendet, und der Callback von `flowstream.send()` oder `flowstream.exec()` läuft. `$.end()` ist ein Alias.\n\nExample: Letzte Komponente\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nEin Objekt, das die Nachricht und alle ihre Kopien teilen.\n\nReturns: `Object`\n\nVerwende es, um Werte entlang der gesamten Kette weiterzugeben, ohne `$.data` zu ändern. Es wird als `repo` an den Callback von `flowstream.send()` und `flowstream.exec()` zurückgegeben. `$.vars` ist ein weiteres geteiltes Objekt.\n\nExample: Einen Wert behalten\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nErsetzt `{key}`-Platzhalter durch Variablen und Werte der Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Der Text. |\n| `data` | `Object` | no | `the message` | Werte. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` oder eine Funktion. |\n\nReturns: `String`\n\nDasselbe wie `instance.replace()`, aber ohne `data` wird die Nachricht selbst verwendet, sodass `{data.id}` den Wert `$.data.id` liest. `$.replace()` ist ein Alias.\n\nExample: Eine URL zusammenbauen\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nHört auf Events der Nachricht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Das Event. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` Die Nachricht.\n\nEvents: `end` (die letzte Kopie ist beendet), `destroy` (gleicher Zeitpunkt), `terminate` (eine beliebige Kopie ist beendet), `message` (eine Kopie hat eine Instanz erreicht), `timeout`. Die Listener werden von allen Kopien geteilt. `$.once()` und `$.off()` gibt es ebenfalls.\n\nExample: Die Kette messen\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nBegrenzt, wie lange jeder nächste Schritt der Nachricht dauern darf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Millisekunden. |\n\nReturns: `Message` Die Nachricht.\n\nJede nach diesem Aufruf gesendete Kopie endet mit `$.error = 408`, wenn sie nicht innerhalb von `time` ms verarbeitet wird; `callback` wird mit dieser Kopie aufgerufen. `$.totaltimeout([callback], time)` begrenzt stattdessen die gesamte Kette.\n\nExample: Fünf Sekunden für die gesamte Kette\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0n1nr60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"FlowStream","summary":"El módulo Flow, las instancias de FlowStream, las definiciones de componentes, las instancias de componentes y los mensajes.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> El módulo Flow, las instancias de FlowStream, las definiciones de componentes, las instancias de componentes y los mensajes.\n\nLos FlowStreams son grafos de componentes que se cargan desde archivos `.flow` en `/flowstreams/` o con `Flow.load()`. Esta página enumera el objeto `Flow`, la instancia de FlowStream, la definición del componente (`exports`), la instancia del componente y el mensaje (`$`). La guía [FlowStream](../../guides/flowstream/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nEl directorio con los archivos `.flow` que se cargan cuando la app se inicia.\n\nCada archivo con la extensión `.flow` de este directorio se lee como JSON y se pasa a `Flow.load()` cuando la app se inicia. Los archivos cuyo nombre contiene `-bk` o `_bk` se omiten, así que puedes guardar copias de seguridad junto a ellos. El directorio `plugins/{name}/flowstreams/` de cada plugin se carga de la misma forma.\n\nEn modo debug, el watcher reinicia la app cuando cambia un archivo `.flow`. El valor por defecto es `/flowstreams/`; un valor vacío desactiva la carga.\n\nExample: Estructura del directorio\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nEl objeto JSON que se guarda en un archivo `.flow` y se pasa a `Flow.load()`.\n\n- `id` {String}: el identificador, la clave en `Flow.instances`. Si falta, se genera uno aleatorio.\n- `name` {String}: un nombre legible (por defecto: el `id`).\n- `components` {Object}: id de componente → el componente como string HTML con un bloque `<script total>`.\n- `design` {Object}: id de instancia → `{ component, config, connections, x, y }`. `connections` asocia un id de salida con un array de `{ id: 'instanceid', index: 'inputid' }`.\n- `variables` {Object}: valores que los componentes leen con `instance.replace()` o `$.variables()`.\n- `worker` {String/Boolean}: `'worker'` ejecuta el FlowStream en un hilo worker, otro valor verdadero (por ejemplo `'fork'`) en un proceso hijo; `false` (por defecto) en el proceso principal.\n- `memory` {Number}: el límite del heap en MB para un proceso hijo (`--max-old-space-size`).\n- `cloning` {Boolean}: clona los datos del mensaje para cada conexión (por defecto `true`).\n- `paused` {Boolean}: inicia el FlowStream en pausa.\n- `readonly` {Boolean}: no se emiten eventos `save`.\n- `origin` {String}: la URL pública de la aplicación, usada por `instance.href()` y la variable `{hostname}`.\n\n`flowstream.export()` devuelve la misma forma, así que puedes volver a escribirla en el archivo `.flow`.\n\nExample: Un archivo .flow mínimo\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nCarga un FlowStream a partir de su esquema y lo inicia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El esquema del FlowStream (el contenido de un archivo `.flow`). |\n| `callback` | `Function` | no |  | `function(err, instance)`; `instance` es la instancia del FlowStream. |\n\nCrea el FlowStream, registra sus componentes, crea las instancias del diseño y llama a `callback` cuando todo está listo. La instancia se guarda en `Flow.instances[schema.id]` y el esquema en `Flow.db[schema.id]`.\n\nCuando ya hay cargado un FlowStream con el mismo `id`, en su lugar se actualiza con el nuevo esquema (se reemplazan los componentes, el diseño y las variables) y el callback recibe la instancia existente.\n\nUn esquema sin `name`, `components`, `design`, `sources` ni `variables` recibe valores vacíos por defecto, así que un flow vacío se carga.\n\nExample: Cargar un flow desde el código\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nCarga todos los archivos `.flow` de un directorio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | Una ruta absoluta. |\n| `callback` | `Function` | no |  | Se llama cuando todos los archivos están cargados. |\n\nLee cada archivo `.flow` de `directory` (por defecto `flowstreams/` en la raíz de la app), omite los nombres con `-bk` o `_bk` y carga cada uno con `Flow.load()`. Que falte el directorio no es un error. El framework la llama para `/flowstreams/` al iniciarse; llámala tú mismo para otro directorio.\n\nExample: Otro directorio\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nLas instancias de FlowStream cargadas, por su `id`.\n\nReturns: `Object`\n\nUn objeto en el que cada clave es el `id` de un esquema y cada valor es la instancia de FlowStream devuelta por `Flow.load()`. Úsalo para enviar datos a un FlowStream desde rutas, esquemas o jobs.\n\nExample: Enviar desde una ruta\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nLos esquemas de los FlowStreams cargados, por su `id`.\n\nReturns: `Object`\n\nContiene el esquema pasado a `Flow.load()`; se sustituye por el esquema exportado cada vez que el FlowStream se guarda a sí mismo (consulta `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nDestruye un FlowStream y lo elimina de `Flow.instances` y `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del FlowStream. |\n\nDetiene todas las instancias, cierra el worker si lo hay, elimina el FlowStream y emite `remove` con su esquema. El archivo `.flow` no se borra.\n\nExample: Eliminar\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nActualiza un FlowStream cargado con un nuevo esquema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El nuevo esquema; `id` selecciona el FlowStream. |\n\nReturns: `Boolean` `true` cuando el FlowStream existe.\n\nBusca el FlowStream por `schema.id`, guarda el esquema en `Flow.db` y reescribe con él el FlowStream en ejecución (componentes, diseño y variables). Devuelve `false` cuando no hay cargado ningún FlowStream con este `id`. `Flow.load()` la llama para un `id` que ya está cargado.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nConecta un controlador WebSocket a un FlowStream para el diseñador de Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del FlowStream (o el propio FlowStream). |\n| `websocket` | `WebSocket` | yes |  | El controlador WebSocket (`this` en una ruta `SOCKET`). |\n| `check` | `Function` | no |  | `function(client, next)`; llama a `next()` para dejar entrar al cliente. |\n\nEl diseñador se comunica con el FlowStream a través de este WebSocket: lee los componentes, el diseño y las estadísticas, y devuelve los cambios. `check(client, next)` se ejecuta para cada cliente nuevo; llama a `next()` para aceptarlo. El socket se desconecta cuando se destruye el controlador WebSocket. Un `id` desconocido destruye el socket.\n\nExample: Endpoint del diseñador\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nGestiona los errores de todos los FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | El error. |\n| `source` | `String` | yes |  | Dónde ocurrió, por ejemplo `instance_message` o `instance_make`. |\n| `id` | `String` | yes |  | El id de la instancia. |\n| `componentid` | `String` | yes |  | El id del componente. |\n| `stack` | `String` | no |  | La pila (stack), para FlowStreams en un worker. |\n\nLa función por defecto imprime en la consola un bloque con el nombre del FlowStream, el origen, el id de la instancia y el id del componente. Asigna tu propia función antes de que se carguen los FlowStreams; `this` es la instancia de FlowStream (`this.id` es su id).\n\nExample: Registrar errores\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nUn FlowStream se ha cargado y está listo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | La instancia de FlowStream. |\n| `schema` | `Object` | yes |  | El esquema. |\n\nSe emite después de que `Flow.load()` termine, antes de su callback.\n\nExample: Registrar\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nUn FlowStream ha cambiado y su esquema debe guardarse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | El esquema exportado con `id`, `components`, `design`, `variables` y los demás campos. |\n\nSe emite unos cinco segundos después del último cambio: una edición en el diseñador, `flowstream.variables()`, `flowstream.reconfigure()` o `instance.save()`. El framework no escribe los archivos `.flow` por sí mismo; guarda aquí el esquema. No se emite nada para un esquema con `readonly: true`.\n\nExample: Escribir el archivo .flow\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nCrea o devuelve un motor FlowStream por nombre, sin workers ni diseñador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | El nombre del motor. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` El motor.\n\nDevuelve el motor que ejecuta componentes y mensajes. El mismo `name` devuelve el mismo motor (nombre por defecto `default`). No tiene archivo `.flow`, ni worker, ni guardado; `Flow.load()` se construye sobre él. Métodos principales:\n\n- `add(id, html, [callback])` registra un componente a partir de su HTML.\n- `use(design, [callback])` crea instancias a partir de un objeto de diseño (devuelve una Promise sin callback); `insert(design, [callback])` añade instancias; `remove(keys, [callback])` las elimina.\n- `trigger('instanceid__inputid', data)` envía datos a una entrada; `send('instanceid__outputid', data)` envía datos desde una salida.\n- `find(id)` devuelve una instancia; `pause(is)`; `reconfigure(id, config)`; `destroy()`.\n- Eventos: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: Un motor local\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nEnvía datos a una instancia y espera al final del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La instancia de destino. |\n| `data` | `Object` | yes |  | Los datos del mensaje. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` es un id de instancia, `@componentid` (la primera instancia del componente) o `#name` (la primera instancia cuyo componente tiene este nombre). Añade `/inputid` para establecer `$.input`. Los datos van a `instance.message` del destino, así que este debe definir `instance.message`.\n\nEl callback se ejecuta cuando el mensaje y todas sus copias se han destruido. Recibe `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, donde `data` son los datos del último mensaje. Un destino desconocido llama a `callback(404)`.\n\nExample: Esperar el resultado\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nEnvía un mensaje a una o más instancias con un repositorio, variables y un timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Opciones. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` tiene `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` es un id de instancia, `@componentid` (todas las instancias del componente) o `#name` (todas las instancias con el nombre del componente). Cada destino debe definir `instance.message`. El callback se ejecuta para cada destino cuando su mensaje termina; un destino desconocido da `404`.\n\n- `opt.data` {Object}: los datos (por defecto `{}`).\n- `opt.repo` {Object}: el `$.repo` inicial.\n- `opt.vars` {Object}: el `$.vars` inicial.\n- `opt.timeout` {Number}: ms; después, el mensaje termina con `error` `408`.\n- `opt.uid`, `opt.ref`: se devuelven en la respuesta.\n\nExample: Con un timeout\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nLlama al handler `instance.trigger` de las instancias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El destino. |\n| `data` | `Object` | no |  | Se pasa a `instance.trigger(data)`. |\n\nReturns: `FlowStreamInstance` La instancia.\n\n`id` es un id de instancia, `@componentid` (todas las instancias del componente) o `#name`. Solo se llama a las instancias que definen `instance.trigger`; no ocurre nada mientras el FlowStream está en pausa.\n\nExample: Ejecutar todos los temporizadores\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nPausa o reanuda el FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` pausa, `false` reanuda. |\n\nReturns: `FlowStreamInstance` La instancia.\n\nUn FlowStream en pausa descarta los mensajes nuevos y llama a `instance.pause(is)` de cada instancia que lo define. Sin argumento, alterna el estado.\n\nExample: Pausar\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nCambia la configuración de una instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id de la instancia. |\n| `config` | `Object` | yes |  | Las claves que se cambian. |\n\nReturns: `FlowStreamInstance` La instancia.\n\nLas claves de `config` se combinan con la configuración de la instancia; después se llama a `instance.configure(config)` y el FlowStream se guarda a sí mismo.\n\nExample: Cambiar un campo\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nSustituye las variables del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | Las nuevas variables. |\n\nReturns: `FlowStreamInstance` La instancia.\n\nLlama a `instance.variables(variables)` y a `instance.vary('variables')` de cada instancia que los define y guarda el FlowStream.\n\nExample: Establecer variables\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nLee los componentes registrados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` La instancia.\n\nEl callback recibe un array con `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` y `settings` de cada componente.\n\nExample: Listar nombres\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nRegistra o sustituye un componente en tiempo de ejecución.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del componente. |\n| `html` | `String` | yes |  | El código fuente del componente. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` La instancia.\n\n`html` es el archivo del componente con un bloque `<script total>`. Las instancias existentes del componente se vuelven a crear con el nuevo código. Usa `flowstream.rem(id, [callback])` para dar de baja un componente y eliminar sus instancias.\n\nExample: Añadir un componente\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nExporta el esquema actual del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` La instancia.\n\nEl callback recibe el esquema en el formato `.flow`: `components` (HTML sin procesar), `design`, `variables`, `sources`, `paused` y los demás campos del esquema cargado.\n\nExample: Copia de seguridad\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nEstadísticas del FlowStream.\n\nReturns: `Object`\n\nContiene `messages` (mensajes enviados), `pending` (mensajes en curso), `minutes` (minutos en ejecución), `mm` (mensajes en el último minuto), `errors` (número de los últimos errores, como máximo 10), `memory` y `paused`. `memory` (heap en bytes) solo se mide en un worker o en un proceso hijo. En un FlowStream dentro de un worker, el objeto llega desde el worker aproximadamente cada 15 segundos y además contiene `pid`; antes del primer informe es `undefined`.\n\nExample: Leer las estadísticas\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nDestruye este FlowStream y lo elimina de `Flow`.\n\nLo mismo que `Flow.remove(flowstream.id)`. `flowstream.destroy()` solo detiene el FlowStream y su worker; sigue en `Flow.instances`.\n\nExample: Eliminar\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nCrea una instancia del componente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | La nueva instancia. |\n| `config` | `Object` | yes |  | La configuración de la instancia. |\n\nUn componente es un archivo HTML cuyo bloque `<script total>` es el código del servidor; `exports` es el componente. `make` se ejecuta para cada instancia del diseño, con `this` e `instance` como la instancia y `config` como su configuración (`exports.config` combinado con la `config` del diseño). Asigna aquí handlers como `instance.message`.\n\nLos demás bloques del archivo son para el diseñador: `<readme>`, `<settings>`, `<style>`, `<script>` (código del cliente), `<body>` y `<template>`.\n\nExample: Un componente completo\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nLas entradas y salidas del componente.\n\nReturns: `Array`\n\n`exports.inputs` y `exports.outputs` son arrays de `{ id, name }`. Las conexiones del diseño hacen referencia a estos ids: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. Una conexión a una entrada que el componente de destino no declara se elimina. Un componente sin entradas solo envía (por ejemplo, un temporizador); uno sin salidas termina los mensajes.\n\nExample: Dos salidas\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nLa configuración por defecto de cada instancia.\n\nReturns: `Object`\n\nUna copia se combina con la `config` de la instancia en el diseño y se pasa a `exports.make()` como `config`.\n\nExample: Valores por defecto\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nEl nombre y los demás metadatos del componente.\n\nReturns: `String`\n\nMetadatos para el diseñador y para `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` y `exports.meta`. El selector `#name` de `send()`, `exec()` y `trigger()` coincide con `exports.name`. El id del componente es la clave en el objeto `components` del esquema.\n\nExample: Metadatos\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nPaquetes NPM que necesita el componente.\n\nReturns: `Array`\n\nLos paquetes se instalan con `NPMINSTALL()` antes de registrar el componente.\n\nExample: Usar un paquete\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nRecibe los mensajes que llegan a las entradas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | El mensaje. |\n\n`$` es el mensaje; `$.input` es el id de la entrada. En lugar de un único handler puedes definir `instance.message_INPUTID` para una sola entrada. Un mensaje que ningún handler recoge se destruye. Cada mensaje debe terminar: envíalo con `$.send()` o llama a `$.destroy()`.\n\nExample: Dos entradas\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nEnvía datos desde una salida de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | El id de la salida. |\n| `data` | `Object` | yes |  | Los datos o un mensaje. |\n| `controller` | `Controller` | no |  | Hace disponibles `$.user`, `$.body` y las demás propiedades de la petición. |\n\nReturns: `Number` Número de mensajes enviados.\n\nCrea un mensaje nuevo para cada conexión de `output`. Cuando `data` es un mensaje, sus copias conservan el repositorio y los callbacks de ese mensaje. Devuelve el número de mensajes enviados (`0` cuando la salida no tiene conexión o el FlowStream está en pausa).\n\nExample: Un temporizador\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrea un mensaje nuevo que pertenece a esta instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Los datos. |\n\nReturns: `Message` El mensaje.\n\nEnvíalo con `$.send(output)`. A diferencia de `instance.send()`, puedes añadir listeners y un repositorio antes de enviarlo.\n\nExample: Esperar al final\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nMuestra un estado de la instancia en el diseñador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | El estado. |\n| `delay` | `Number` | no |  | Retraso en ms. |\n\n`data` es cualquier valor que el diseño del componente (`<body>`, `<script>`) pueda mostrar. Con `delay` (ms), el estado se envía una sola vez pasado ese tiempo, lo que evita saturar el diseñador. Sin argumentos, se vuelve a enviar el último estado.\n\nExample: Contar mensajes\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nEnvía datos al dashboard del diseñador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Datos del dashboard. |\n\nComo `instance.status()`, pero para los widgets del dashboard. Se conserva el último valor, que se vuelve a enviar cuando se llama sin argumentos.\n\nExample: Temperatura\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nInforma de un error de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | El error. |\n\nEl error se guarda entre los diez últimos errores del FlowStream (contados en `stats.errors`), se muestra en el diseñador y se pasa a `Flow.onerror`. `$.throw(err)` hace lo mismo y además establece `$.error`. Ninguno de los dos termina el mensaje.\n\nExample: Datos no válidos\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nLa configuración de la instancia.\n\nReturns: `Object`\n\nEl `exports.config` por defecto combinado con la `config` del diseño. Un cambio desde el diseñador o con `flowstream.reconfigure()` actualiza el mismo objeto y llama a `instance.configure(config)`.\n\nExample: Leer un valor\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nSe ejecuta cuando cambia la configuración de la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La nueva configuración. |\n\nSe llama después de que el diseñador, un diseño nuevo o `flowstream.reconfigure()` hayan cambiado `instance.config`. No se llama para la primera configuración; usa `exports.make()` para eso.\n\nExample: Reiniciar un temporizador\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nSe ejecuta cuando la instancia se detiene.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true` cuando la instancia se elimina, no solo cuando se vuelve a crear. |\n\nSe llama cuando la instancia se elimina del diseño, su componente se sustituye o se elimina, o el FlowStream se descarga. Limpia aquí los temporizadores y cierra las conexiones. Otros handlers opcionales: `instance.init()` (una vez, después de crear el diseño), `instance.refresh()` (después de cada cambio del diseño), `instance.pause(is)` e `instance.variables(variables)`.\n\nExample: Limpiar\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nSe ejecuta cuando se dispara la instancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Los datos del disparo. |\n\nLo llaman `flowstream.trigger()` y el botón de disparo del diseñador. Normalmente inicia un mensaje nuevo.\n\nExample: Iniciar bajo demanda\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nSustituye los marcadores `{key}` por variables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | El texto. |\n| `data` | `Object` | no |  | Valores adicionales. |\n| `encoding` | `String/Function` | no |  | Cómo codificar cada valor. |\n\nReturns: `String` El texto con los valores.\n\nCada `{key}` (o `{{key}}`) se busca en las variables del FlowStream, después en `variables2`, después en los secretos, después en `{hostname}` y después en `data` (funcionan las claves anidadas como `{user.name}`). Las claves desconocidas se quedan como están. `encoding` es `'url'`, `'json'`, `'querify'` o `function(value, key)`. Un objeto como `str` sustituye todos sus valores de tipo cadena.\n\nExample: Una URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nGuarda los cambios de la instancia y la vuelve a dibujar en el diseñador.\n\nÚsalo después de cambiar `instance.config` u otras propiedades del diseño en el código. Después, el FlowStream emite `save`.\n\nExample: Recordar un valor\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nEl motor FlowStream que ejecuta la instancia.\n\nReturns: `FlowStream`\n\nPropiedades útiles: `instance.main.variables` (las variables), `instance.main.paused`, `instance.main.stats` e `instance.main.id`. `instance.instances` contiene todas las instancias del diseño e `instance.components` todos los componentes registrados. `instance.id` es el id de la instancia, `instance.component` el id del componente e `instance.module` el componente.\n\nExample: Leer una variable\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nLos datos del mensaje.\n\nReturns: `Object`\n\nCualquier valor. Cada conexión recibe su propia copia de los objetos y Buffers cuando la clonación está activada (por defecto). Las propiedades de la petición `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` y `$.files` solo existen cuando el mensaje se inició con un controlador.\n\nExample: Leer y modificar\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nEnvía el mensaje desde una salida de la instancia actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | El id de la salida. |\n| `data` | `Object` | no |  | Los nuevos datos. |\n| `clone` | `Boolean` | no | `cloning` | Clona los datos para cada conexión. |\n\nReturns: `Number` Número de mensajes enviados.\n\nSin `output`, se envía desde todas las salidas. Sin `data`, conserva sus datos. Si no hay nada conectado a la salida, el mensaje se destruye. `clone` anula la opción `cloning` del FlowStream para esta llamada. Devuelve el número de mensajes enviados.\n\nExample: Encaminar según una condición\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nTermina el mensaje.\n\nLlámalo en el último componente de una cadena. Cuando termina la última copia de un mensaje, se emite `end` y se ejecuta el callback de `flowstream.send()` o `flowstream.exec()`. `$.end()` es un alias.\n\nExample: Último componente\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nUn objeto compartido por el mensaje y todas sus copias.\n\nReturns: `Object`\n\nÚsalo para pasar valores a lo largo de toda la cadena sin cambiar `$.data`. Se devuelve como `repo` al callback de `flowstream.send()` y `flowstream.exec()`. `$.vars` es otro objeto compartido.\n\nExample: Conservar un valor\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nSustituye los marcadores `{key}` por variables y valores del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | El texto. |\n| `data` | `Object` | no | `the message` | Valores. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` o una función. |\n\nReturns: `String`\n\nLo mismo que `instance.replace()`, pero sin `data` se usa el propio mensaje, así que `{data.id}` lee `$.data.id`. `$.replace()` es un alias.\n\nExample: Construir una URL\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nEscucha los eventos del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El evento. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` El mensaje.\n\nEventos: `end` (terminó la última copia), `destroy` (en el mismo momento), `terminate` (terminó cualquier copia), `message` (una copia llegó a una instancia), `timeout`. Los listeners los comparten todas las copias. También existen `$.once()` y `$.off()`.\n\nExample: Medir la cadena\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nLimita cuánto puede tardar cada paso siguiente del mensaje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Milisegundos. |\n\nReturns: `Message` El mensaje.\n\nCada copia enviada después de esta llamada termina con `$.error = 408` si no se procesa en `time` ms; se llama a `callback` con esa copia. `$.totaltimeout([callback], time)` limita en cambio toda la cadena.\n\nExample: Cinco segundos para toda la cadena\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0n1nr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"FlowStream","summary":"Le module Flow, les instances FlowStream, les définitions de composants, les instances de composants et les messages.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Le module Flow, les instances FlowStream, les définitions de composants, les instances de composants et les messages.\n\nLes FlowStreams sont des graphes de composants chargés depuis des fichiers `.flow` dans `/flowstreams/` ou avec `Flow.load()`. Cette page liste l'objet `Flow`, l'instance FlowStream, la définition de composant (`exports`), l'instance de composant et le message (`$`). Le guide [FlowStream](../../guides/flowstream/) explique comment les utiliser avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nLe répertoire contenant les fichiers `.flow` chargés au démarrage de l'application.\n\nChaque fichier portant l'extension `.flow` dans ce répertoire est lu comme du JSON et passé à `Flow.load()` au démarrage de l'application. Les fichiers dont le nom contient `-bk` ou `_bk` sont ignorés : tu peux donc garder des sauvegardes à côté. Le répertoire `plugins/{name}/flowstreams/` de chaque plugin est chargé de la même manière.\n\nEn mode debug, le watcher redémarre l'application lorsqu'un fichier `.flow` change. La valeur par défaut est `/flowstreams/` ; une valeur vide désactive le chargement.\n\nExample: Structure du répertoire\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nL'objet JSON stocké dans un fichier `.flow` et transmis à `Flow.load()`.\n\n- `id` {String} : l'identifiant, la clé dans `Flow.instances`. Un identifiant aléatoire est généré s'il est absent.\n- `name` {String} : un nom lisible (par défaut : l'`id`).\n- `components` {Object} : id de composant → le composant sous forme de chaîne HTML avec un bloc `<script total>`.\n- `design` {Object} : id d'instance → `{ component, config, connections, x, y }`. `connections` associe un id de sortie à un tableau de `{ id: 'instanceid', index: 'inputid' }`.\n- `variables` {Object} : des valeurs que les composants lisent avec `instance.replace()` ou `$.variables()`.\n- `worker` {String/Boolean} : `'worker'` exécute le FlowStream dans un worker thread, toute autre valeur vraie (par exemple `'fork'`) dans un processus enfant ; `false` (par défaut) dans le processus principal.\n- `memory` {Number} : la limite du heap en Mo pour un processus enfant (`--max-old-space-size`).\n- `cloning` {Boolean} : clone les données du message pour chaque connexion (par défaut `true`).\n- `paused` {Boolean} : démarre le FlowStream en pause.\n- `readonly` {Boolean} : aucun événement `save` n'est émis.\n- `origin` {String} : l'URL publique de l'application, utilisée par `instance.href()` et la variable `{hostname}`.\n\n`flowstream.export()` renvoie la même structure ; tu peux donc la réécrire dans le fichier `.flow`.\n\nExample: Un fichier .flow minimal\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nCharge un FlowStream à partir de son schéma et le démarre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le schéma du FlowStream (le contenu d'un fichier `.flow`). |\n| `callback` | `Function` | no |  | `function(err, instance)` ; `instance` est l'instance du FlowStream. |\n\nCrée le FlowStream, enregistre ses composants, crée les instances du design et appelle `callback` quand tout est prêt. L'instance est stockée dans `Flow.instances[schema.id]` et le schéma dans `Flow.db[schema.id]`.\n\nQuand un FlowStream avec le même `id` est déjà chargé, il est mis à jour avec le nouveau schéma (les composants, le design et les variables sont remplacés) et le callback reçoit l'instance existante.\n\nUn schéma sans `name`, `components`, `design`, `sources` ni `variables` reçoit des valeurs par défaut vides ; un flow vide se charge donc.\n\nExample: Charger un flow depuis le code\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nCharge tous les fichiers `.flow` d'un répertoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | Un chemin absolu. |\n| `callback` | `Function` | no |  | Appelé lorsque tous les fichiers sont chargés. |\n\nLit chaque fichier `.flow` de `directory` (par défaut `flowstreams/` à la racine de l'application), ignore les noms contenant `-bk` ou `_bk` et charge chacun avec `Flow.load()`. Un répertoire absent n'est pas une erreur. Le framework l'appelle pour `/flowstreams/` au démarrage ; appelle-la toi-même pour un autre répertoire.\n\nExample: Un autre répertoire\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nLes instances FlowStream chargées, indexées par leur `id`.\n\nReturns: `Object`\n\nUn objet dont chaque clé est l'`id` d'un schéma et chaque valeur l'instance FlowStream renvoyée par `Flow.load()`. Utilise-le pour envoyer des données à un FlowStream depuis des routes, des schémas ou des jobs.\n\nExample: Envoyer depuis une route\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nLes schémas des FlowStreams chargés, indexés par leur `id`.\n\nReturns: `Object`\n\nContient le schéma passé à `Flow.load()` ; il est remplacé par le schéma exporté chaque fois que le FlowStream s'enregistre (voir `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nDétruit un FlowStream et le retire de `Flow.instances` et de `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant du FlowStream. |\n\nArrête toutes les instances, ferme un éventuel worker, supprime le FlowStream et émet `remove` avec son schéma. Le fichier `.flow` n'est pas supprimé.\n\nExample: Supprimer\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nMet à jour un FlowStream chargé avec un nouveau schéma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le nouveau schéma ; `id` sélectionne le FlowStream. |\n\nReturns: `Boolean` `true` lorsque le FlowStream existe.\n\nTrouve le FlowStream par `schema.id`, stocke le schéma dans `Flow.db` et réécrit avec lui le FlowStream en cours d'exécution (composants, design et variables). Renvoie `false` lorsqu'aucun FlowStream avec cet `id` n'est chargé. `Flow.load()` l'appelle pour un `id` déjà chargé.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nConnecte un contrôleur WebSocket à un FlowStream pour le designer Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant du FlowStream (ou le FlowStream lui-même). |\n| `websocket` | `WebSocket` | yes |  | Le contrôleur WebSocket (`this` dans une route `SOCKET`). |\n| `check` | `Function` | no |  | `function(client, next)` ; appelle `next()` pour laisser entrer le client. |\n\nLe designer communique avec le FlowStream via ce WebSocket : il lit les composants, le design et les statistiques, et renvoie les modifications. `check(client, next)` s'exécute pour chaque nouveau client ; appelle `next()` pour l'accepter. Le socket est détaché lorsque le contrôleur WebSocket est détruit. Un `id` inconnu détruit le socket.\n\nExample: Point d'accès du designer\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nGère les erreurs de tous les FlowStreams.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | L'erreur. |\n| `source` | `String` | yes |  | L'endroit où elle s'est produite, par exemple `instance_message` ou `instance_make`. |\n| `id` | `String` | yes |  | L'identifiant de l'instance. |\n| `componentid` | `String` | yes |  | L'identifiant du composant. |\n| `stack` | `String` | no |  | La pile d'appels, pour les FlowStreams dans un worker. |\n\nPar défaut, affiche dans la console un bloc avec le nom du FlowStream, la source, l'identifiant de l'instance et l'identifiant du composant. Assigne ta propre fonction avant le chargement des FlowStreams ; `this` est l'instance FlowStream (`this.id` est son identifiant).\n\nExample: Journaliser les erreurs\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nUn FlowStream a été chargé et est prêt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | L'instance FlowStream. |\n| `schema` | `Object` | yes |  | Le schéma. |\n\nÉmis une fois `Flow.load()` terminé, avant son callback.\n\nExample: Journaliser\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nUn FlowStream a changé et son schéma doit être enregistré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Le schéma exporté avec `id`, `components`, `design`, `variables` et les autres champs. |\n\nÉmis environ cinq secondes après la dernière modification : une modification dans le designer, `flowstream.variables()`, `flowstream.reconfigure()` ou `instance.save()`. Le framework n'écrit pas lui-même les fichiers `.flow` ; enregistre le schéma ici. Rien n'est émis pour un schéma avec `readonly: true`.\n\nExample: Écrire le fichier .flow\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nCrée ou renvoie un moteur FlowStream par son nom, sans workers ni designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Le nom du moteur. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` Le moteur.\n\nRenvoie le moteur qui exécute les composants et les messages. Le même `name` renvoie le même moteur (nom par défaut `default`). Il n'a ni fichier `.flow`, ni worker, ni enregistrement ; `Flow.load()` s'appuie sur lui. Méthodes principales :\n\n- `add(id, html, [callback])` enregistre un composant à partir de son HTML.\n- `use(design, [callback])` crée des instances à partir d'un objet design (renvoie une Promise sans callback) ; `insert(design, [callback])` ajoute des instances ; `remove(keys, [callback])` les supprime.\n- `trigger('instanceid__inputid', data)` envoie des données vers une entrée ; `send('instanceid__outputid', data)` envoie des données depuis une sortie.\n- `find(id)` renvoie une instance ; `pause(is)` ; `reconfigure(id, config)` ; `destroy()`.\n- Événements : `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: Un moteur local\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nEnvoie des données à une instance et attend la fin du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | L'instance cible. |\n| `data` | `Object` | yes |  | Les données du message. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` est un identifiant d'instance, `@componentid` (la première instance du composant) ou `#name` (la première instance dont le composant porte ce nom). Ajoute `/inputid` pour définir `$.input`. Les données vont vers `instance.message` de la cible, qui doit donc définir `instance.message`.\n\nLe callback s'exécute lorsque le message et toutes ses copies sont détruits. Il reçoit `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, où `data` contient les données du dernier message. Une cible inconnue appelle `callback(404)`.\n\nExample: Attendre le résultat\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nEnvoie un message à une ou plusieurs instances avec un dépôt, des variables et un timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Options. |\n| `callback` | `Function` | no |  | `function(err, response)` ; `response` contient `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` est un identifiant d'instance, `@componentid` (toutes les instances du composant) ou `#name` (toutes les instances portant ce nom de composant). Chaque cible doit définir `instance.message`. Le callback s'exécute pour chaque cible lorsque son message se termine ; une cible inconnue donne `404`.\n\n- `opt.data` {Object} : les données (par défaut `{}`).\n- `opt.repo` {Object} : le `$.repo` initial.\n- `opt.vars` {Object} : le `$.vars` initial.\n- `opt.timeout` {Number} : en ms ; ensuite, le message se termine avec `error` `408`.\n- `opt.uid`, `opt.ref` : renvoyés tels quels dans la réponse.\n\nExample: Avec un timeout\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nAppelle le handler `instance.trigger` des instances.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | La cible. |\n| `data` | `Object` | no |  | Passé à `instance.trigger(data)`. |\n\nReturns: `FlowStreamInstance` L'instance.\n\n`id` est un identifiant d'instance, `@componentid` (toutes les instances du composant) ou `#name`. Seules les instances qui définissent `instance.trigger` sont appelées ; rien ne se passe tant que le FlowStream est en pause.\n\nExample: Lancer tous les timers\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nMet en pause ou relance le FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` met en pause, `false` relance. |\n\nReturns: `FlowStreamInstance` L'instance.\n\nUn FlowStream en pause abandonne les nouveaux messages et appelle `instance.pause(is)` de chaque instance qui le définit. Sans argument, il bascule l'état.\n\nExample: Mettre en pause\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nModifie la configuration d'une instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant de l'instance. |\n| `config` | `Object` | yes |  | Les clés à modifier. |\n\nReturns: `FlowStreamInstance` L'instance.\n\nLes clés de `config` sont fusionnées dans la configuration de l'instance, puis `instance.configure(config)` est appelé et le FlowStream s'enregistre.\n\nExample: Modifier un champ\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nRemplace les variables du FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | Les nouvelles variables. |\n\nReturns: `FlowStreamInstance` L'instance.\n\nAppelle `instance.variables(variables)` et `instance.vary('variables')` de chaque instance qui les définit, puis enregistre le FlowStream.\n\nExample: Définir des variables\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nLit les composants enregistrés.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` L'instance.\n\nLe callback reçoit un tableau contenant `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` et `settings` de chaque composant.\n\nExample: Lister les noms\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nEnregistre ou remplace un composant à l'exécution.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant du composant. |\n| `html` | `String` | yes |  | La source du composant. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` L'instance.\n\n`html` est le fichier du composant avec un bloc `<script total>`. Les instances existantes du composant sont recréées avec le nouveau code. Utilise `flowstream.rem(id, [callback])` pour désenregistrer un composant et supprimer ses instances.\n\nExample: Ajouter un composant\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nExporte le schéma actuel du FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` L'instance.\n\nLe callback reçoit le schéma au format `.flow` : `components` (HTML brut), `design`, `variables`, `sources`, `paused` et les autres champs du schéma chargé.\n\nExample: Sauvegarde\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nStatistiques du FlowStream.\n\nReturns: `Object`\n\nContient `messages` (messages envoyés), `pending` (messages en cours), `minutes` (minutes d'exécution), `mm` (messages de la dernière minute), `errors` (nombre des dernières erreurs, au plus 10), `memory` et `paused`. `memory` (heap en octets) n'est mesuré que dans un worker ou un processus enfant. Pour un FlowStream dans un worker, l'objet provient du worker environ toutes les 15 secondes et contient aussi `pid` ; avant le premier rapport, il vaut `undefined`.\n\nExample: Lire les statistiques\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nDétruit ce FlowStream et le retire de `Flow`.\n\nIdentique à `Flow.remove(flowstream.id)`. `flowstream.destroy()` arrête seulement le FlowStream et son worker ; il reste dans `Flow.instances`.\n\nExample: Supprimer\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nCrée une instance du composant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | La nouvelle instance. |\n| `config` | `Object` | yes |  | La configuration de l'instance. |\n\nUn composant est un fichier HTML dont le bloc `<script total>` est le code serveur ; `exports` est le composant. `make` s'exécute pour chaque instance du design ; `this` et `instance` sont tous deux l'instance, et `config` sa configuration (`exports.config` fusionné avec la `config` du design). Assigne ici des handlers comme `instance.message`.\n\nLes autres blocs du fichier sont destinés au designer : `<readme>`, `<settings>`, `<style>`, `<script>` (code client), `<body>` et `<template>`.\n\nExample: Un composant complet\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nLes entrées et les sorties du composant.\n\nReturns: `Array`\n\n`exports.inputs` et `exports.outputs` sont des tableaux de `{ id, name }`. Les connexions du design font référence à ces identifiants : `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. Une connexion vers une entrée que le composant cible ne déclare pas est supprimée. Un composant sans entrées ne fait qu'envoyer (par exemple un timer) ; un composant sans sorties termine les messages.\n\nExample: Deux sorties\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nLa configuration par défaut de chaque instance.\n\nReturns: `Object`\n\nUne copie est fusionnée avec la `config` de l'instance dans le design et passée à `exports.make()` comme `config`.\n\nExample: Valeurs par défaut\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nLe nom et les autres métadonnées du composant.\n\nReturns: `String`\n\nMétadonnées pour le designer et pour `flowstream.components()` : `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` et `exports.meta`. Le sélecteur `#name` de `send()`, `exec()` et `trigger()` correspond à `exports.name`. L'identifiant du composant est la clé dans l'objet `components` du schéma.\n\nExample: Métadonnées\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nLes paquets NPM dont le composant a besoin.\n\nReturns: `Array`\n\nLes paquets sont installés avec `NPMINSTALL()` avant l'enregistrement du composant.\n\nExample: Utiliser un paquet\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nReçoit les messages qui arrivent sur les entrées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Le message. |\n\n`$` est le message ; `$.input` est l'identifiant de l'entrée. Au lieu d'un seul handler, tu peux définir `instance.message_INPUTID` pour une entrée. Un message qu'aucun handler ne prend en charge est détruit. Chaque message doit se terminer : transmets-le avec `$.send()` ou appelle `$.destroy()`.\n\nExample: Deux entrées\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nEnvoie des données depuis une sortie de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | L'identifiant de la sortie. |\n| `data` | `Object` | yes |  | Les données ou un message. |\n| `controller` | `Controller` | no |  | Rend disponibles `$.user`, `$.body` et les autres propriétés de la requête. |\n\nReturns: `Number` Nombre de messages envoyés.\n\nCrée un nouveau message pour chaque connexion de `output`. Lorsque `data` est un message, ses copies conservent le dépôt et les callbacks de ce message. Renvoie le nombre de messages envoyés (`0` lorsque la sortie n'a pas de connexion ou que le FlowStream est en pause).\n\nExample: Un timer\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrée un nouveau message appartenant à cette instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Les données. |\n\nReturns: `Message` Le message.\n\nEnvoie-le avec `$.send(output)`. Contrairement à `instance.send()`, tu peux ajouter des listeners et un dépôt avant l'envoi.\n\nExample: Attendre la fin\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nAffiche un statut de l'instance dans le designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | Le statut. |\n| `delay` | `Number` | no |  | Délai en ms. |\n\n`data` est n'importe quelle valeur que le design du composant (`<body>`, `<script>`) sait afficher. Avec `delay` (ms), le statut est envoyé une seule fois après ce délai, ce qui évite de surcharger le designer. Sans arguments, le dernier statut est renvoyé.\n\nExample: Compter les messages\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nEnvoie des données au tableau de bord du designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Données du tableau de bord. |\n\nComme `instance.status()`, mais pour les widgets du tableau de bord. La dernière valeur est conservée et renvoyée lors d'un appel sans arguments.\n\nExample: Température\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nSignale une erreur de l'instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | L'erreur. |\n\nL'erreur est stockée parmi les dix dernières erreurs du FlowStream (comptées dans `stats.errors`), affichée dans le designer et passée à `Flow.onerror`. `$.throw(err)` fait la même chose et définit aussi `$.error`. Aucun des deux ne termine le message.\n\nExample: Données invalides\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nLa configuration de l'instance.\n\nReturns: `Object`\n\nLa valeur par défaut `exports.config` fusionnée avec la `config` du design. Une modification depuis le designer ou `flowstream.reconfigure()` met à jour le même objet et appelle `instance.configure(config)`.\n\nExample: Lire une valeur\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nS'exécute lorsque la configuration de l'instance change.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La nouvelle configuration. |\n\nAppelé après que le designer, un nouveau design ou `flowstream.reconfigure()` a modifié `instance.config`. Il n'est pas appelé pour la première configuration ; utilise `exports.make()` pour cela.\n\nExample: Redémarrer un timer\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nS'exécute lorsque l'instance s'arrête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true` lorsque l'instance est supprimée, et pas seulement recréée. |\n\nAppelé lorsque l'instance est retirée du design, que son composant est remplacé ou supprimé, ou que le FlowStream est déchargé. Nettoie ici les timers et ferme les connexions. Autres handlers optionnels : `instance.init()` (une fois, après la création du design), `instance.refresh()` (après chaque modification du design), `instance.pause(is)` et `instance.variables(variables)`.\n\nExample: Nettoyer\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nS'exécute lorsque l'instance est déclenchée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Les données du déclenchement. |\n\nAppelé par `flowstream.trigger()` et par le bouton de déclenchement du designer. En général, il démarre un nouveau message.\n\nExample: Démarrer à la demande\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nRemplace les placeholders `{key}` par des variables.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Le texte. |\n| `data` | `Object` | no |  | Valeurs supplémentaires. |\n| `encoding` | `String/Function` | no |  | La façon d'encoder chaque valeur. |\n\nReturns: `String` Le texte avec les valeurs.\n\nChaque `{key}` (ou `{{key}}`) est recherché dans les variables du FlowStream, puis dans `variables2`, puis dans les secrets, puis dans `{hostname}`, puis dans `data` (les clés imbriquées comme `{user.name}` fonctionnent). Les clés inconnues restent telles quelles. `encoding` vaut `'url'`, `'json'`, `'querify'` ou `function(value, key)`. Un objet passé comme `str` voit toutes ses valeurs de type chaîne remplacées.\n\nExample: Une URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nEnregistre les modifications de l'instance et la redessine dans le designer.\n\nUtilise-la après avoir modifié `instance.config` ou d'autres propriétés du design dans le code. Le FlowStream émet ensuite `save`.\n\nExample: Mémoriser une valeur\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nLe moteur FlowStream qui exécute l'instance.\n\nReturns: `FlowStream`\n\nPropriétés utiles : `instance.main.variables` (les variables), `instance.main.paused`, `instance.main.stats` et `instance.main.id`. `instance.instances` contient toutes les instances du design et `instance.components` tous les composants enregistrés. `instance.id` est l'identifiant de l'instance, `instance.component` l'identifiant du composant et `instance.module` le composant.\n\nExample: Lire une variable\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nLes données du message.\n\nReturns: `Object`\n\nN'importe quelle valeur. Chaque connexion reçoit sa propre copie des objets et des Buffers quand le clonage est activé (par défaut). Les propriétés de requête `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` et `$.files` n'existent que si le message a été démarré avec un contrôleur.\n\nExample: Lire et modifier\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nTransmet le message depuis une sortie de l'instance courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | L'identifiant de la sortie. |\n| `data` | `Object` | no |  | Nouvelles données. |\n| `clone` | `Boolean` | no | `cloning` | Clone les données pour chaque connexion. |\n\nReturns: `Number` Nombre de messages envoyés.\n\nSans `output`, il est envoyé depuis toutes les sorties. Sans `data`, il conserve ses données. Lorsque rien n'est connecté à la sortie, le message est détruit. `clone` remplace l'option `cloning` du FlowStream pour cet appel. Renvoie le nombre de messages envoyés.\n\nExample: Aiguiller selon une condition\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nTermine le message.\n\nAppelle-la dans le dernier composant d'une chaîne. Lorsque la dernière copie d'un message se termine, `end` est émis et le callback de `flowstream.send()` ou de `flowstream.exec()` s'exécute. `$.end()` est un alias.\n\nExample: Dernier composant\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nUn objet partagé par le message et toutes ses copies.\n\nReturns: `Object`\n\nUtilise-le pour transmettre des valeurs tout au long de la chaîne sans modifier `$.data`. Il est renvoyé comme `repo` au callback de `flowstream.send()` et de `flowstream.exec()`. `$.vars` est un autre objet partagé.\n\nExample: Conserver une valeur\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nRemplace les placeholders `{key}` par des variables et des valeurs du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Le texte. |\n| `data` | `Object` | no | `the message` | Valeurs. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` ou une fonction. |\n\nReturns: `String`\n\nIdentique à `instance.replace()`, mais sans `data` c'est le message lui-même qui est utilisé : `{data.id}` lit donc `$.data.id`. `$.replace()` est un alias.\n\nExample: Construire une URL\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nÉcoute les événements du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | L'événement. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` Le message.\n\nÉvénements : `end` (la dernière copie s'est terminée), `destroy` (au même moment), `terminate` (une copie quelconque s'est terminée), `message` (une copie a atteint une instance), `timeout`. Les listeners sont partagés par toutes les copies. `$.once()` et `$.off()` existent aussi.\n\nExample: Mesurer la chaîne\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nLimite la durée de chaque étape suivante du message.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Millisecondes. |\n\nReturns: `Message` Le message.\n\nChaque copie envoyée après cet appel se termine avec `$.error = 408` lorsqu'elle n'est pas traitée en moins de `time` ms ; `callback` est appelé avec cette copie. `$.totaltimeout([callback], time)` limite plutôt la chaîne entière.\n\nExample: Cinq secondes pour toute la chaîne\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0n1nr60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"FlowStream","summary":"Il modulo Flow, le istanze di FlowStream, le definizioni dei componenti, le istanze dei componenti e i messaggi.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Il modulo Flow, le istanze di FlowStream, le definizioni dei componenti, le istanze dei componenti e i messaggi.\n\nI FlowStream sono grafi di componenti caricati dai file `.flow` in `/flowstreams/` o con `Flow.load()`. Questa pagina elenca l'oggetto `Flow`, l'istanza di FlowStream, la definizione del componente (`exports`), l'istanza del componente e il messaggio (`$`). La guida [FlowStream](../../guides/flowstream/) spiega come usarli con degli esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nLa directory con i file `.flow` che vengono caricati all'avvio dell'app.\n\nOgni file con estensione `.flow` in questa directory viene letto come JSON e passato a `Flow.load()` all'avvio dell'app. I file il cui nome contiene `-bk` o `_bk` vengono saltati, così puoi tenere i backup accanto. La directory `plugins/{name}/flowstreams/` di ogni plugin viene caricata allo stesso modo.\n\nIn modalità debug il watcher riavvia l'app quando un file `.flow` cambia. Il valore predefinito è `/flowstreams/`; un valore vuoto disattiva il caricamento.\n\nExample: Struttura della directory\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nL'oggetto JSON salvato in un file `.flow` e passato a `Flow.load()`.\n\n- `id` {String}: l'identificatore, la chiave in `Flow.instances`. Se manca ne viene generato uno casuale.\n- `name` {String}: un nome leggibile (predefinito: l'`id`).\n- `components` {Object}: id del componente → il componente come stringa HTML con un blocco `<script total>`.\n- `design` {Object}: id dell'istanza → `{ component, config, connections, x, y }`. `connections` associa l'id di un output a un array di `{ id: 'instanceid', index: 'inputid' }`.\n- `variables` {Object}: valori che i componenti leggono con `instance.replace()` o `$.variables()`.\n- `worker` {String/Boolean}: `'worker'` esegue il FlowStream in un worker thread, un altro valore truthy (per esempio `'fork'`) in un processo figlio; `false` (predefinito) nel processo principale.\n- `memory` {Number}: il limite dell'heap in MB per un processo figlio (`--max-old-space-size`).\n- `cloning` {Boolean}: clona i dati del messaggio per ogni connessione (predefinito `true`).\n- `paused` {Boolean}: avvia il FlowStream in pausa.\n- `readonly` {Boolean}: non vengono emessi eventi `save`.\n- `origin` {String}: l'URL pubblico dell'app, usato da `instance.href()` e dalla variabile `{hostname}`.\n\n`flowstream.export()` restituisce la stessa forma, così puoi riscriverla nel file `.flow`.\n\nExample: Un file .flow minimo\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nCarica un FlowStream dal suo schema e lo avvia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Lo schema del FlowStream (il contenuto di un file `.flow`). |\n| `callback` | `Function` | no |  | `function(err, instance)`; `instance` è l'istanza del FlowStream. |\n\nCrea il FlowStream, registra i suoi componenti, crea le istanze del design e chiama `callback` quando tutto è pronto. L'istanza viene salvata in `Flow.instances[schema.id]` e lo schema in `Flow.db[schema.id]`.\n\nQuando un FlowStream con lo stesso `id` è già caricato, viene invece aggiornato con il nuovo schema (componenti, design e variabili vengono sostituiti) e la callback riceve l'istanza esistente.\n\nUno schema senza `name`, `components`, `design`, `sources` o `variables` riceve valori predefiniti vuoti, così anche un flow vuoto viene caricato.\n\nExample: Caricare un flow dal codice\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nCarica tutti i file `.flow` di una directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | Un percorso assoluto. |\n| `callback` | `Function` | no |  | Chiamata quando tutti i file sono caricati. |\n\nLegge ogni file `.flow` di `directory` (predefinita `flowstreams/` nella root dell'app), salta i nomi con `-bk` o `_bk` e carica ciascuno con `Flow.load()`. Una directory mancante non è un errore. Il framework la chiama per `/flowstreams/` all'avvio; chiamala tu per un'altra directory.\n\nExample: Un'altra directory\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nLe istanze di FlowStream caricate, per `id`.\n\nReturns: `Object`\n\nUn oggetto in cui ogni chiave è l'`id` di uno schema e ogni valore è l'istanza di FlowStream restituita da `Flow.load()`. Usalo per inviare dati a un FlowStream da route, schemi o job.\n\nExample: Inviare da una route\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nGli schemi dei FlowStream caricati, per `id`.\n\nReturns: `Object`\n\nContiene lo schema passato a `Flow.load()`; viene sostituito dallo schema esportato ogni volta che il FlowStream si salva (vedi `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nDistrugge un FlowStream e lo rimuove da `Flow.instances` e `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del FlowStream. |\n\nFerma tutte le istanze, chiude un eventuale worker, rimuove il FlowStream ed emette `remove` con il suo schema. Il file `.flow` non viene eliminato.\n\nExample: Rimuovere\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nAggiorna un FlowStream caricato con un nuovo schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Il nuovo schema; `id` seleziona il FlowStream. |\n\nReturns: `Boolean` `true` quando il FlowStream esiste.\n\nTrova il FlowStream tramite `schema.id`, salva lo schema in `Flow.db` e riscrive con esso il FlowStream in esecuzione (componenti, design e variabili). Restituisce `false` quando non è caricato alcun FlowStream con questo `id`. `Flow.load()` la chiama per un `id` già caricato.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nCollega un controller WebSocket a un FlowStream per il designer di Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del FlowStream (o il FlowStream stesso). |\n| `websocket` | `WebSocket` | yes |  | Il controller WebSocket (`this` in una route `SOCKET`). |\n| `check` | `Function` | no |  | `function(client, next)`; chiama `next()` per far entrare il client. |\n\nIl designer comunica con il FlowStream tramite questo WebSocket: legge i componenti, il design e le statistiche, e rimanda indietro le modifiche. `check(client, next)` viene eseguito per ogni nuovo client; chiama `next()` per accettarlo. Il socket viene scollegato quando il controller WebSocket viene distrutto. Un `id` sconosciuto distrugge il socket.\n\nExample: Endpoint del designer\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nGestisce gli errori di tutti i FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | L'errore. |\n| `source` | `String` | yes |  | Dove è avvenuto, per esempio `instance_message` o `instance_make`. |\n| `id` | `String` | yes |  | L'id dell'istanza. |\n| `componentid` | `String` | yes |  | L'id del componente. |\n| `stack` | `String` | no |  | Lo stack, per i FlowStream in un worker. |\n\nLa funzione predefinita stampa nella console un blocco con il nome del FlowStream, la sorgente, l'id dell'istanza e l'id del componente. Assegna la tua funzione prima che i FlowStream vengano caricati; `this` è l'istanza di FlowStream (`this.id` è il suo id).\n\nExample: Registrare gli errori\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nUn FlowStream è stato caricato ed è pronto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | L'istanza di FlowStream. |\n| `schema` | `Object` | yes |  | Lo schema. |\n\nEmesso dopo che `Flow.load()` ha finito, prima della sua callback.\n\nExample: Log\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nUn FlowStream è cambiato e il suo schema va salvato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Lo schema esportato con `id`, `components`, `design`, `variables` e gli altri campi. |\n\nEmesso circa cinque secondi dopo l'ultima modifica: una modifica nel designer, `flowstream.variables()`, `flowstream.reconfigure()` o `instance.save()`. Il framework non scrive da solo i file `.flow`; salva qui lo schema. Non viene emesso nulla per uno schema con `readonly: true`.\n\nExample: Scrivere il file .flow\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nCrea o restituisce un motore FlowStream per nome, senza worker né designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Il nome del motore. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` Il motore.\n\nRestituisce il motore che esegue componenti e messaggi. Lo stesso `name` restituisce lo stesso motore (nome predefinito `default`). Non ha file `.flow`, worker né salvataggio; `Flow.load()` si basa su di esso. Metodi principali:\n\n- `add(id, html, [callback])` registra un componente dal suo HTML.\n- `use(design, [callback])` crea le istanze da un oggetto design (senza callback restituisce una Promise); `insert(design, [callback])` aggiunge istanze; `remove(keys, [callback])` le rimuove.\n- `trigger('instanceid__inputid', data)` invia dati a un input; `send('instanceid__outputid', data)` invia dati da un output.\n- `find(id)` restituisce un'istanza; `pause(is)`; `reconfigure(id, config)`; `destroy()`.\n- Eventi: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: Un motore locale\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nInvia dati a un'istanza e attende la fine del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | L'istanza di destinazione. |\n| `data` | `Object` | yes |  | I dati del messaggio. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` è un id di istanza, `@componentid` (la prima istanza del componente) o `#name` (la prima istanza il cui componente ha questo nome). Aggiungi `/inputid` per impostare `$.input`. I dati vanno a `instance.message` della destinazione, quindi questa deve definire `instance.message`.\n\nLa callback viene eseguita quando il messaggio e tutte le sue copie sono distrutti. Riceve `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, dove `data` sono i dati dell'ultimo messaggio. Una destinazione sconosciuta chiama `callback(404)`.\n\nExample: Attendere il risultato\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nInvia un messaggio a una o più istanze con un repository, variabili e un timeout.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Opzioni. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` contiene `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` è un id di istanza, `@componentid` (tutte le istanze del componente) o `#name` (tutte le istanze con il nome del componente). Ogni destinazione deve definire `instance.message`. La callback viene eseguita per ogni destinazione quando il suo messaggio termina; una destinazione sconosciuta dà `404`.\n\n- `opt.data` {Object}: i dati (predefinito `{}`).\n- `opt.repo` {Object}: il `$.repo` iniziale.\n- `opt.vars` {Object}: il `$.vars` iniziale.\n- `opt.timeout` {Number}: ms; dopo, il messaggio termina con `error` `408`.\n- `opt.uid`, `opt.ref`: restituiti nella risposta.\n\nExample: Con un timeout\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nChiama l'handler `instance.trigger` delle istanze.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | La destinazione. |\n| `data` | `Object` | no |  | Passato a `instance.trigger(data)`. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\n`id` è un id di istanza, `@componentid` (tutte le istanze del componente) o `#name`. Vengono chiamate solo le istanze che definiscono `instance.trigger`; mentre il FlowStream è in pausa non succede nulla.\n\nExample: Eseguire tutti i timer\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nMette in pausa o riprende il FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` mette in pausa, `false` riprende. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\nUn FlowStream in pausa scarta i nuovi messaggi e chiama `instance.pause(is)` di ogni istanza che lo definisce. Senza argomento inverte lo stato.\n\nExample: Mettere in pausa\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nCambia la configurazione di un'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id dell'istanza. |\n| `config` | `Object` | yes |  | Le chiavi da cambiare. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\nLe chiavi di `config` vengono unite alla configurazione dell'istanza, poi viene chiamato `instance.configure(config)` e il FlowStream si salva.\n\nExample: Cambiare un campo\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nSostituisce le variabili del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | Le nuove variabili. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\nChiama `instance.variables(variables)` e `instance.vary('variables')` di ogni istanza che li definisce e salva il FlowStream.\n\nExample: Impostare le variabili\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nLegge i componenti registrati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\nLa callback riceve un array con `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` e `settings` di ogni componente.\n\nExample: Elencare i nomi\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nRegistra o sostituisce un componente in fase di esecuzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del componente. |\n| `html` | `String` | yes |  | Il sorgente del componente. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\n`html` è il file del componente con un blocco `<script total>`. Le istanze esistenti del componente vengono ricreate con il nuovo codice. Usa `flowstream.rem(id, [callback])` per annullare la registrazione di un componente e rimuoverne le istanze.\n\nExample: Aggiungere un componente\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nEsporta lo schema attuale del FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` L'istanza.\n\nLa callback riceve lo schema nel formato `.flow`: `components` (HTML grezzo), `design`, `variables`, `sources`, `paused` e gli altri campi dello schema caricato.\n\nExample: Backup\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nStatistiche del FlowStream.\n\nReturns: `Object`\n\nContiene `messages` (messaggi inviati), `pending` (messaggi in elaborazione), `minutes` (minuti di esecuzione), `mm` (messaggi nell'ultimo minuto), `errors` (numero degli ultimi errori, al massimo 10), `memory` e `paused`. `memory` (heap in byte) viene misurata solo in un worker o in un processo figlio. Per un FlowStream in un worker l'oggetto arriva dal worker circa ogni 15 secondi e contiene anche `pid`; prima del primo report è `undefined`.\n\nExample: Leggere le statistiche\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nDistrugge questo FlowStream e lo rimuove da `Flow`.\n\nEquivale a `Flow.remove(flowstream.id)`. `flowstream.destroy()` ferma solo il FlowStream e il suo worker; resta in `Flow.instances`.\n\nExample: Rimuovere\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nCrea un'istanza del componente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | La nuova istanza. |\n| `config` | `Object` | yes |  | La configurazione dell'istanza. |\n\nUn componente è un file HTML il cui blocco `<script total>` è il codice server; `exports` è il componente. `make` viene eseguito per ogni istanza del design, dove `this` e `instance` sono entrambi l'istanza e `config` è la sua configurazione (`exports.config` unito al `config` del design). Assegna qui gli handler come `instance.message`.\n\nGli altri blocchi del file servono al designer: `<readme>`, `<settings>`, `<style>`, `<script>` (codice client), `<body>` e `<template>`.\n\nExample: Un componente completo\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nGli input e gli output del componente.\n\nReturns: `Array`\n\n`exports.inputs` e `exports.outputs` sono array di `{ id, name }`. Le connessioni nel design fanno riferimento a questi id: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. Una connessione a un input che il componente di destinazione non dichiara viene rimossa. Un componente senza input si limita a inviare (per esempio un timer); uno senza output termina i messaggi.\n\nExample: Due output\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nLa configurazione predefinita di ogni istanza.\n\nReturns: `Object`\n\nUna copia viene unita al `config` dell'istanza nel design e passata a `exports.make()` come `config`.\n\nExample: Valori predefiniti\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nIl nome e gli altri metadati del componente.\n\nReturns: `String`\n\nMetadati per il designer e per `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` e `exports.meta`. Il selettore `#name` di `send()`, `exec()` e `trigger()` corrisponde a `exports.name`. L'id del componente è la chiave nell'oggetto `components` dello schema.\n\nExample: Metadati\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nI pacchetti NPM di cui il componente ha bisogno.\n\nReturns: `Array`\n\nI pacchetti vengono installati con `NPMINSTALL()` prima che il componente sia registrato.\n\nExample: Usare un pacchetto\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nRiceve i messaggi che arrivano agli input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Il messaggio. |\n\n`$` è il messaggio; `$.input` è l'id dell'input. Invece di un solo handler puoi definire `instance.message_INPUTID` per un singolo input. Un messaggio che nessun handler prende viene distrutto. Ogni messaggio deve terminare: inoltralo con `$.send()` oppure chiama `$.destroy()`.\n\nExample: Due input\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nInvia dati da un output dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | L'id dell'output. |\n| `data` | `Object` | yes |  | I dati o un messaggio. |\n| `controller` | `Controller` | no |  | Rende disponibili `$.user`, `$.body` e le altre proprietà della richiesta. |\n\nReturns: `Number` Numero di messaggi inviati.\n\nCrea un nuovo messaggio per ogni connessione di `output`. Quando `data` è un messaggio, le sue copie mantengono il repository e le callback di quel messaggio. Restituisce il numero di messaggi inviati (`0` quando l'output non ha connessioni o il FlowStream è in pausa).\n\nExample: Un timer\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nCrea un nuovo messaggio appartenente a questa istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | I dati. |\n\nReturns: `Message` Il messaggio.\n\nInvialo con `$.send(output)`. A differenza di `instance.send()`, puoi aggiungere listener e un repository prima dell'invio.\n\nExample: Attendere la fine\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nMostra uno stato dell'istanza nel designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | Lo stato. |\n| `delay` | `Number` | no |  | Ritardo in ms. |\n\n`data` è qualsiasi valore che il design del componente (`<body>`, `<script>`) sa visualizzare. Con `delay` (ms) lo stato viene inviato una sola volta dopo questo tempo, il che evita di sommergere il designer. Senza argomenti viene inviato di nuovo l'ultimo stato.\n\nExample: Contare i messaggi\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nInvia dati alla dashboard del designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Dati della dashboard. |\n\nCome `instance.status()`, ma per i widget della dashboard. L'ultimo valore viene conservato e inviato di nuovo quando la chiami senza argomenti.\n\nExample: Temperatura\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nSegnala un errore dell'istanza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | L'errore. |\n\nL'errore viene salvato tra gli ultimi dieci errori del FlowStream (conteggiati in `stats.errors`), mostrato nel designer e passato a `Flow.onerror`. `$.throw(err)` fa lo stesso e imposta anche `$.error`. Nessuno dei due termina il messaggio.\n\nExample: Dati non validi\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nLa configurazione dell'istanza.\n\nReturns: `Object`\n\nL'`exports.config` predefinito unito al `config` del design. Una modifica dal designer o da `flowstream.reconfigure()` aggiorna lo stesso oggetto e chiama `instance.configure(config)`.\n\nExample: Leggere un valore\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nViene eseguito quando la configurazione dell'istanza cambia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | La nuova configurazione. |\n\nChiamato dopo che il designer, un nuovo design o `flowstream.reconfigure()` hanno cambiato `instance.config`. Non viene chiamato per la prima configurazione; per quella usa `exports.make()`.\n\nExample: Riavviare un timer\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nViene eseguito quando l'istanza si ferma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true` quando l'istanza viene rimossa, non solo ricreata. |\n\nChiamato quando l'istanza viene rimossa dal design, il suo componente viene sostituito o rimosso, oppure il FlowStream viene scaricato. Cancella qui i timer e chiudi le connessioni. Altri handler opzionali: `instance.init()` (una volta, dopo la creazione del design), `instance.refresh()` (dopo ogni modifica del design), `instance.pause(is)` e `instance.variables(variables)`.\n\nExample: Pulizia\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nViene eseguito quando l'istanza viene attivata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | I dati del trigger. |\n\nChiamato da `flowstream.trigger()` e dal pulsante trigger del designer. Di solito avvia un nuovo messaggio.\n\nExample: Avviare su richiesta\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nSostituisce i segnaposto `{key}` con le variabili.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Il testo. |\n| `data` | `Object` | no |  | Valori aggiuntivi. |\n| `encoding` | `String/Function` | no |  | Come codificare ogni valore. |\n\nReturns: `String` Il testo con i valori.\n\nOgni `{key}` (o `{{key}}`) viene cercato nelle variabili del FlowStream, poi in `variables2`, poi nei secret, poi in `{hostname}`, poi in `data` (funzionano le chiavi annidate come `{user.name}`). Le chiavi sconosciute restano come sono. `encoding` è `'url'`, `'json'`, `'querify'` o `function(value, key)`. Un oggetto come `str` sostituisce tutti i suoi valori stringa.\n\nExample: Un URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nSalva le modifiche dell'istanza e la ridisegna nel designer.\n\nUsalo dopo aver cambiato nel codice `instance.config` o altre proprietà del design. Il FlowStream emette quindi `save`.\n\nExample: Ricordare un valore\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nIl motore FlowStream che esegue l'istanza.\n\nReturns: `FlowStream`\n\nProprietà utili: `instance.main.variables` (le variabili), `instance.main.paused`, `instance.main.stats` e `instance.main.id`. `instance.instances` contiene tutte le istanze del design e `instance.components` tutti i componenti registrati. `instance.id` è l'id dell'istanza, `instance.component` l'id del componente e `instance.module` il componente.\n\nExample: Leggere una variabile\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nI dati del messaggio.\n\nReturns: `Object`\n\nQualsiasi valore. Ogni connessione riceve la propria copia di oggetti e Buffer quando la clonazione è attiva (il valore predefinito). Le proprietà della richiesta `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` e `$.files` esistono solo quando il messaggio è stato avviato con un controller.\n\nExample: Leggere e modificare\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nInoltra il messaggio da un output dell'istanza corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | L'id dell'output. |\n| `data` | `Object` | no |  | Nuovi dati. |\n| `clone` | `Boolean` | no | `cloning` | Clona i dati per ogni connessione. |\n\nReturns: `Number` Numero di messaggi inviati.\n\nSenza `output` viene inviato da tutti gli output. Senza `data` mantiene i suoi dati. Quando all'output non è collegato nulla, il messaggio viene distrutto. `clone` sovrascrive l'opzione `cloning` del FlowStream per questa chiamata. Restituisce il numero di messaggi inviati.\n\nExample: Instradare in base a una condizione\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nTermina il messaggio.\n\nChiamalo nell'ultimo componente di una catena. Quando termina l'ultima copia di un messaggio, viene emesso `end` e viene eseguita la callback di `flowstream.send()` o `flowstream.exec()`. `$.end()` è un alias.\n\nExample: Ultimo componente\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nUn oggetto condiviso dal messaggio e da tutte le sue copie.\n\nReturns: `Object`\n\nUsalo per passare valori lungo tutta la catena senza modificare `$.data`. Viene restituito come `repo` alla callback di `flowstream.send()` e `flowstream.exec()`. `$.vars` è un altro oggetto condiviso.\n\nExample: Conservare un valore\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nSostituisce i segnaposto `{key}` con le variabili e i valori del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Il testo. |\n| `data` | `Object` | no | `the message` | Valori. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` o una funzione. |\n\nReturns: `String`\n\nUguale a `instance.replace()`, ma senza `data` viene usato il messaggio stesso, quindi `{data.id}` legge `$.data.id`. `$.replace()` è un alias.\n\nExample: Costruire un URL\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nAscolta gli eventi del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | L'evento. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` Il messaggio.\n\nEventi: `end` (è terminata l'ultima copia), `destroy` (nello stesso momento), `terminate` (è terminata una copia qualsiasi), `message` (una copia ha raggiunto un'istanza), `timeout`. I listener sono condivisi da tutte le copie. Esistono anche `$.once()` e `$.off()`.\n\nExample: Misurare la catena\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nLimita quanto può durare ogni passo successivo del messaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Millisecondi. |\n\nReturns: `Message` Il messaggio.\n\nOgni copia inviata dopo questa chiamata termina con `$.error = 408` quando non viene elaborata entro `time` ms; `callback` viene chiamata con quella copia. `$.totaltimeout([callback], time)` limita invece l'intera catena.\n\nExample: Cinque secondi per l'intera catena\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm0n1nr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/flowstream/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"FlowStream","summary":"Modul Flow, inštancie FlowStream, definície komponentov, inštancie komponentov a správy.","markdown":"---\ntitle: FlowStream\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/flowstream/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# FlowStream\n\n> Modul Flow, inštancie FlowStream, definície komponentov, inštancie komponentov a správy.\n\nFlowStreamy sú grafy komponentov načítané zo súborov `.flow` v `/flowstreams/` alebo pomocou `Flow.load()`. Táto stránka uvádza objekt `Flow`, inštanciu FlowStream, definíciu komponentu (`exports`), inštanciu komponentu a správu (`$`). Príručka [FlowStream](../../guides/flowstream/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### CONF.directory_flowstreams = '/flowstreams/'\n\nType: `config`\n\nAdresár so súbormi `.flow`, ktoré sa načítajú pri štarte aplikácie.\n\nKaždý súbor s príponou `.flow` v tomto adresári sa pri štarte aplikácie prečíta ako JSON a odovzdá do `Flow.load()`. Súbory, ktorých názov obsahuje `-bk` alebo `_bk`, sa preskočia, takže vedľa nich môžeš mať zálohy. Adresár `plugins/{name}/flowstreams/` každého pluginu sa načíta rovnako.\n\nV režime debug watcher reštartuje aplikáciu, keď sa zmení súbor `.flow`. Predvolená hodnota je `/flowstreams/`; prázdna hodnota načítanie vypne.\n\nExample: Štruktúra adresára\n```text\nflowstreams/\n\torders.flow\n\torders_bk.flow     // skipped\nplugins/\n\tcrm/\n\t\tflowstreams/\n\t\t\tleads.flow\n```\n\n### { id, name, components, design, variables, worker, ... }\n\nType: `config`\n\nJSON objekt uložený v súbore `.flow` a odovzdaný do `Flow.load()`.\n\n- `id` {String}: identifikátor, kľúč v `Flow.instances`. Keď chýba, vygeneruje sa náhodný.\n- `name` {String}: čitateľný názov (predvolene: `id`).\n- `components` {Object}: id komponentu → komponent ako HTML reťazec s blokom `<script total>`.\n- `design` {Object}: id inštancie → `{ component, config, connections, x, y }`. `connections` mapuje id výstupu na pole `{ id: 'instanceid', index: 'inputid' }`.\n- `variables` {Object}: hodnoty, ktoré komponenty čítajú cez `instance.replace()` alebo `$.variables()`.\n- `worker` {String/Boolean}: `'worker'` spustí FlowStream vo worker vlákne, iná pravdivá hodnota (napríklad `'fork'`) v podradenom procese; `false` (predvolene) v hlavnom procese.\n- `memory` {Number}: limit heapu v MB pre podradený proces (`--max-old-space-size`).\n- `cloning` {Boolean}: klonuje dáta správy pre každé spojenie (predvolene `true`).\n- `paused` {Boolean}: spustí FlowStream pozastavený.\n- `readonly` {Boolean}: nevysielajú sa žiadne udalosti `save`.\n- `origin` {String}: verejná URL aplikácie, ktorú používa `instance.href()` a premenná `{hostname}`.\n\n`flowstream.export()` vracia rovnaký tvar, takže ho môžeš zapísať späť do súboru `.flow`.\n\nExample: Minimálny súbor .flow\n```json\n{\n\t\"id\": \"orders\",\n\t\"name\": \"Orders\",\n\t\"components\": {\n\t\t\"uppercase\": \"<script total>...</script>\",\n\t\t\"print\": \"<script total>...</script>\"\n\t},\n\t\"design\": {\n\t\t\"a1\": { \"component\": \"uppercase\", \"config\": { \"field\": \"name\" }, \"connections\": { \"output\": [{ \"id\": \"b1\", \"index\": \"input\" }] } },\n\t\t\"b1\": { \"component\": \"print\", \"config\": {} }\n\t},\n\t\"variables\": { \"currency\": \"EUR\" }\n}\n```\n\n### Flow.load(schema, [callback])\n\nType: `method`\n\nNačíta FlowStream z jeho schémy a spustí ho.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Schéma FlowStreamu (obsah súboru `.flow`). |\n| `callback` | `Function` | no |  | `function(err, instance)`; `instance` je inštancia FlowStreamu. |\n\nVytvorí FlowStream, zaregistruje jeho komponenty, vytvorí inštancie dizajnu a zavolá `callback`, keď je všetko pripravené. Inštancia sa uloží do `Flow.instances[schema.id]` a schéma do `Flow.db[schema.id]`.\n\nKeď je FlowStream s rovnakým `id` už načítaný, namiesto toho sa aktualizuje novou schémou (komponenty, dizajn a premenné sa nahradia) a callback dostane existujúcu inštanciu.\n\nSchéma bez `name`, `components`, `design`, `sources` alebo `variables` dostane prázdne predvolené hodnoty, takže sa načíta aj prázdny flow.\n\nExample: Načítanie flow z kódu\n```js\n// definitions/flowstream.js\nON('ready', function() {\n\n\tvar schema = {};\n\tschema.id = 'orders';\n\tschema.name = 'Orders';\n\tschema.components = {};\n\tschema.components.uppercase = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\n\tschema.components.print = F.Fs.readFileSync(PATH.root('components/print.html'), 'utf8');\n\tschema.design = {};\n\tschema.design.a1 = { component: 'uppercase', config: { field: 'name' }, connections: { output: [{ id: 'b1', index: 'input' }] } };\n\tschema.design.b1 = { component: 'print', config: {} };\n\n\tFlow.load(schema, function(err, instance) {\n\t\tinstance.send('a1', { name: 'Peter' });\n\t});\n});\n```\n\n### Flow.init([directory], [callback])\n\nType: `method`\n\nNačíta všetky súbory `.flow` z adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `directory` | `String` | no | `PATH.root('flowstreams')` | Absolútna cesta. |\n| `callback` | `Function` | no |  | Zavolá sa, keď sú načítané všetky súbory. |\n\nPrečíta každý súbor `.flow` v `directory` (predvolene `flowstreams/` v koreni aplikácie), preskočí názvy s `-bk` alebo `_bk` a každý načíta pomocou `Flow.load()`. Chýbajúci adresár nie je chyba. Framework ju volá pre `/flowstreams/` pri štarte; pre iný adresár ju zavolaj sám.\n\nExample: Iný adresár\n```js\nFlow.init(PATH.root('databases/flows'), function() {\n\tconsole.log(Object.keys(Flow.instances));\n});\n```\n\n### Flow.instances\n\nType: `property`\n\nNačítané inštancie FlowStream podľa ich `id`.\n\nReturns: `Object`\n\nObjekt, v ktorom je každý kľúč `id` schémy a každá hodnota inštancia FlowStream vrátená z `Flow.load()`. Použi ho na posielanie dát do FlowStreamu z trás, schém alebo jobov.\n\nExample: Odoslanie z trasy\n```js\nexports.install = function() {\n\tROUTE('POST /api/orders/', create);\n};\n\nfunction create() {\n\tvar self = this;\n\tvar flow = Flow.instances.orders;\n\tif (!flow) {\n\t\tself.invalid(404);\n\t\treturn;\n\t}\n\tflow.send('a1', self.body, function(err, response) {\n\t\tif (err)\n\t\t\tself.invalid(err);\n\t\telse\n\t\t\tself.json(response.data);\n\t});\n}\n```\n\n### Flow.db\n\nType: `property`\n\nSchémy načítaných FlowStreamov podľa ich `id`.\n\nReturns: `Object`\n\nObsahuje schému odovzdanú do `Flow.load()`; nahradí sa exportovanou schémou vždy, keď sa FlowStream uloží (pozri `Flow.on('save')`).\n\n### Flow.remove(id)\n\nType: `method`\n\nZničí FlowStream a odstráni ho z `Flow.instances` a `Flow.db`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu. |\n\nZastaví všetky inštancie, zatvorí worker, odstráni FlowStream a vyšle `remove` s jeho schémou. Súbor `.flow` sa nezmaže.\n\nExample: Odstránenie\n```js\nFlow.remove('orders');\n```\n\n### Flow.reload(schema)\n\nType: `method`\n\nAktualizuje načítaný FlowStream novou schémou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Nová schéma; `id` vyberá FlowStream. |\n\nReturns: `Boolean` `true`, keď FlowStream existuje.\n\nNájde FlowStream podľa `schema.id`, uloží schému do `Flow.db` a prepíše ňou bežiaci FlowStream (komponenty, dizajn a premenné). Vráti `false`, keď nie je načítaný žiadny FlowStream s týmto `id`. `Flow.load()` ju volá pre `id`, ktoré je už načítané.\n\n### Flow.socket(id, websocket, [check])\n\nType: `method`\n\nPripojí WebSocket kontrolér k FlowStreamu pre dizajnér Flow.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id FlowStreamu (alebo samotný FlowStream). |\n| `websocket` | `WebSocket` | yes |  | WebSocket kontrolér (`this` v trase `SOCKET`). |\n| `check` | `Function` | no |  | `function(client, next)`; zavolaj `next()`, aby si klienta pustil dnu. |\n\nDizajnér komunikuje s FlowStreamom cez tento WebSocket: číta komponenty, dizajn a štatistiky a posiela späť zmeny. `check(client, next)` sa spustí pre každého nového klienta; zavolaj `next()`, aby si ho prijal. Socket sa odpojí, keď sa WebSocket kontrolér zničí. Neznáme `id` socket zničí.\n\nExample: Endpoint pre dizajnér\n```js\nexports.install = function() {\n\tROUTE('+SOCKET /flowstreams/{id}/', designer);\n};\n\nfunction designer(id) {\n\tvar self = this;\n\tFlow.socket(id, self, function(client, next) {\n\t\tif (client.user && client.user.sa)\n\t\t\tnext();\n\t\telse\n\t\t\tclient.close();\n\t});\n}\n```\n\n### Flow.onerror = function(err, source, id, componentid, stack) {}\n\nType: `delegate`\n\nSpracúva chyby všetkých FlowStreamov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | Chyba. |\n| `source` | `String` | yes |  | Kde sa to stalo, napríklad `instance_message` alebo `instance_make`. |\n| `id` | `String` | yes |  | Id inštancie. |\n| `componentid` | `String` | yes |  | Id komponentu. |\n| `stack` | `String` | no |  | Stack, pre FlowStreamy vo workeri. |\n\nPredvolená funkcia vypíše do konzoly blok s názvom FlowStreamu, zdrojom, id inštancie a id komponentu. Vlastnú funkciu priraď pred načítaním FlowStreamov; `this` je inštancia FlowStream (`this.id` je jej id).\n\nExample: Logovanie chýb\n```js\nFlow.onerror = function(err, source, id, componentid) {\n\tconsole.error('FlowStream', this.id, source, id, componentid, err);\n};\n```\n\n### Flow.on('load', function(instance, schema) {})\n\nType: `event`\n\nFlowStream bol načítaný a je pripravený.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Inštancia FlowStream. |\n| `schema` | `Object` | yes |  | Schéma. |\n\nVyšle sa po dokončení `Flow.load()`, pred jeho callbackom.\n\nExample: Logovanie\n```js\nFlow.on('load', function(instance, schema) {\n\tconsole.log('FlowStream ready:', schema.name);\n});\n```\n\n### Flow.on('save', function(schema) {})\n\nType: `event`\n\nFlowStream sa zmenil a jeho schému treba uložiť.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `Object` | yes |  | Exportovaná schéma s `id`, `components`, `design`, `variables` a ďalšími poliami. |\n\nVyšle sa asi päť sekúnd po poslednej zmene: úprave v dizajnéri, `flowstream.variables()`, `flowstream.reconfigure()` alebo `instance.save()`. Framework súbory `.flow` sám nezapisuje; schému ulož tu. Pre schému s `readonly: true` sa nič nevyšle.\n\nExample: Zápis súboru .flow\n```js\nFlow.on('save', function(schema) {\n\tdelete schema.unixsocket;\n\tF.Fs.writeFile(PATH.root('flowstreams/' + schema.id + '.flow'), JSON.stringify(schema, null, '\\t'), NOOP);\n});\n```\n\n### FLOWSTREAM([name], [errorhandler])\n\nType: `method`\n\nVytvorí alebo vráti engine FlowStream podľa názvu, bez workerov a dizajnéra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Názov enginu. |\n| `errorhandler` | `Function` | no | `console.error` | `function(err, source, instance)`. |\n\nReturns: `FlowStream` Engine.\n\nVráti engine, ktorý spúšťa komponenty a správy. Rovnaký `name` vráti rovnaký engine (predvolený názov `default`). Nemá žiadny súbor `.flow`, žiadny worker a žiadne ukladanie; stavia na ňom `Flow.load()`. Hlavné metódy:\n\n- `add(id, html, [callback])` zaregistruje komponent z jeho HTML.\n- `use(design, [callback])` vytvorí inštancie z objektu dizajnu (bez callbacku vráti Promise); `insert(design, [callback])` pridá inštancie; `remove(keys, [callback])` ich odstráni.\n- `trigger('instanceid__inputid', data)` pošle dáta do vstupu; `send('instanceid__outputid', data)` pošle dáta z výstupu.\n- `find(id)` vráti inštanciu; `pause(is)`; `reconfigure(id, config)`; `destroy()`.\n- Udalosti: `message`, `end`, `connect`, `disconnect`, `configure`, `schema`.\n\nExample: Lokálny engine\n```js\nvar flow = FLOWSTREAM('local');\n\nvar print = '<script total>exports.inputs = [{ id: \\'input\\', name: \\'Input\\' }]; exports.make = function(instance) { instance.message = function($) { console.log($.data); $.destroy(); }; };</script>';\n\nflow.add('print', print, function() {\n\tflow.use({ p1: { component: 'print', config: {} } }, function() {\n\t\tflow.trigger('p1__input', { hello: 'world' });\n\t});\n});\n```\n\n### flowstream.send(path, data, [callback])\n\nType: `method`\n\nPošle dáta jednej inštancii a počká na koniec správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cieľová inštancia. |\n| `data` | `Object` | yes |  | Dáta správy. |\n| `callback` | `Function` | no |  | `function(err, response)`. |\n\n`path` je id inštancie, `@componentid` (prvá inštancia komponentu) alebo `#name` (prvá inštancia, ktorej komponent má tento názov). Pridaj `/inputid`, aby si nastavil `$.input`. Dáta idú do `instance.message` cieľa, takže ten musí definovať `instance.message`.\n\nCallback sa spustí, keď sa správa a všetky jej kópie zničia. Dostane `{ error, repo, data, count, cloned, duration, meta: { id, component } }`, kde `data` sú dáta poslednej správy. Neznámy cieľ zavolá `callback(404)`.\n\nExample: Čakanie na výsledok\n```js\nFlow.instances.orders.send('a1', { name: 'Peter' }, function(err, response) {\n\tconsole.log(response.data, response.duration + ' ms');\n});\n```\n\n### flowstream.exec(opt, [callback])\n\nType: `method`\n\nPošle správu jednej alebo viacerým inštanciám s repozitárom, premennými a časovým limitom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Voľby. |\n| `callback` | `Function` | no |  | `function(err, response)`; `response` má `uid`, `ref`, `error`, `repo`, `data`, `count`, `cloned`, `duration`, `meta`. |\n\n`opt.id` je id inštancie, `@componentid` (všetky inštancie komponentu) alebo `#name` (všetky inštancie s názvom komponentu). Každý cieľ musí definovať `instance.message`. Callback sa spustí pre každý cieľ, keď jeho správa skončí; neznámy cieľ dá `404`.\n\n- `opt.data` {Object}: dáta (predvolene `{}`).\n- `opt.repo` {Object}: počiatočné `$.repo`.\n- `opt.vars` {Object}: počiatočné `$.vars`.\n- `opt.timeout` {Number}: ms; potom správa skončí s `error` `408`.\n- `opt.uid`, `opt.ref`: vrátia sa späť v odpovedi.\n\nExample: S časovým limitom\n```js\nFlow.instances.orders.exec({ id: '@uppercase', data: { name: 'Peter' }, timeout: 5000 }, function(err, response) {\n\tif (err === 408)\n\t\tconsole.log('Timeout');\n});\n```\n\n### flowstream.trigger(id, data)\n\nType: `method`\n\nZavolá handler `instance.trigger` inštancií.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Cieľ. |\n| `data` | `Object` | no |  | Odovzdá sa do `instance.trigger(data)`. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\n`id` je id inštancie, `@componentid` (všetky inštancie komponentu) alebo `#name`. Zavolajú sa iba inštancie, ktoré definujú `instance.trigger`; kým je FlowStream pozastavený, nič sa nedeje.\n\nExample: Spustenie všetkých časovačov\n```js\nFlow.instances.orders.trigger('@timer', { manual: true });\n```\n\n### flowstream.pause([is])\n\nType: `method`\n\nPozastaví alebo obnoví FlowStream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `is` | `Boolean` | no |  | `true` pozastaví, `false` obnoví. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\nPozastavený FlowStream zahadzuje nové správy a zavolá `instance.pause(is)` každej inštancie, ktorá ho definuje. Bez argumentu prepne stav.\n\nExample: Pozastavenie\n```js\nFlow.instances.orders.pause(true);\n```\n\n### flowstream.reconfigure(id, config)\n\nType: `method`\n\nZmení konfiguráciu jednej inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id inštancie. |\n| `config` | `Object` | yes |  | Kľúče na zmenu. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\nKľúče z `config` sa zlúčia do konfigurácie inštancie, potom sa zavolá `instance.configure(config)` a FlowStream sa uloží.\n\nExample: Zmena poľa\n```js\nFlow.instances.orders.reconfigure('a1', { field: 'email' });\n```\n\n### flowstream.variables(variables)\n\nType: `method`\n\nNahradí premenné FlowStreamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `variables` | `Object` | yes |  | Nové premenné. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\nZavolá `instance.variables(variables)` a `instance.vary('variables')` každej inštancie, ktorá ich definuje, a uloží FlowStream.\n\nExample: Nastavenie premenných\n```js\nFlow.instances.orders.variables({ currency: 'USD', api: 'https://api.example.com' });\n```\n\n### flowstream.components(callback)\n\nType: `method`\n\nPrečíta zaregistrované komponenty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, components)`. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\nCallback dostane pole s `id`, `name`, `type`, `icon`, `color`, `group`, `version`, `author`, `config`, `inputs`, `outputs`, `readme`, `html`, `css`, `js` a `settings` každého komponentu.\n\nExample: Výpis názvov\n```js\nFlow.instances.orders.components(function(err, components) {\n\tconsole.log(components.map(c => c.name));\n});\n```\n\n### flowstream.add(id, html, [callback])\n\nType: `method`\n\nZaregistruje alebo nahradí komponent za behu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id komponentu. |\n| `html` | `String` | yes |  | Zdrojový kód komponentu. |\n| `callback` | `Function` | no |  | `function(err)`. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\n`html` je súbor komponentu s blokom `<script total>`. Existujúce inštancie komponentu sa vytvoria znova s novým kódom. Na odregistrovanie komponentu a odstránenie jeho inštancií použi `flowstream.rem(id, [callback])`.\n\nExample: Pridanie komponentu\n```js\nvar html = F.Fs.readFileSync(PATH.root('components/uppercase.html'), 'utf8');\nFlow.instances.orders.add('uppercase', html, function(err) {\n\terr && console.error(err);\n});\n```\n\n### flowstream.export(callback)\n\nType: `method`\n\nExportuje aktuálnu schému FlowStreamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | yes |  | `function(err, schema)`. |\n\nReturns: `FlowStreamInstance` Inštancia.\n\nCallback dostane schému vo formáte `.flow`: `components` (surové HTML), `design`, `variables`, `sources`, `paused` a ďalšie polia načítanej schémy.\n\nExample: Záloha\n```js\nFlow.instances.orders.export(function(err, schema) {\n\tF.Fs.writeFile(PATH.root('flowstreams/orders_bk.flow'), JSON.stringify(schema), NOOP);\n});\n```\n\n### flowstream.stats\n\nType: `property` · Since: `0.0.96`\n\nŠtatistiky FlowStream.\n\nReturns: `Object`\n\nObsahuje `messages` (odoslané správy), `pending` (rozpracované správy), `minutes` (minúty behu), `mm` (správy za poslednú minútu), `errors` (počet posledných chýb, najviac 10), `memory` a `paused`. `memory` (heap v bajtoch) sa meria len vo workeri alebo podprocese. Pre FlowStream vo workeri objekt prichádza z workera približne každých 15 sekúnd a obsahuje aj `pid`; pred prvým hlásením je `undefined`.\n\nExample: Čítanie štatistík\n```js\nvar stats = Flow.instances.orders.stats;\nconsole.log(stats.messages, stats.pending);\n```\n\n### flowstream.remove()\n\nType: `method`\n\nZničí tento FlowStream a odstráni ho z `Flow`.\n\nTo isté ako `Flow.remove(flowstream.id)`. `flowstream.destroy()` iba zastaví FlowStream a jeho worker; zostane v `Flow.instances`.\n\nExample: Odstránenie\n```js\nFlow.instances.orders.remove();\n```\n\n### exports.make = function(instance, config) {}\n\nType: `method`\n\nVytvorí jednu inštanciu komponentu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `instance` | `Object` | yes |  | Nová inštancia. |\n| `config` | `Object` | yes |  | Konfigurácia inštancie. |\n\nKomponent je HTML súbor, ktorého blok `<script total>` je serverový kód; `exports` je komponent. `make` sa spustí pre každú inštanciu dizajnu, pričom `this` aj `instance` sú inštancia a `config` je jej konfigurácia (`exports.config` zlúčené s `config` dizajnu). Tu priraď handlery, napríklad `instance.message`.\n\nOstatné bloky súboru sú pre dizajnér: `<readme>`, `<settings>`, `<style>`, `<script>` (klientsky kód), `<body>` a `<template>`.\n\nExample: Kompletný komponent\n```html\n<script total>\n\n\texports.name = 'Uppercase';\n\texports.icon = 'ti ti-font';\n\texports.config = { field: 'name' };\n\texports.inputs = [{ id: 'input', name: 'Input' }];\n\texports.outputs = [{ id: 'output', name: 'Output' }];\n\n\texports.make = function(instance, config) {\n\t\tinstance.message = function($) {\n\t\t\tvar data = $.data;\n\t\t\tif (data && typeof(data[config.field]) === 'string')\n\t\t\t\tdata[config.field] = data[config.field].toUpperCase();\n\t\t\t$.send('output', data);\n\t\t};\n\t};\n\n</script>\n\n<readme>\nConverts one field of the incoming object to upper case.\n</readme>\n```\n\n### exports.inputs = [{ id: 'input', name: 'Input' }]\n\nType: `property`\n\nVstupy a výstupy komponentu.\n\nReturns: `Array`\n\n`exports.inputs` a `exports.outputs` sú polia `{ id, name }`. Spojenia v dizajne odkazujú na tieto id: `connections: { outputid: [{ id: 'instanceid', index: 'inputid' }] }`. Spojenie do vstupu, ktorý cieľový komponent nedeklaruje, sa odstráni. Komponent bez vstupov iba posiela (napríklad časovač); komponent bez výstupov správy ukončuje.\n\nExample: Dva výstupy\n```js\nexports.inputs = [{ id: 'input', name: 'Input' }];\nexports.outputs = [{ id: 'ok', name: 'Valid' }, { id: 'error', name: 'Invalid' }];\n```\n\n### exports.config = {}\n\nType: `property`\n\nPredvolená konfigurácia každej inštancie.\n\nReturns: `Object`\n\nKópia sa zlúči s `config` inštancie v dizajne a odovzdá sa do `exports.make()` ako `config`.\n\nExample: Predvolené hodnoty\n```js\nexports.config = { field: 'name', timeout: 5000 };\n```\n\n### exports.name = 'Uppercase'\n\nType: `property`\n\nNázov a ďalšie metadáta komponentu.\n\nReturns: `String`\n\nMetadáta pre dizajnér a pre `flowstream.components()`: `exports.name`, `exports.icon`, `exports.color`, `exports.group`, `exports.type`, `exports.version`, `exports.author` a `exports.meta`. Selektor `#name` v `send()`, `exec()` a `trigger()` zodpovedá `exports.name`. Id komponentu je kľúč v objekte `components` schémy.\n\nExample: Metadáta\n```js\nexports.name = 'Uppercase';\nexports.icon = 'ti ti-font';\nexports.color = '#5D9CEC';\nexports.group = 'Text';\nexports.version = '1';\nexports.author = 'Total.js';\n```\n\n### exports.npm = ['package']\n\nType: `property`\n\nNPM balíky, ktoré komponent potrebuje.\n\nReturns: `Array`\n\nBalíky sa nainštalujú pomocou `NPMINSTALL()` pred registráciou komponentu.\n\nExample: Použitie balíka\n```js\nexports.npm = ['qrcode'];\n\nexports.make = function(instance) {\n\tinstance.message = function($) {\n\t\tvar QR = require('qrcode');\n\t\tQR.toDataURL($.data.text, function(err, url) {\n\t\t\t$.send('output', url);\n\t\t});\n\t};\n};\n```\n\n### instance.message = function($) {}\n\nType: `delegate`\n\nPrijíma správy, ktoré prídu na vstupy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Message` | yes |  | Správa. |\n\n`$` je správa; `$.input` je id vstupu. Namiesto jedného handlera môžeš pre jeden vstup definovať `instance.message_INPUTID`. Správa, ktorú žiadny handler neprevezme, sa zničí. Každá správa musí skončiť: pošli ju ďalej pomocou `$.send()` alebo zavolaj `$.destroy()`.\n\nExample: Dva vstupy\n```js\nexports.make = function(instance) {\n\n\tinstance.message_a = function($) {\n\t\t$.send('output', { from: 'A', data: $.data });\n\t};\n\n\tinstance.message_b = function($) {\n\t\t$.destroy();\n\t};\n};\n```\n\n### instance.send(output, data, [controller])\n\nType: `method`\n\nPošle dáta z výstupu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | yes |  | Id výstupu. |\n| `data` | `Object` | yes |  | Dáta alebo správa. |\n| `controller` | `Controller` | no |  | Sprístupní `$.user`, `$.body` a ďalšie vlastnosti požiadavky. |\n\nReturns: `Number` Počet odoslaných správ.\n\nVytvorí novú správu pre každé spojenie `output`. Keď je `data` správa, jej kópie si ponechajú repozitár a callbacky tejto správy. Vráti počet odoslaných správ (`0`, keď výstup nemá spojenie alebo je FlowStream pozastavený).\n\nExample: Časovač\n```js\nexports.outputs = [{ id: 'output', name: 'Tick' }];\n\nexports.make = function(instance, config) {\n\tvar timer = setInterval(function() {\n\t\tinstance.send('output', { ts: new Date() });\n\t}, config.interval || 5000);\n\n\tinstance.close = function() {\n\t\tclearInterval(timer);\n\t};\n};\n```\n\n### instance.newmessage([data])\n\nType: `method`\n\nVytvorí novú správu, ktorú vlastní táto inštancia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Dáta. |\n\nReturns: `Message` Správa.\n\nPošli ju pomocou `$.send(output)`. Na rozdiel od `instance.send()` môžeš pred odoslaním pridať listenery a repozitár.\n\nExample: Čakanie na koniec\n```js\nvar msg = instance.newmessage({ id: 1 });\nmsg.repo.started = Date.now();\nmsg.on('end', function(msg) {\n\tinstance.status('Last run: ' + (Date.now() - msg.repo.started) + ' ms');\n});\nmsg.send('output');\n```\n\n### instance.status(data, [delay])\n\nType: `method`\n\nZobrazí stav inštancie v dizajnéri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object/String` | yes |  | Stav. |\n| `delay` | `Number` | no |  | Oneskorenie v ms. |\n\n`data` je ľubovoľná hodnota, ktorú dokáže vykresliť dizajn komponentu (`<body>`, `<script>`). S `delay` (ms) sa stav pošle raz po tomto čase, čo zabráni zahlteniu dizajnéra. Bez argumentov sa znova pošle posledný stav.\n\nExample: Počítanie správ\n```js\nvar count = 0;\ninstance.message = function($) {\n\tcount++;\n\tinstance.status({ count: count }, 1000);\n\t$.send('output');\n};\n```\n\n### instance.dashboard(data)\n\nType: `method`\n\nPošle dáta na dashboard dizajnéra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Dáta pre dashboard. |\n\nAko `instance.status()`, ale pre widgety dashboardu. Posledná hodnota sa uchová a pri volaní bez argumentov sa pošle znova.\n\nExample: Teplota\n```js\ninstance.dashboard({ temperature: 21.5 });\n```\n\n### instance.throw(err)\n\nType: `method`\n\nNahlási chybu inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error/String` | yes |  | Chyba. |\n\nChyba sa uloží medzi posledných desať chýb FlowStreamu (počítaných v `stats.errors`), zobrazí sa v dizajnéri a odovzdá sa do `Flow.onerror`. `$.throw(err)` robí to isté a navyše nastaví `$.error`. Ani jedno správu neukončí.\n\nExample: Neplatné dáta\n```js\ninstance.message = function($) {\n\tif (!$.data.email) {\n\t\t$.throw('Missing email');\n\t\t$.destroy();\n\t\treturn;\n\t}\n\t$.send('output');\n};\n```\n\n### instance.config\n\nType: `property`\n\nKonfigurácia inštancie.\n\nReturns: `Object`\n\nPredvolené `exports.config` zlúčené s `config` dizajnu. Zmena z dizajnéra alebo cez `flowstream.reconfigure()` aktualizuje ten istý objekt a zavolá `instance.configure(config)`.\n\nExample: Čítanie hodnoty\n```js\nvar field = instance.config.field;\n```\n\n### instance.configure = function(config) {}\n\nType: `delegate`\n\nSpustí sa, keď sa zmení konfigurácia inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `config` | `Object` | yes |  | Nová konfigurácia. |\n\nZavolá sa potom, čo dizajnér, nový dizajn alebo `flowstream.reconfigure()` zmenili `instance.config`. Pri prvej konfigurácii sa nevolá; na to použi `exports.make()`.\n\nExample: Reštart časovača\n```js\nvar timer;\n\ninstance.configure = function(config) {\n\ttimer && clearInterval(timer);\n\ttimer = setInterval(() => instance.send('output', {}), config.interval || 5000);\n};\n\ninstance.configure(instance.config);\n```\n\n### instance.close = function(removed) {}\n\nType: `delegate`\n\nSpustí sa, keď sa inštancia zastavuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `removed` | `Boolean` | no |  | `true`, keď sa inštancia odstraňuje, nielen znova vytvára. |\n\nZavolá sa, keď sa inštancia odstráni z dizajnu, jej komponent sa nahradí alebo odstráni, alebo sa FlowStream uvoľní. Tu zruš časovače a zatvor spojenia. Ďalšie voliteľné handlery: `instance.init()` (raz, po vytvorení dizajnu), `instance.refresh()` (po každej zmene dizajnu), `instance.pause(is)` a `instance.variables(variables)`.\n\nExample: Upratanie\n```js\ninstance.close = function() {\n\tclearInterval(timer);\n};\n```\n\n### instance.trigger = function(data) {}\n\nType: `delegate`\n\nSpustí sa, keď je inštancia spustená triggerom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | no |  | Dáta triggeru. |\n\nVolá ho `flowstream.trigger()` a tlačidlo trigger v dizajnéri. Typicky spúšťa novú správu.\n\nExample: Spustenie na požiadanie\n```js\ninstance.trigger = function() {\n\tinstance.send('output', { ts: new Date() });\n};\n```\n\n### instance.replace(str, [data], [encoding])\n\nType: `method`\n\nNahradí zástupné znaky `{key}` premennými.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Text. |\n| `data` | `Object` | no |  | Ďalšie hodnoty. |\n| `encoding` | `String/Function` | no |  | Ako zakódovať každú hodnotu. |\n\nReturns: `String` Text s hodnotami.\n\nKaždý `{key}` (alebo `{{key}}`) sa hľadá v premenných FlowStreamu, potom vo `variables2`, potom v tajomstvách, potom v `{hostname}` a potom v `data` (fungujú aj vnorené kľúče ako `{user.name}`). Neznáme kľúče zostanú, ako sú. `encoding` je `'url'`, `'json'`, `'querify'` alebo `function(value, key)`. Objekt ako `str` nahradí všetky svoje reťazcové hodnoty.\n\nExample: URL\n```js\nvar url = instance.replace('{api}/orders/{id}/', { id: 15 }, 'url');\n```\n\n### instance.save()\n\nType: `method`\n\nUloží zmeny inštancie a prekreslí ju v dizajnéri.\n\nPouži ju, keď v kóde zmeníš `instance.config` alebo iné vlastnosti dizajnu. FlowStream potom vyšle `save`.\n\nExample: Zapamätanie hodnoty\n```js\ninstance.config.last = Date.now();\ninstance.save();\n```\n\n### instance.main\n\nType: `property`\n\nEngine FlowStream, ktorý spúšťa inštanciu.\n\nReturns: `FlowStream`\n\nUžitočné vlastnosti: `instance.main.variables` (premenné), `instance.main.paused`, `instance.main.stats` a `instance.main.id`. `instance.instances` obsahuje všetky inštancie dizajnu a `instance.components` všetky zaregistrované komponenty. `instance.id` je id inštancie, `instance.component` id komponentu a `instance.module` komponent.\n\nExample: Čítanie premennej\n```js\nvar currency = instance.main.variables.currency;\n```\n\n### $.data\n\nType: `property`\n\nDáta správy.\n\nReturns: `Object`\n\nAkákoľvek hodnota. Každé spojenie dostane vlastnú kópiu objektov a bufferov, keď je zapnuté klonovanie (predvolene). Vlastnosti požiadavky `$.user`, `$.body`, `$.query`, `$.params`, `$.headers`, `$.ip` a `$.files` existujú len vtedy, keď bola správa spustená s kontrolérom.\n\nExample: Čítanie a zmena\n```js\ninstance.message = function($) {\n\t$.data.total = $.data.price * $.data.count;\n\t$.send('output');\n};\n```\n\n### $.send([output], [data], [clone])\n\nType: `method`\n\nPošle správu ďalej z výstupu aktuálnej inštancie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `output` | `String` | no |  | Id výstupu. |\n| `data` | `Object` | no |  | Nové dáta. |\n| `clone` | `Boolean` | no | `cloning` | Klonuje dáta pre každé spojenie. |\n\nReturns: `Number` Počet odoslaných správ.\n\nBez `output` sa pošle zo všetkých výstupov. Bez `data` si ponechá svoje dáta. Keď k výstupu nie je nič pripojené, správa sa zničí. `clone` prepíše pre toto volanie voľbu `cloning` FlowStreamu. Vráti počet odoslaných správ.\n\nExample: Smerovanie podľa podmienky\n```js\ninstance.message = function($) {\n\t$.send($.data.valid ? 'ok' : 'error');\n};\n```\n\n### $.destroy()\n\nType: `method`\n\nUkončí správu.\n\nZavolaj ju v poslednom komponente reťazca. Keď skončí posledná kópia správy, vyšle sa `end` a spustí sa callback `flowstream.send()` alebo `flowstream.exec()`. `$.end()` je alias.\n\nExample: Posledný komponent\n```js\ninstance.message = function($) {\n\tconsole.log($.data);\n\t$.destroy();\n};\n```\n\n### $.repo\n\nType: `property`\n\nObjekt zdieľaný správou a všetkými jej kópiami.\n\nReturns: `Object`\n\nPouži ho na odovzdávanie hodnôt pozdĺž celého reťazca bez zmeny `$.data`. Vráti sa ako `repo` do callbacku `flowstream.send()` a `flowstream.exec()`. `$.vars` je ďalší zdieľaný objekt.\n\nExample: Uchovanie hodnoty\n```js\n// first component\n$.repo.started = Date.now();\n$.send('output');\n\n// last component\n$.data.duration = Date.now() - $.repo.started;\n$.destroy();\n```\n\n### $.variables(str, [data], [encoding])\n\nType: `method`\n\nNahradí zástupné znaky `{key}` premennými a hodnotami správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String/Object` | yes |  | Text. |\n| `data` | `Object` | no | `the message` | Hodnoty. |\n| `encoding` | `String/Function` | no |  | `url`, `json`, `querify` alebo funkcia. |\n\nReturns: `String`\n\nTo isté ako `instance.replace()`, ale bez `data` sa použije samotná správa, takže `{data.id}` číta `$.data.id`. `$.replace()` je alias.\n\nExample: Zostavenie URL\n```js\nvar url = $.variables('{api}/users/{data.id}/', null, 'url');\n```\n\n### $.on(name, callback)\n\nType: `method`\n\nPočúva udalosti správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Udalosť. |\n| `callback` | `Function` | yes |  | `function(msg)`. |\n\nReturns: `Message` Správa.\n\nUdalosti: `end` (skončila posledná kópia), `destroy` (v rovnakom okamihu), `terminate` (skončila ľubovoľná kópia), `message` (kópia dorazila k inštancii), `timeout`. Listenery zdieľajú všetky kópie. Existujú aj `$.once()` a `$.off()`.\n\nExample: Meranie reťazca\n```js\nvar msg = instance.newmessage(data);\nmsg.on('end', function(msg) {\n\tconsole.log('Done', msg.data);\n});\nmsg.send('output');\n```\n\n### $.timeout([callback], time)\n\nType: `method`\n\nObmedzí, ako dlho môže trvať každý ďalší krok správy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function` | no |  | `function(msg)`. |\n| `time` | `Number` | yes |  | Milisekundy. |\n\nReturns: `Message` Správa.\n\nKaždá kópia odoslaná po tomto volaní skončí s `$.error = 408`, keď nie je spracovaná do `time` ms; `callback` sa zavolá s touto kópiou. `$.totaltimeout([callback], time)` namiesto toho obmedzí celý reťazec.\n\nExample: Päť sekúnd pre celý reťazec\n```js\n$.totaltimeout(function(msg) {\n\tinstance.throw('Timeout');\n}, 5000);\n$.send('output');\n```\n","entries":[{"type":"config","name":"CONF.directory_flowstreams","signature":"CONF.directory_flowstreams = '/flowstreams/'","since":"","deprecated":false},{"type":"config","name":"FlowStream schema","signature":"{ id, name, components, design, variables, worker, ... }","since":"","deprecated":false},{"type":"method","name":"Flow.load()","signature":"Flow.load(schema, [callback])","since":"","deprecated":false},{"type":"method","name":"Flow.init()","signature":"Flow.init([directory], [callback])","since":"","deprecated":false},{"type":"property","name":"Flow.instances","signature":"Flow.instances","since":"","deprecated":false},{"type":"property","name":"Flow.db","signature":"Flow.db","since":"","deprecated":false},{"type":"method","name":"Flow.remove()","signature":"Flow.remove(id)","since":"","deprecated":false},{"type":"method","name":"Flow.reload()","signature":"Flow.reload(schema)","since":"","deprecated":false},{"type":"method","name":"Flow.socket()","signature":"Flow.socket(id, websocket, [check])","since":"","deprecated":false},{"type":"delegate","name":"Flow.onerror","signature":"Flow.onerror = function(err, source, id, componentid, stack) {}","since":"","deprecated":false},{"type":"event","name":"Flow.on('load')","signature":"Flow.on('load', function(instance, schema) {})","since":"","deprecated":false},{"type":"event","name":"Flow.on('save')","signature":"Flow.on('save', function(schema) {})","since":"","deprecated":false},{"type":"method","name":"FLOWSTREAM()","signature":"FLOWSTREAM([name], [errorhandler])","since":"","deprecated":false},{"type":"method","name":"flowstream.send()","signature":"flowstream.send(path, data, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.exec()","signature":"flowstream.exec(opt, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.trigger()","signature":"flowstream.trigger(id, data)","since":"","deprecated":false},{"type":"method","name":"flowstream.pause()","signature":"flowstream.pause([is])","since":"","deprecated":false},{"type":"method","name":"flowstream.reconfigure()","signature":"flowstream.reconfigure(id, config)","since":"","deprecated":false},{"type":"method","name":"flowstream.variables()","signature":"flowstream.variables(variables)","since":"","deprecated":false},{"type":"method","name":"flowstream.components()","signature":"flowstream.components(callback)","since":"","deprecated":false},{"type":"method","name":"flowstream.add()","signature":"flowstream.add(id, html, [callback])","since":"","deprecated":false},{"type":"method","name":"flowstream.export()","signature":"flowstream.export(callback)","since":"","deprecated":false},{"type":"property","name":"flowstream.stats","signature":"flowstream.stats","since":"0.0.96","deprecated":false},{"type":"method","name":"flowstream.remove()","signature":"flowstream.remove()","since":"","deprecated":false},{"type":"method","name":"exports.make()","signature":"exports.make = function(instance, config) {}","since":"","deprecated":false},{"type":"property","name":"exports.inputs","signature":"exports.inputs = [{ id: 'input', name: 'Input' }]","since":"","deprecated":false},{"type":"property","name":"exports.config","signature":"exports.config = {}","since":"","deprecated":false},{"type":"property","name":"exports.name","signature":"exports.name = 'Uppercase'","since":"","deprecated":false},{"type":"property","name":"exports.npm","signature":"exports.npm = ['package']","since":"","deprecated":false},{"type":"delegate","name":"instance.message","signature":"instance.message = function($) {}","since":"","deprecated":false},{"type":"method","name":"instance.send()","signature":"instance.send(output, data, [controller])","since":"","deprecated":false},{"type":"method","name":"instance.newmessage()","signature":"instance.newmessage([data])","since":"","deprecated":false},{"type":"method","name":"instance.status()","signature":"instance.status(data, [delay])","since":"","deprecated":false},{"type":"method","name":"instance.dashboard()","signature":"instance.dashboard(data)","since":"","deprecated":false},{"type":"method","name":"instance.throw()","signature":"instance.throw(err)","since":"","deprecated":false},{"type":"property","name":"instance.config","signature":"instance.config","since":"","deprecated":false},{"type":"delegate","name":"instance.configure","signature":"instance.configure = function(config) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.close","signature":"instance.close = function(removed) {}","since":"","deprecated":false},{"type":"delegate","name":"instance.trigger","signature":"instance.trigger = function(data) {}","since":"","deprecated":false},{"type":"method","name":"instance.replace()","signature":"instance.replace(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"instance.save()","signature":"instance.save()","since":"","deprecated":false},{"type":"property","name":"instance.main","signature":"instance.main","since":"","deprecated":false},{"type":"property","name":"$.data","signature":"$.data","since":"","deprecated":false},{"type":"method","name":"$.send()","signature":"$.send([output], [data], [clone])","since":"","deprecated":false},{"type":"method","name":"$.destroy()","signature":"$.destroy()","since":"","deprecated":false},{"type":"property","name":"$.repo","signature":"$.repo","since":"","deprecated":false},{"type":"method","name":"$.variables()","signature":"$.variables(str, [data], [encoding])","since":"","deprecated":false},{"type":"method","name":"$.on()","signature":"$.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"$.timeout()","signature":"$.timeout([callback], time)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm931ci61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() and every method of the SQL QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() and every method of the SQL QueryBuilder.\n\nThe SQL QueryBuilder describes a query with chained methods and passes it to the adapter registered with `NEWDB()`. The guide [QueryBuilder](../../guides/querybuilder/) explains how to use it with examples; this page is the exact reference.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegisters or removes the adapter of an SQL connection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | The connection name. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, see the adapter function. Leave it out to remove the adapter. |\n\nReturns: `undefined`\n\nRegisters `fn` as the adapter for the connection `name` (default `default`). The name `*` is a fallback used for every connection without its own adapter. Calling `NEWDB(name)` without a function removes the adapter. When a query runs and no adapter exists, it fails with the error `Database is not initialized`.\n\nThe adapter is called with `this` set to the internal query object and receives the adapter options (see *Adapter options*) and a callback.\n\nExample: A default and a named adapter\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nThe function that runs a query against the database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | The description of the query. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nYou write the adapter and register it with `NEWDB()`. It reads `filter` (see *Adapter options*), builds and runs the SQL, and calls `callback(err, response)` exactly once.\n\nWhat `response` must contain depends on `filter.exec`: an array for `find`, a row or an array for `read` and `check`, `{ items, count }` for `list`, a number for `count`, and what you consider useful for the rest. An `err` stops a `DB()` chain and goes to the callbacks of the query.\n\nExample: Skeleton of an adapter\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nThe description of a query that the adapter receives.\n\nReturns: `Object`\n\n| Field | Type | Meaning |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` or `drop` |\n| `table` | String | The table name, without the connection prefix (empty for `query`) |\n| `filter` | Array | The conditions in their order (see below) |\n| `fields` | Array | The column names from `fields()`, or empty for all |\n| `sort` | Array | Items in the form `name_asc` or `name_desc` |\n| `take`, `skip` | Number | Limit and offset. `list` starts with `take: 100, skip: 0` |\n| `first` | Boolean | `true` for `read`, `check` and `first()`: one row is expected |\n| `payload` | Object | The data of `insert` and `update` |\n| `upsert` | Boolean | `true` for an update with upsert |\n| `returning` | Array | The columns from `returning()` |\n| `query`, `params` | String, Array/Object | The SQL and the arguments of `query()` |\n| `scalar` | Object | `{ type, key, key2 }` from `scalar()` |\n| `command` | String | The name from `command()` |\n| `language` | String | The value from `language()` |\n| `primarykey` | String | The value from `builder.primarykey(name)` |\n| `schema` | String | The value from `builder.schema(name)` |\n| `checksum` | String | A hash of the shape of the filters (without the values), useful as a cache key of prepared statements |\n| `debug` | Boolean | `true` after `debug()` |\n\nThe items of `filter.filter` have a `type`: `where` (`name`, `comparer`, `value`), `in` and `notin` (`name`, `value` array), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` and `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: an array of items), `query` (`value`: raw SQL), `join` (`name`, `table`, `join`, `on`) and `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nCreates a controller that runs several queries one after another.\n\nReturns: `QueryBuilderDB` The controller.\n\nReturns a new controller (alias `DATABASE()`). Each method you call on it adds a query to a queue. The queue starts on the next tick and runs the queries in order. After the last one, the callback of the controller (`callback()`, `promise()` or `done()`) receives the error or the response. An error stops the queue.\n\nBy default each query replaces the response; use `builder.set(name)` to collect several responses, and `builder.nobind()` to keep a query out of the response. A query added from a callback of a previous query is run too.\n\nExample: Two queries in a row\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nA global controller for single queries.\n\nReturns: `QueryBuilderDB`\n\n`DATA` has the same query methods as `DB()` (`find`, `read`, `insert`...), but each query runs on its own as soon as it is created, without a queue. It is faster than `DB()` because no controller is created.\n\nRead the result with the methods of the builder: `callback()`, `promise()`, `done()`, `data()` or `fail()`. Do not use `set()` with `DATA`, and do not use the controller methods `DATA.callback()`, `DATA.promise()` and `DATA.done()`: `DATA` is shared by the whole app.\n\nExample: A single query\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nFinds rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `find` query (alias `all()`). The response is an array of rows.\n\nExample: Find\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nFinds one page of rows with counts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `list` query with `take: 100` and `skip: 0`. The adapter returns `{ items, count }`, where `count` is the number of all matching rows. The framework adds `page`, `limit` and `pages` (the number of pages).\n\nExample: A page\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nReads one row.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `read` query (alias `one()`) with `take: 1`. When the adapter returns an array, the response is its first item or `null`. Combine it with `error('404')`.\n\nExample: Read\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nChecks whether a row exists.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `check` query with `take: 1`. The adapter usually selects only one column. Use it with `error()` to stop on a missing row, or `error(err, true)` to stop on an existing one.\n\nExample: Unique e-mail\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nRuns an aggregation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n| `type` | `String` | yes |  | The kind of aggregation. |\n| `key` | `String` | no | `'*'` | The column. |\n| `key2` | `String` | no |  | A second column, for example for grouping. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `scalar` query. The adapter receives `filter.scalar = { type, key, key2 }`. The meaning of `type` (for example `sum`, `min`, `max`, `avg`, `group`) depends on the adapter.\n\n`db.count(table)` starts a `count` query; the response is the number the adapter returns.\n\nExample: Sum\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Count\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nInserts a row.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n| `data` | `Object` | yes |  | The row. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts an `insert` query (alias `ins()`). `data` goes to the adapter as `filter.payload`.\n\nExample: Insert\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nUpdates rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n| `data` | `Object` | yes |  | The changed columns. |\n| `upsert` | `Boolean` | no | `false` | Insert the data when nothing was updated. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts an `update` query (aliases `modify()`, `mod()`, `upd()`). `data` goes to the adapter as `filter.payload`. With `upsert`, when the adapter returns an empty response (or nothing from `returning`), the framework calls the function of `builder.insert()`, clears the filters and runs the data as an `insert`.\n\nExample: Update\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nRemoves rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `remove` query (alias `rem()`).\n\nExample: Remove\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nRuns your own SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | The connection name. |\n| `sql` | `String` | yes |  | The SQL. |\n| `params` | `Array|Object` | no |  | The arguments for the placeholders of your driver. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nSends `sql` as `filter.query` and `params` as `filter.params` to the adapter of `conn`. When the second argument is an array or an object, it is taken as `params` and the connection is `default`. Filters added to the builder (for example `where()`) are passed in `filter.filter` as well.\n\n`db.command(table, name)` sends `exec: 'command'` with `filter.command = name`, for operations of your adapter that the other methods do not cover.\n\nExample: Raw SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Command\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nRemoves all rows of a table.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | The table name. A prefix `name/` chooses the connection, for example `logs/tbl_request`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nStarts a `truncate` query (alias `clear()`). `db.drop(table)` starts a `drop` query in the same way, to remove the table itself.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nCreates a query from a prepared object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | The connection name. |\n| `options` | `Object` | yes |  | The prepared query. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nCreates a builder from the fields of `options`: `table`, `exec`, `fields` (array), `sort` (array), `skip`, `take`, `query`, `payload`, `upsert`, `returning` and `filter` (an array of filter items). Unlike the other methods, `table` has no connection prefix; pass the connection as `conn`. Put all conditions into `options.filter`.\n\n`db.exec(options, callback)` runs a prepared object at once: it starts the query named by `options.exec` on `options.table` (for `exec: 'query'`, `options.query` holds the SQL), copies the other fields to the adapter options and calls `callback(err, response)`. It returns nothing.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nSets the final callback of a DB() controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` or `$`. |\n\nReturns: `QueryBuilderDB`\n\nCalled after the last query, or after the first error, with `(err, response)`. Accepts `$` too, then it uses `$.callback`. Use it only on `DB()`.\n\nTwo other ways to end a `DB()` controller: `db.promise([$])` returns a promise of the final response (with `$`, an error goes to `$.invalid()` and the promise stays pending; without it, the promise is rejected), and `db.done($, [fn])` sends an error to `$.invalid(err)` and otherwise calls `fn(response)`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nCalls fn on success, $.invalid() on an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The options of a schema or an operation. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nSets the final callback of a `DB()` controller: an error goes to `$.invalid(err)`, otherwise `fn(response)` is called.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nTurns on debug mode for the next queries.\n\nReturns: `QueryBuilderDB`\n\nSets `filter.debug = true` for queries created on this controller after the call, so the adapter can print the SQL. On one query, use `builder.debug()` instead.\n\n`builder.debug()` sets the flag on one query only.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Debug\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nSets the default prefix and skip value of builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Text put before the language. |\n| `skip` | `String` | yes |  | A language that produces an empty value (the default language). |\n\nReturns: `QueryBuilderDB`\n\nThe values are global: they apply to every later `builder.language()` call in the app, whether on `DB()` or `DATA`. The defaults are `prefix: ''` and `skip: '_'`.\n\nExample: Defaults\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAdds a condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` or `<=`. |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'where', name, comparer, value }`. Without a comparer it is `=`. `==` becomes `=` and `!=` becomes `<>`. Called with one argument, it adds a raw condition like `builder.query()`.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFilters by the id column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | One value or an array. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nShortcut for `where('id', id)`, or `in('id', id)` when `id` is an array. `builder.userid(id)` does the same for the `userid` column, and `builder.equal(obj)` adds `where(key, value)` for each key of an object.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nThe column is one of the values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `value` | `Array|Object` | yes |  | The values. |\n| `key` | `String` | no |  | Take this property from each object of `value`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'in', name, value }`. A single value becomes an array. With `key`, `value` is an array of objects and their `key` property is used.\n\n`builder.notin(name, value, [key])` is the opposite, with the same arguments.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nThe column is between two values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `a` | `Object` | yes |  | The lower value. |\n| `b` | `Object` | yes |  | The upper value. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'between', name, a, b }`.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nA condition on an array column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `comparer` | `String` | no | `'&&'` | The operator for the adapter. |\n| `value` | `Array` | yes |  | The values. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'array', name, comparer, value }` for columns that hold arrays (for example `text[]` in PostgreSQL). The default comparer is `&&` (overlap).\n\nExample: Tags\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nGroups conditions joined with OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nCalls `fn(builder)`; conditions added inside go to one `{ type: 'or', value: [...] }` item.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nA text search (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `value` | `String` | yes |  | The text. |\n| `where` | `String` | no |  | The position hint for the adapter. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'search', name, value, comparer: where }`. `where` is a hint for the adapter where the text may be (for example at the beginning or the end); without it, anywhere.\n\nExample: Search\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nThe column has a value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'contains', name }`; the adapter writes a test for a non-empty value. `builder.empty(name)` adds the opposite test `{ type: 'empty', name }`.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompares a part of a date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The date column. |\n| `comparer` | `String` | no | `'='` | The operator. |\n| `value` | `Number` | yes |  | The year (or month, day, hour, minute). |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` and `minute()` work the same way. The default comparer is `=`.\n\nExample: Dates\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nAdds a raw SQL condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | The condition. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'query', value: sql }`. The adapter puts the text into the WHERE clause as it is, so never put input of users into it.\n\nExample: Raw condition\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nAdds a join.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the joined data. |\n| `table` | `String` | yes |  | The joined table. |\n| `jointype` | `String` | no |  | For example `left` or `inner`. |\n| `a` | `String` | yes |  | The column of the main table. |\n| `b` | `String` | yes |  | The column of the joined table. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `{ type: 'join', name, table, join: jointype, on: [a, b] }`. How the adapter builds the join and where it puts the joined data depends on the adapter.\n\nExample: Join\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFilters by a permissions column.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `type` | `String` | yes |  | Letters such as `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roles or ids. |\n| `userid` | `String` | no |  | A user id that the adapter may also accept. |\n| `required` | `Boolean` | no | `true` | Whether the permission is required. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds a `permit` filter for a column that holds permissions as `<type><value>` strings. `type` is one or more letters (`R` read, `W` write, `D` delete); each letter is joined with each item of `value`, so `permit('permissions', 'RW', ['admin'])` gives `['Radmin', 'Wadmin']`. `userid` and `required` (default `true`) are passed to the adapter.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nSelects the columns.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | For example `'id,name,email'`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nA comma-separated list of columns. It goes to the adapter as an array in `filter.fields`.\n\nExample: Fields\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAdds a sort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The column. |\n| `desc` | `Boolean|String` | no | `false` | Descending order. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nAdds `name_asc`, or `name_desc` when `desc` is `true` or `'desc'`. Call it more times for more columns.\n\n`builder.gridsort(sort, [localized])` adds sorts from a string such as `'name_asc,price_desc'` (an item without `_asc`/`_desc` is ascending); `localized` maps a field name to another column name.\n\nExample: Sort\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Grid sort\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimits the number of rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | The maximum number of rows. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nSets `filter.take` (alias `limit()`). `builder.first()` sets `take: 1` and makes the response one row or `null` instead of an array.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSets the page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | The page, from 1. |\n| `limit` | `Number` | no |  | Rows per page. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nSets `skip` to `(page - 1) * take`. With `limit`, it sets `take` first. `page` starts at 1.\n\n`builder.skip(count)` sets `filter.skip` (the offset) directly.\n\nExample: Page\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSets the page from user input.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | The page, from 1. |\n| `limit` | `String|Number` | yes |  | Rows per page. |\n| `maxlimit` | `Number` | no |  | The largest and the default limit. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nLike `page()`, but accepts strings from a query string, uses page 1 for missing or wrong values, caps `limit` at `maxlimit` and uses `maxlimit` when `limit` is missing.\n\nExample: Paginate\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nAdds a filter from a text value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The key in `obj`. |\n| `obj` | `Object` | yes |  | Usually the query string. |\n| `type` | `Function|String` | no | `String` | The type of the column. |\n| `key` | `String` | no |  | The column, when it differs from `name`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nReads `obj[name]` and, when it is a non-empty string, adds a filter for the column `key` (default `name`). `type` is `String` (default), `Number`, `Date`, `Boolean` or a string: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (an `array()` filter) or `json` (a `search()`).\n\n- `a - b` is `between()`.\n- `a,b,c` is `in()`; for strings it is an `or()` of searches.\n- For strings, `!text` is an exact match and other text is `search()`.\n- For numbers and dates, a leading `>` or `<` compares.\n- Dates accept `today`, `yesterday`, a full date, `MM-DD` of this year, a year (more than 1000) or a month number, and a relative value with a space such as `7 days` (that day in the past). A single day matches from 00:00:00 to 23:59:59.\n\nExample: Grid filter\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nBuilds fields, filters, sort and paging from the query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | The query string, usually `$.query`. |\n| `fields` | `String` | yes |  | The allowed columns and types. |\n| `sort` | `String` | no |  | The default sort, for example `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | The maximum rows per page. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\n`fields` lists the allowed columns with their types, `'id,name,price:number,dtcreated:date'` (the default type is `string`). Then:\n\n- `query.fields` chooses columns from the allowed ones; otherwise all allowed columns are selected.\n- Each allowed column present in `query` gets a `gridfilter()` with its type.\n- `query.sort` (for example `price_desc`) is used for allowed columns; otherwise `sort` is the default.\n- With `maxlimit`, `paginate(query.page, query.limit, maxlimit)` is called. Without it, no paging is set.\n\nA column name with `§` is localized: `§` stays in the column name sent to the adapter and is removed in the name used in the query string.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nBuilds a grid query from the schema of $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The options of a schema operation. |\n| `allowedfields` | `String` | no |  | Extra columns, with optional types. |\n| `skipfields` | `String` | no |  | Columns of the schema to leave out. |\n| `sort` | `String` | no |  | The default sort. |\n| `maxlimit` | `Number` | no | `50` | The maximum rows per page. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nWorks like `autoquery()`, but the columns and their types come from the schema of the current operation (`$.schema`). It reads `$.query` (or `$.options`). `allowedfields` adds columns that are not in the schema (`'name:type,...'`), `skipfields` hides columns of the schema. Paging is always set, with `maxlimit` 50 by default. When the fourth argument is a number, it is `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nPasses a language to the adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | The language, or an object with `language`. |\n| `prefix` | `String` | no |  | Text before the language. |\n| `skip` | `String` | no |  | The language that gives an empty value. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nSets `filter.language` to `prefix + value`. `value` may be `$` or a controller; then its `language` is used. When `value` equals `skip` (by default `_`, see `db.language()`), the language is empty. The adapter uses it, for example, to replace `§` in column names.\n\nExample: Language\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nAsks for columns of changed rows.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | For example `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nSets `filter.returning` to an array from a comma-separated list. The adapter returns these columns after `insert`, `update` or `remove`. With upsert, an empty returned result means \"not updated\".\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepares the data of an upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | A value passed to `fn`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nWith `update(table, data, true)`, when nothing was updated, `fn(data, param)` is called before the data are inserted. Use it to add columns that only a new row has.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nMakes an empty result an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | The error. |\n| `reverse` | `Boolean` | no | `false` | Fail when a row exists. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nWhen the response is empty (no row, `null`, `0` or an empty array), the query fails with `err` (as a string, for example an error key of a resource or `'404'`). With `reverse`, the query fails when the response is **not** empty. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nStores the response under a key of a DB() response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The key. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nOn a `DB()` controller, the response of this query goes to `response[name]` instead of replacing the whole response. `builder.nobind()` keeps the response out of the controller response completely. Not for `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nCalls fn with the response on success.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nCalled only when the query succeeds, before `callback()`. In a `DB()` chain you can add more queries from here.\n\n`builder.fail(fn)` is the counterpart: `fn(err)` is called only when the query fails.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nCalls fn with the result of this query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` or `$`. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nCalled with `(err, response)`. Accepts `$` too, then it uses `$.callback`, so an error becomes the error of the operation.\n\n`builder.done($, fn, [param])` sends an error to `$.invalid(err)` and otherwise calls `fn(response, param)`.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nReturns a promise of this query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | The options of a schema or an operation. |\n\nReturns: `Promise`\n\nResolves with the response. With `$`, an error goes to `$.invalid()` and the promise stays pending, so the rest of the function does not run. Without `$`, the promise is rejected; the error gets the name `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nWrites an audit record after success.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The options of a schema or an operation. |\n| `message` | `String` | no |  | The text. |\n| `type` | `String` | no |  | The type of the record. |\n\nReturns: `QueryBuilder` The builder of the query, for chaining.\n\nWhen the query succeeds, calls `$.audit(message, type)`. `message` may contain dynamic arguments (`{user.name}`, `{model.key}`, `{data.key}`...); `data` is the payload of the query.\n\nExample: Audit\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nThe global class of the SQL query builder.\n\nEvery method of `DB()` and `DATA` that starts a query returns an instance. Its prototype `QueryBuilder.prototype` is global, so you can add your own methods. The controller class is the global `QueryBuilderDB`.\n\nExample: Own method\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm931ci61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() und jede Methode des SQL-QueryBuilders.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() und jede Methode des SQL-QueryBuilders.\n\nDer SQL-QueryBuilder beschreibt eine Abfrage mit verketteten Methoden und übergibt sie an den mit `NEWDB()` registrierten Adapter. Der Guide [QueryBuilder](../../guides/querybuilder/) erklärt die Verwendung mit Beispielen; diese Seite ist die genaue Referenz.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistriert oder entfernt den Adapter einer SQL-Verbindung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Der Verbindungsname. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, siehe die Adapter-Funktion. Lass sie weg, um den Adapter zu entfernen. |\n\nReturns: `undefined`\n\nRegistriert `fn` als Adapter für die Verbindung `name` (Standard `default`). Der Name `*` ist ein Fallback, der für jede Verbindung ohne eigenen Adapter verwendet wird. Ein Aufruf von `NEWDB(name)` ohne Funktion entfernt den Adapter. Läuft eine Abfrage und es existiert kein Adapter, schlägt sie mit dem Fehler `Database is not initialized` fehl.\n\nDer Adapter wird mit `this` als internem Abfrageobjekt aufgerufen und erhält die Adapter-Optionen (siehe *Adapter-Optionen*) und einen Callback.\n\nExample: Ein Standard- und ein benannter Adapter\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nDie Funktion, die eine Abfrage gegen die Datenbank ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Die Beschreibung der Abfrage. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nDu schreibst den Adapter und registrierst ihn mit `NEWDB()`. Er liest `filter` (siehe *Adapter-Optionen*), baut und führt das SQL aus und ruft `callback(err, response)` genau einmal auf.\n\nWas `response` enthalten muss, hängt von `filter.exec` ab: ein Array für `find`, eine Zeile oder ein Array für `read` und `check`, `{ items, count }` für `list`, eine Zahl für `count` und für den Rest, was du für sinnvoll hältst. Ein `err` stoppt eine `DB()`-Kette und geht an die Callbacks der Abfrage.\n\nExample: Gerüst eines Adapters\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nDie Beschreibung einer Abfrage, die der Adapter erhält.\n\nReturns: `Object`\n\n| Feld | Typ | Bedeutung |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` oder `drop` |\n| `table` | String | Der Tabellenname, ohne Verbindungspräfix (leer bei `query`) |\n| `filter` | Array | Die Bedingungen in ihrer Reihenfolge (siehe unten) |\n| `fields` | Array | Die Spaltennamen aus `fields()` oder leer für alle |\n| `sort` | Array | Einträge in der Form `name_asc` oder `name_desc` |\n| `take`, `skip` | Number | Limit und Offset. `list` beginnt mit `take: 100, skip: 0` |\n| `first` | Boolean | `true` bei `read`, `check` und `first()`: Eine Zeile wird erwartet |\n| `payload` | Object | Die Daten von `insert` und `update` |\n| `upsert` | Boolean | `true` bei einem Update mit Upsert |\n| `returning` | Array | Die Spalten aus `returning()` |\n| `query`, `params` | String, Array/Object | Das SQL und die Argumente von `query()` |\n| `scalar` | Object | `{ type, key, key2 }` aus `scalar()` |\n| `command` | String | Der Name aus `command()` |\n| `language` | String | Der Wert aus `language()` |\n| `primarykey` | String | Der Wert aus `builder.primarykey(name)` |\n| `schema` | String | Der Wert aus `builder.schema(name)` |\n| `checksum` | String | Ein Hash der Form der Filter (ohne die Werte), nützlich als Cache-Schlüssel für Prepared Statements |\n| `debug` | Boolean | `true` nach `debug()` |\n\nDie Einträge von `filter.filter` haben einen `type`: `where` (`name`, `comparer`, `value`), `in` und `notin` (`name`, `value` als Array), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` und `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: ein Array von Einträgen), `query` (`value`: rohes SQL), `join` (`name`, `table`, `join`, `on`) und `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nErstellt einen Controller, der mehrere Abfragen nacheinander ausführt.\n\nReturns: `QueryBuilderDB` Der Controller.\n\nGibt einen neuen Controller zurück (Alias `DATABASE()`). Jede Methode, die du darauf aufrufst, fügt einer Warteschlange eine Abfrage hinzu. Die Warteschlange startet im nächsten Tick und führt die Abfragen der Reihe nach aus. Nach der letzten erhält der Callback des Controllers (`callback()`, `promise()` oder `done()`) den Fehler oder die Antwort. Ein Fehler stoppt die Warteschlange.\n\nStandardmäßig ersetzt jede Abfrage die Antwort; nutze `builder.set(name)`, um mehrere Antworten zu sammeln, und `builder.nobind()`, um eine Abfrage aus der Antwort herauszuhalten. Eine Abfrage, die aus einem Callback einer vorherigen Abfrage hinzugefügt wird, wird ebenfalls ausgeführt.\n\nExample: Zwei Abfragen nacheinander\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nEin globaler Controller für einzelne Abfragen.\n\nReturns: `QueryBuilderDB`\n\n`DATA` hat dieselben Abfragemethoden wie `DB()` (`find`, `read`, `insert`...), aber jede Abfrage läuft eigenständig, sobald sie erstellt wird, ohne Warteschlange. Es ist schneller als `DB()`, weil kein Controller erstellt wird.\n\nLies das Ergebnis mit den Methoden des Builders: `callback()`, `promise()`, `done()`, `data()` oder `fail()`. Verwende `set()` nicht mit `DATA` und verwende nicht die Controller-Methoden `DATA.callback()`, `DATA.promise()` und `DATA.done()`: `DATA` wird von der ganzen App gemeinsam genutzt.\n\nExample: Eine einzelne Abfrage\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nFindet Zeilen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `find`-Abfrage (Alias `all()`). Die Antwort ist ein Array von Zeilen.\n\nExample: Finden\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nFindet eine Seite mit Zeilen samt Zählwerten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `list`-Abfrage mit `take: 100` und `skip: 0`. Der Adapter gibt `{ items, count }` zurück, wobei `count` die Anzahl aller passenden Zeilen ist. Das Framework ergänzt `page`, `limit` und `pages` (die Anzahl der Seiten).\n\nExample: Eine Seite\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nLiest eine Zeile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `read`-Abfrage (Alias `one()`) mit `take: 1`. Gibt der Adapter ein Array zurück, ist die Antwort sein erstes Element oder `null`. Kombiniere es mit `error('404')`.\n\nExample: Lesen\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nPrüft, ob eine Zeile existiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `check`-Abfrage mit `take: 1`. Der Adapter wählt üblicherweise nur eine Spalte aus. Nutze es mit `error()`, um bei einer fehlenden Zeile abzubrechen, oder mit `error(err, true)`, um bei einer vorhandenen abzubrechen.\n\nExample: Eindeutige E-Mail\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nFührt eine Aggregation aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n| `type` | `String` | yes |  | Die Art der Aggregation. |\n| `key` | `String` | no | `'*'` | Die Spalte. |\n| `key2` | `String` | no |  | Eine zweite Spalte, zum Beispiel zum Gruppieren. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `scalar`-Abfrage. Der Adapter erhält `filter.scalar = { type, key, key2 }`. Die Bedeutung von `type` (zum Beispiel `sum`, `min`, `max`, `avg`, `group`) hängt vom Adapter ab.\n\n`db.count(table)` startet eine `count`-Abfrage; die Antwort ist die Zahl, die der Adapter zurückgibt.\n\nExample: Summe\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Anzahl\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nFügt eine Zeile ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Die Zeile. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `insert`-Abfrage (Alias `ins()`). `data` geht als `filter.payload` an den Adapter.\n\nExample: Einfügen\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAktualisiert Zeilen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Die geänderten Spalten. |\n| `upsert` | `Boolean` | no | `false` | Die Daten einfügen, wenn nichts aktualisiert wurde. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `update`-Abfrage (Aliase `modify()`, `mod()`, `upd()`). `data` geht als `filter.payload` an den Adapter. Mit `upsert` ruft das Framework, wenn der Adapter eine leere Antwort zurückgibt (oder nichts aus `returning`), die Funktion von `builder.insert()` auf, leert die Filter und führt die Daten als `insert` aus.\n\nExample: Aktualisieren\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nEntfernt Zeilen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `remove`-Abfrage (Alias `rem()`).\n\nExample: Entfernen\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nFührt dein eigenes SQL aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Der Verbindungsname. |\n| `sql` | `String` | yes |  | Das SQL. |\n| `params` | `Array|Object` | no |  | Die Argumente für die Platzhalter deines Treibers. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nSendet `sql` als `filter.query` und `params` als `filter.params` an den Adapter von `conn`. Ist das zweite Argument ein Array oder ein Objekt, wird es als `params` genommen, und die Verbindung ist `default`. Filter, die dem Builder hinzugefügt wurden (zum Beispiel `where()`), werden ebenfalls in `filter.filter` übergeben.\n\n`db.command(table, name)` sendet `exec: 'command'` mit `filter.command = name`, für Operationen deines Adapters, die die anderen Methoden nicht abdecken.\n\nExample: Rohes SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Befehl\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nEntfernt alle Zeilen einer Tabelle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Der Tabellenname. Ein Präfix `name/` wählt die Verbindung, zum Beispiel `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nStartet eine `truncate`-Abfrage (Alias `clear()`). `db.drop(table)` startet auf die gleiche Weise eine `drop`-Abfrage, um die Tabelle selbst zu entfernen.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nErstellt eine Abfrage aus einem vorbereiteten Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Der Verbindungsname. |\n| `options` | `Object` | yes |  | Die vorbereitete Abfrage. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nErstellt einen Builder aus den Feldern von `options`: `table`, `exec`, `fields` (Array), `sort` (Array), `skip`, `take`, `query`, `payload`, `upsert`, `returning` und `filter` (ein Array von Filtereinträgen). Anders als bei den anderen Methoden hat `table` kein Verbindungspräfix; übergib die Verbindung als `conn`. Lege alle Bedingungen in `options.filter` ab.\n\n`db.exec(options, callback)` führt ein vorbereitetes Objekt sofort aus: Es startet die durch `options.exec` benannte Abfrage auf `options.table` (bei `exec: 'query'` enthält `options.query` das SQL), kopiert die übrigen Felder in die Adapter-Optionen und ruft `callback(err, response)` auf. Es gibt nichts zurück.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nSetzt den finalen Callback eines DB()-Controllers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` oder `$`. |\n\nReturns: `QueryBuilderDB`\n\nWird nach der letzten Abfrage oder nach dem ersten Fehler mit `(err, response)` aufgerufen. Akzeptiert auch `$` und verwendet dann `$.callback`. Nutze es nur auf `DB()`.\n\nZwei weitere Wege, einen `DB()`-Controller abzuschließen: `db.promise([$])` gibt eine Promise der finalen Antwort zurück (mit `$` geht ein Fehler an `$.invalid()` und die Promise bleibt ausstehend; ohne wird die Promise abgelehnt), und `db.done($, [fn])` sendet einen Fehler an `$.invalid(err)` und ruft andernfalls `fn(response)` auf.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nRuft bei Erfolg fn auf, bei einem Fehler $.invalid().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Die Optionen eines Schemas oder einer Operation. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nSetzt den finalen Callback eines `DB()`-Controllers: Ein Fehler geht an `$.invalid(err)`, andernfalls wird `fn(response)` aufgerufen.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nSchaltet den Debug-Modus für die nächsten Abfragen ein.\n\nReturns: `QueryBuilderDB`\n\nSetzt `filter.debug = true` für Abfragen, die nach dem Aufruf auf diesem Controller erstellt werden, sodass der Adapter das SQL ausgeben kann. Für eine einzelne Abfrage nutze stattdessen `builder.debug()`.\n\n`builder.debug()` setzt das Flag nur für eine Abfrage.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Debug\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nSetzt das Standardpräfix und den Skip-Wert von builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Text, der vor die Sprache gesetzt wird. |\n| `skip` | `String` | yes |  | Eine Sprache, die einen leeren Wert ergibt (die Standardsprache). |\n\nReturns: `QueryBuilderDB`\n\nDie Werte sind global: Sie gelten für jeden späteren Aufruf von `builder.language()` in der App, ob auf `DB()` oder `DATA`. Die Standardwerte sind `prefix: ''` und `skip: '_'`.\n\nExample: Standardwerte\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nFügt eine Bedingung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` oder `<=`. |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'where', name, comparer, value }` hinzu. Ohne Vergleichsoperator ist es `=`. `==` wird zu `=` und `!=` wird zu `<>`. Mit einem Argument aufgerufen, fügt es eine rohe Bedingung wie `builder.query()` hinzu.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltert nach der Spalte id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | Ein Wert oder ein Array. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nKurzform für `where('id', id)` oder `in('id', id)`, wenn `id` ein Array ist. `builder.userid(id)` macht dasselbe für die Spalte `userid`, und `builder.equal(obj)` fügt `where(key, value)` für jeden Schlüssel eines Objekts hinzu.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nDie Spalte ist einer der Werte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `value` | `Array|Object` | yes |  | Die Werte. |\n| `key` | `String` | no |  | Diese Eigenschaft aus jedem Objekt von `value` nehmen. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'in', name, value }` hinzu. Ein einzelner Wert wird zu einem Array. Mit `key` ist `value` ein Array von Objekten, und deren Eigenschaft `key` wird verwendet.\n\n`builder.notin(name, value, [key])` ist das Gegenteil, mit denselben Argumenten.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nDie Spalte liegt zwischen zwei Werten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `a` | `Object` | yes |  | Der untere Wert. |\n| `b` | `Object` | yes |  | Der obere Wert. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'between', name, a, b }` hinzu.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nEine Bedingung auf eine Array-Spalte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `comparer` | `String` | no | `'&&'` | Der Operator für den Adapter. |\n| `value` | `Array` | yes |  | Die Werte. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'array', name, comparer, value }` für Spalten hinzu, die Arrays enthalten (zum Beispiel `text[]` in PostgreSQL). Der Standard-Vergleichsoperator ist `&&` (Überschneidung).\n\nExample: Tags\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nGruppiert Bedingungen, die mit OR verknüpft sind.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nRuft `fn(builder)` auf; darin hinzugefügte Bedingungen landen in einem einzigen Eintrag `{ type: 'or', value: [...] }`.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nEine Textsuche (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `value` | `String` | yes |  | Der Text. |\n| `where` | `String` | no |  | Der Positionshinweis für den Adapter. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'search', name, value, comparer: where }` hinzu. `where` ist ein Hinweis für den Adapter, wo der Text stehen darf (zum Beispiel am Anfang oder am Ende); ohne ihn irgendwo.\n\nExample: Suche\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nDie Spalte hat einen Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'contains', name }` hinzu; der Adapter schreibt einen Test auf einen nicht leeren Wert. `builder.empty(name)` fügt den gegenteiligen Test `{ type: 'empty', name }` hinzu.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nVergleicht einen Teil eines Datums.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Datumsspalte. |\n| `comparer` | `String` | no | `'='` | Der Operator. |\n| `value` | `Number` | yes |  | Das Jahr (oder Monat, Tag, Stunde, Minute). |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'year', name, comparer, value }` hinzu. `month()`, `day()`, `hour()` und `minute()` funktionieren genauso. Der Standard-Vergleichsoperator ist `=`.\n\nExample: Datumswerte\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nFügt eine rohe SQL-Bedingung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | Die Bedingung. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'query', value: sql }` hinzu. Der Adapter setzt den Text unverändert in die WHERE-Klausel, also füge niemals Benutzereingaben darin ein.\n\nExample: Rohe Bedingung\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nFügt einen Join hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der verknüpften Daten. |\n| `table` | `String` | yes |  | Die verknüpfte Tabelle. |\n| `jointype` | `String` | no |  | Zum Beispiel `left` oder `inner`. |\n| `a` | `String` | yes |  | Die Spalte der Haupttabelle. |\n| `b` | `String` | yes |  | Die Spalte der verknüpften Tabelle. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `{ type: 'join', name, table, join: jointype, on: [a, b] }` hinzu. Wie der Adapter den Join baut und wo er die verknüpften Daten ablegt, hängt vom Adapter ab.\n\nExample: Join\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFiltert nach einer Berechtigungsspalte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `type` | `String` | yes |  | Buchstaben wie `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Rollen oder IDs. |\n| `userid` | `String` | no |  | Eine Benutzer-ID, die der Adapter ebenfalls akzeptieren kann. |\n| `required` | `Boolean` | no | `true` | Ob die Berechtigung erforderlich ist. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt einen `permit`-Filter für eine Spalte hinzu, die Berechtigungen als Strings der Form `<type><value>` enthält. `type` besteht aus einem oder mehreren Buchstaben (`R` Lesen, `W` Schreiben, `D` Löschen); jeder Buchstabe wird mit jedem Element von `value` verbunden, sodass `permit('permissions', 'RW', ['admin'])` den Wert `['Radmin', 'Wadmin']` ergibt. `userid` und `required` (Standard `true`) werden an den Adapter übergeben.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nWählt die Spalten aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Zum Beispiel `'id,name,email'`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nEine kommagetrennte Liste von Spalten. Sie geht als Array in `filter.fields` an den Adapter.\n\nExample: Felder\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nFügt eine Sortierung hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Die Spalte. |\n| `desc` | `Boolean|String` | no | `false` | Absteigende Reihenfolge. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFügt `name_asc` hinzu, oder `name_desc`, wenn `desc` `true` oder `'desc'` ist. Rufe es für weitere Spalten mehrmals auf.\n\n`builder.gridsort(sort, [localized])` fügt Sortierungen aus einem String wie `'name_asc,price_desc'` hinzu (ein Eintrag ohne `_asc`/`_desc` ist aufsteigend); `localized` ordnet einem Feldnamen einen anderen Spaltennamen zu.\n\nExample: Sortierung\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Grid-Sortierung\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nBegrenzt die Anzahl der Zeilen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Die maximale Anzahl an Zeilen. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nSetzt `filter.take` (Alias `limit()`). `builder.first()` setzt `take: 1` und macht die Antwort zu einer Zeile oder `null` statt einem Array.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nSetzt die Seite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Die Seite, ab 1. |\n| `limit` | `Number` | no |  | Zeilen pro Seite. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nSetzt `skip` auf `(page - 1) * take`. Mit `limit` setzt es zuerst `take`. `page` beginnt bei 1.\n\n`builder.skip(count)` setzt `filter.skip` (den Offset) direkt.\n\nExample: Seite\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nSetzt die Seite anhand von Benutzereingaben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | Die Seite, ab 1. |\n| `limit` | `String|Number` | yes |  | Zeilen pro Seite. |\n| `maxlimit` | `Number` | no |  | Das größte und das Standardlimit. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nWie `page()`, akzeptiert aber Strings aus einem Query-String, verwendet Seite 1 bei fehlenden oder falschen Werten, begrenzt `limit` auf `maxlimit` und verwendet `maxlimit`, wenn `limit` fehlt.\n\nExample: Paginate\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nFügt einen Filter aus einem Textwert hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Schlüssel in `obj`. |\n| `obj` | `Object` | yes |  | Üblicherweise der Query-String. |\n| `type` | `Function|String` | no | `String` | Der Typ der Spalte. |\n| `key` | `String` | no |  | Die Spalte, wenn sie sich von `name` unterscheidet. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nLiest `obj[name]` und fügt, wenn es ein nicht leerer String ist, einen Filter für die Spalte `key` (Standard `name`) hinzu. `type` ist `String` (Standard), `Number`, `Date`, `Boolean` oder ein String: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (ein `array()`-Filter) oder `json` (ein `search()`).\n\n- `a - b` ist `between()`.\n- `a,b,c` ist `in()`; bei Strings ist es ein `or()` von Suchen.\n- Bei Strings ist `!text` eine exakte Übereinstimmung und anderer Text ist `search()`.\n- Bei Zahlen und Datumswerten vergleicht ein vorangestelltes `>` oder `<`.\n- Datumswerte akzeptieren `today`, `yesterday`, ein vollständiges Datum, `MM-DD` des aktuellen Jahres, ein Jahr (größer als 1000) oder eine Monatszahl und einen relativen Wert mit Leerzeichen wie `7 days` (dieser Tag in der Vergangenheit). Ein einzelner Tag passt von 00:00:00 bis 23:59:59.\n\nExample: Grid-Filter\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nBaut Felder, Filter, Sortierung und Paginierung aus dem Query-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | Der Query-String, üblicherweise `$.query`. |\n| `fields` | `String` | yes |  | Die erlaubten Spalten und Typen. |\n| `sort` | `String` | no |  | Die Standardsortierung, zum Beispiel `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | Die maximale Anzahl Zeilen pro Seite. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\n`fields` listet die erlaubten Spalten mit ihren Typen auf, `'id,name,price:number,dtcreated:date'` (der Standardtyp ist `string`). Dann:\n\n- `query.fields` wählt Spalten aus den erlaubten aus; andernfalls werden alle erlaubten Spalten ausgewählt.\n- Jede erlaubte Spalte, die in `query` vorhanden ist, erhält ein `gridfilter()` mit ihrem Typ.\n- `query.sort` (zum Beispiel `price_desc`) wird für erlaubte Spalten verwendet; andernfalls ist `sort` der Standard.\n- Mit `maxlimit` wird `paginate(query.page, query.limit, maxlimit)` aufgerufen. Ohne wird keine Paginierung gesetzt.\n\nEin Spaltenname mit `§` ist lokalisiert: `§` bleibt im an den Adapter gesendeten Spaltennamen und wird im Namen entfernt, der im Query-String verwendet wird.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nBaut eine Grid-Abfrage aus dem Schema von $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Die Optionen einer Schema-Operation. |\n| `allowedfields` | `String` | no |  | Zusätzliche Spalten, optional mit Typen. |\n| `skipfields` | `String` | no |  | Spalten des Schemas, die weggelassen werden. |\n| `sort` | `String` | no |  | Die Standardsortierung. |\n| `maxlimit` | `Number` | no | `50` | Die maximale Anzahl Zeilen pro Seite. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nFunktioniert wie `autoquery()`, aber die Spalten und ihre Typen stammen aus dem Schema der aktuellen Operation (`$.schema`). Es liest `$.query` (oder `$.options`). `allowedfields` fügt Spalten hinzu, die nicht im Schema sind (`'name:type,...'`), `skipfields` blendet Spalten des Schemas aus. Die Paginierung wird immer gesetzt, standardmäßig mit `maxlimit` 50. Ist das vierte Argument eine Zahl, ist es `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nÜbergibt eine Sprache an den Adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | Die Sprache oder ein Objekt mit `language`. |\n| `prefix` | `String` | no |  | Text vor der Sprache. |\n| `skip` | `String` | no |  | Die Sprache, die einen leeren Wert ergibt. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nSetzt `filter.language` auf `prefix + value`. `value` kann `$` oder ein Controller sein; dann wird dessen `language` verwendet. Ist `value` gleich `skip` (standardmäßig `_`, siehe `db.language()`), ist die Sprache leer. Der Adapter nutzt sie zum Beispiel, um `§` in Spaltennamen zu ersetzen.\n\nExample: Sprache\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nFordert Spalten geänderter Zeilen an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Zum Beispiel `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nSetzt `filter.returning` auf ein Array aus einer kommagetrennten Liste. Der Adapter gibt diese Spalten nach `insert`, `update` oder `remove` zurück. Bei Upsert bedeutet ein leeres zurückgegebenes Ergebnis „nicht aktualisiert“.\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nBereitet die Daten eines Upserts vor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | Ein Wert, der an `fn` übergeben wird. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nMit `update(table, data, true)` wird, wenn nichts aktualisiert wurde, `fn(data, param)` aufgerufen, bevor die Daten eingefügt werden. Nutze es, um Spalten hinzuzufügen, die nur eine neue Zeile hat.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nMacht aus einem leeren Ergebnis einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | Der Fehler. |\n| `reverse` | `Boolean` | no | `false` | Fehlschlagen, wenn eine Zeile existiert. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nIst die Antwort leer (keine Zeile, `null`, `0` oder ein leeres Array), schlägt die Abfrage mit `err` fehl (als String, zum Beispiel ein Fehlerschlüssel einer Ressource oder `'404'`). Mit `reverse` schlägt die Abfrage fehl, wenn die Antwort **nicht** leer ist. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nSpeichert die Antwort unter einem Schlüssel einer DB()-Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Schlüssel. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nAuf einem `DB()`-Controller geht die Antwort dieser Abfrage nach `response[name]`, statt die ganze Antwort zu ersetzen. `builder.nobind()` hält die Antwort vollständig aus der Controller-Antwort heraus. Nicht für `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nRuft bei Erfolg fn mit der Antwort auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nWird nur aufgerufen, wenn die Abfrage erfolgreich ist, vor `callback()`. In einer `DB()`-Kette kannst du von hier aus weitere Abfragen hinzufügen.\n\n`builder.fail(fn)` ist das Gegenstück: `fn(err)` wird nur aufgerufen, wenn die Abfrage fehlschlägt.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nRuft fn mit dem Ergebnis dieser Abfrage auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` oder `$`. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nWird mit `(err, response)` aufgerufen. Akzeptiert auch `$` und verwendet dann `$.callback`, sodass ein Fehler zum Fehler der Operation wird.\n\n`builder.done($, fn, [param])` sendet einen Fehler an `$.invalid(err)` und ruft andernfalls `fn(response, param)` auf.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nGibt eine Promise dieser Abfrage zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Die Optionen eines Schemas oder einer Operation. |\n\nReturns: `Promise`\n\nWird mit der Antwort aufgelöst. Mit `$` geht ein Fehler an `$.invalid()` und die Promise bleibt ausstehend, sodass der Rest der Funktion nicht ausgeführt wird. Ohne `$` wird die Promise abgelehnt; der Fehler erhält den Namen `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nSchreibt nach Erfolg einen Audit-Eintrag.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Die Optionen eines Schemas oder einer Operation. |\n| `message` | `String` | no |  | Der Text. |\n| `type` | `String` | no |  | Der Typ des Eintrags. |\n\nReturns: `QueryBuilder` Der Builder der Abfrage, zum Verketten.\n\nRuft bei erfolgreicher Abfrage `$.audit(message, type)` auf. `message` kann dynamische Argumente enthalten (`{user.name}`, `{model.key}`, `{data.key}`...); `data` ist der Payload der Abfrage.\n\nExample: Audit\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nDie globale Klasse des SQL-QueryBuilders.\n\nJede Methode von `DB()` und `DATA`, die eine Abfrage startet, gibt eine Instanz zurück. Ihr Prototyp `QueryBuilder.prototype` ist global, sodass du eigene Methoden hinzufügen kannst. Die Controller-Klasse ist das globale `QueryBuilderDB`.\n\nExample: Eigene Methode\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm931ci61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() y todos los métodos del SQL QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() y todos los métodos del SQL QueryBuilder.\n\nEl SQL QueryBuilder describe una consulta con métodos encadenados y la pasa al adaptador registrado con `NEWDB()`. La guía [QueryBuilder](../../guides/querybuilder/) explica cómo usarlo con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistra o elimina el adaptador de una conexión SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | El nombre de la conexión. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, consulta la función del adaptador. Omítela para eliminar el adaptador. |\n\nReturns: `undefined`\n\nRegistra `fn` como adaptador de la conexión `name` (por defecto `default`). El nombre `*` es un respaldo que se usa para cada conexión sin adaptador propio. Llamar a `NEWDB(name)` sin función elimina el adaptador. Cuando se ejecuta una consulta y no existe ningún adaptador, falla con el error `Database is not initialized`.\n\nEl adaptador se llama con `this` apuntando al objeto interno de la consulta y recibe las opciones del adaptador (consulta *Opciones del adaptador*) y un callback.\n\nExample: Un adaptador por defecto y uno con nombre\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nLa función que ejecuta una consulta contra la base de datos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | La descripción de la consulta. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nTú escribes el adaptador y lo registras con `NEWDB()`. Lee `filter` (consulta *Opciones del adaptador*), construye y ejecuta el SQL, y llama a `callback(err, response)` exactamente una vez.\n\nLo que debe contener `response` depende de `filter.exec`: un array para `find`, una fila o un array para `read` y `check`, `{ items, count }` para `list`, un número para `count`, y lo que consideres útil para el resto. Un `err` detiene una cadena `DB()` y va a los callbacks de la consulta.\n\nExample: Esqueleto de un adaptador\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nLa descripción de una consulta que recibe el adaptador.\n\nReturns: `Object`\n\n| Campo | Tipo | Significado |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` o `drop` |\n| `table` | String | El nombre de la tabla, sin el prefijo de conexión (vacío para `query`) |\n| `filter` | Array | Las condiciones en su orden (ver abajo) |\n| `fields` | Array | Los nombres de columna de `fields()`, o vacío para todas |\n| `sort` | Array | Elementos con la forma `name_asc` o `name_desc` |\n| `take`, `skip` | Number | Límite y desplazamiento. `list` empieza con `take: 100, skip: 0` |\n| `first` | Boolean | `true` para `read`, `check` y `first()`: se espera una fila |\n| `payload` | Object | Los datos de `insert` y `update` |\n| `upsert` | Boolean | `true` para una actualización con upsert |\n| `returning` | Array | Las columnas de `returning()` |\n| `query`, `params` | String, Array/Object | El SQL y los argumentos de `query()` |\n| `scalar` | Object | `{ type, key, key2 }` de `scalar()` |\n| `command` | String | El nombre de `command()` |\n| `language` | String | El valor de `language()` |\n| `primarykey` | String | El valor de `builder.primarykey(name)` |\n| `schema` | String | El valor de `builder.schema(name)` |\n| `checksum` | String | Un hash de la forma de los filtros (sin los valores), útil como clave de caché de sentencias preparadas |\n| `debug` | Boolean | `true` después de `debug()` |\n\nLos elementos de `filter.filter` tienen un `type`: `where` (`name`, `comparer`, `value`), `in` y `notin` (`name`, array `value`), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` y `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: un array de elementos), `query` (`value`: SQL en bruto), `join` (`name`, `table`, `join`, `on`) y `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nCrea un controlador que ejecuta varias consultas una tras otra.\n\nReturns: `QueryBuilderDB` El controlador.\n\nDevuelve un nuevo controlador (alias `DATABASE()`). Cada método que llamas en él añade una consulta a una cola. La cola empieza en el siguiente tick y ejecuta las consultas en orden. Después de la última, el callback del controlador (`callback()`, `promise()` o `done()`) recibe el error o la respuesta. Un error detiene la cola.\n\nPor defecto cada consulta reemplaza la respuesta; usa `builder.set(name)` para reunir varias respuestas, y `builder.nobind()` para dejar una consulta fuera de la respuesta. Una consulta añadida desde un callback de una consulta anterior también se ejecuta.\n\nExample: Dos consultas seguidas\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nUn controlador global para consultas sueltas.\n\nReturns: `QueryBuilderDB`\n\n`DATA` tiene los mismos métodos de consulta que `DB()` (`find`, `read`, `insert`...), pero cada consulta se ejecuta por su cuenta en cuanto se crea, sin cola. Es más rápido que `DB()` porque no se crea ningún controlador.\n\nLee el resultado con los métodos del builder: `callback()`, `promise()`, `done()`, `data()` o `fail()`. No uses `set()` con `DATA`, y no uses los métodos de controlador `DATA.callback()`, `DATA.promise()` y `DATA.done()`: `DATA` lo comparte toda la aplicación.\n\nExample: Una consulta suelta\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nBusca filas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `find` (alias `all()`). La respuesta es un array de filas.\n\nExample: Find\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nBusca una página de filas con recuentos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `list` con `take: 100` y `skip: 0`. El adaptador devuelve `{ items, count }`, donde `count` es el número de todas las filas coincidentes. El framework añade `page`, `limit` y `pages` (el número de páginas).\n\nExample: Una página\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nLee una fila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `read` (alias `one()`) con `take: 1`. Cuando el adaptador devuelve un array, la respuesta es su primer elemento o `null`. Combínalo con `error('404')`.\n\nExample: Read\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nComprueba si existe una fila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `check` con `take: 1`. El adaptador normalmente selecciona solo una columna. Úsalo con `error()` para detenerte si falta una fila, o con `error(err, true)` para detenerte si existe.\n\nExample: E-mail único\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nEjecuta una agregación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n| `type` | `String` | yes |  | El tipo de agregación. |\n| `key` | `String` | no | `'*'` | La columna. |\n| `key2` | `String` | no |  | Una segunda columna, por ejemplo para agrupar. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `scalar`. El adaptador recibe `filter.scalar = { type, key, key2 }`. El significado de `type` (por ejemplo `sum`, `min`, `max`, `avg`, `group`) depende del adaptador.\n\n`db.count(table)` empieza una consulta `count`; la respuesta es el número que devuelve el adaptador.\n\nExample: Suma\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Recuento\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nInserta una fila.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n| `data` | `Object` | yes |  | La fila. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `insert` (alias `ins()`). `data` llega al adaptador como `filter.payload`.\n\nExample: Insertar\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nActualiza filas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Las columnas modificadas. |\n| `upsert` | `Boolean` | no | `false` | Inserta los datos cuando no se actualizó nada. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `update` (alias `modify()`, `mod()`, `upd()`). `data` llega al adaptador como `filter.payload`. Con `upsert`, cuando el adaptador devuelve una respuesta vacía (o nada de `returning`), el framework llama a la función de `builder.insert()`, borra los filtros y ejecuta los datos como `insert`.\n\nExample: Actualizar\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nElimina filas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `remove` (alias `rem()`).\n\nExample: Eliminar\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nEjecuta tu propio SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | El nombre de la conexión. |\n| `sql` | `String` | yes |  | El SQL. |\n| `params` | `Array|Object` | no |  | Los argumentos para los marcadores de tu driver. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEnvía `sql` como `filter.query` y `params` como `filter.params` al adaptador de `conn`. Cuando el segundo argumento es un array o un objeto, se toma como `params` y la conexión es `default`. Los filtros añadidos al builder (por ejemplo `where()`) también se pasan en `filter.filter`.\n\n`db.command(table, name)` envía `exec: 'command'` con `filter.command = name`, para operaciones de tu adaptador que los demás métodos no cubren.\n\nExample: SQL sin procesar\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Comando\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nElimina todas las filas de una tabla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | El nombre de la tabla. Un prefijo `name/` elige la conexión, por ejemplo `logs/tbl_request`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEmpieza una consulta `truncate` (alias `clear()`). `db.drop(table)` empieza de la misma forma una consulta `drop`, para eliminar la propia tabla.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nCrea una consulta a partir de un objeto preparado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | El nombre de la conexión. |\n| `options` | `Object` | yes |  | La consulta preparada. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nCrea un builder a partir de los campos de `options`: `table`, `exec`, `fields` (array), `sort` (array), `skip`, `take`, `query`, `payload`, `upsert`, `returning` y `filter` (un array de elementos de filtro). A diferencia de los otros métodos, `table` no lleva prefijo de conexión; pasa la conexión como `conn`. Pon todas las condiciones en `options.filter`.\n\n`db.exec(options, callback)` ejecuta un objeto preparado de inmediato: empieza la consulta indicada por `options.exec` sobre `options.table` (para `exec: 'query'`, `options.query` contiene el SQL), copia los otros campos a las opciones del adaptador y llama a `callback(err, response)`. No devuelve nada.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nAsigna el callback final de un controlador DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilderDB`\n\nSe llama después de la última consulta, o después del primer error, con `(err, response)`. También acepta `$`, y entonces usa `$.callback`. Úsalo solo en `DB()`.\n\nOtras dos formas de terminar un controlador `DB()`: `db.promise([$])` devuelve una promesa de la respuesta final (con `$`, un error va a `$.invalid()` y la promesa queda pendiente; sin él, la promesa se rechaza), y `db.done($, [fn])` envía un error a `$.invalid(err)` y, si no, llama a `fn(response)`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nLlama a fn si tiene éxito, y a $.invalid() si hay un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Las opciones de un esquema o de una operación. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nAsigna el callback final de un controlador `DB()`: un error va a `$.invalid(err)`; si no, se llama a `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nActiva el modo de depuración para las siguientes consultas.\n\nReturns: `QueryBuilderDB`\n\nAsigna `filter.debug = true` a las consultas creadas en este controlador después de la llamada, para que el adaptador pueda imprimir el SQL. Para una sola consulta, usa `builder.debug()`.\n\n`builder.debug()` activa el flag solo en una consulta.\n\nExample: Depuración\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Depuración\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nAsigna el prefijo y el valor de omisión por defecto de builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Texto que se pone antes del idioma. |\n| `skip` | `String` | yes |  | Un idioma que produce un valor vacío (el idioma por defecto). |\n\nReturns: `QueryBuilderDB`\n\nLos valores son globales: se aplican a todas las llamadas posteriores a `builder.language()` en la aplicación, ya sea en `DB()` o en `DATA`. Los valores por defecto son `prefix: ''` y `skip: '_'`.\n\nExample: Valores por defecto\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAñade una condición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` o `<=`. |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'where', name, comparer, value }`. Sin comparador es `=`. `==` se convierte en `=` y `!=` en `<>`. Llamado con un solo argumento, añade una condición en bruto como `builder.query()`.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltra por la columna id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | Un valor o un array. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAtajo de `where('id', id)`, o de `in('id', id)` cuando `id` es un array. `builder.userid(id)` hace lo mismo para la columna `userid`, y `builder.equal(obj)` añade `where(key, value)` para cada clave de un objeto.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nLa columna es uno de los valores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `value` | `Array|Object` | yes |  | Los valores. |\n| `key` | `String` | no |  | Toma esta propiedad de cada objeto de `value`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'in', name, value }`. Un valor único se convierte en un array. Con `key`, `value` es un array de objetos y se usa su propiedad `key`.\n\n`builder.notin(name, value, [key])` es lo contrario, con los mismos argumentos.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nLa columna está entre dos valores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `a` | `Object` | yes |  | El valor inferior. |\n| `b` | `Object` | yes |  | El valor superior. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'between', name, a, b }`.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nUna condición sobre una columna de tipo array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `comparer` | `String` | no | `'&&'` | El operador para el adaptador. |\n| `value` | `Array` | yes |  | Los valores. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'array', name, comparer, value }` para columnas que contienen arrays (por ejemplo `text[]` en PostgreSQL). El comparador por defecto es `&&` (solapamiento).\n\nExample: Etiquetas\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nAgrupa condiciones unidas con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nLlama a `fn(builder)`; las condiciones añadidas dentro van a un único elemento `{ type: 'or', value: [...] }`.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nUna búsqueda de texto (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `value` | `String` | yes |  | El texto. |\n| `where` | `String` | no |  | La pista de posición para el adaptador. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'search', name, value, comparer: where }`. `where` es una pista para el adaptador sobre dónde puede estar el texto (por ejemplo al principio o al final); sin ella, en cualquier parte.\n\nExample: Búsqueda\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nLa columna tiene un valor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'contains', name }`; el adaptador escribe una comprobación de valor no vacío. `builder.empty(name)` añade la comprobación contraria `{ type: 'empty', name }`.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompara una parte de una fecha.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna de fecha. |\n| `comparer` | `String` | no | `'='` | El operador. |\n| `value` | `Number` | yes |  | El año (o mes, día, hora, minuto). |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` y `minute()` funcionan igual. El comparador por defecto es `=`.\n\nExample: Fechas\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nAñade una condición SQL en bruto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | La condición. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'query', value: sql }`. El adaptador pone el texto tal cual en la cláusula WHERE, así que nunca metas en él datos introducidos por usuarios.\n\nExample: Condición en bruto\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nAñade un join.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de los datos unidos. |\n| `table` | `String` | yes |  | La tabla unida. |\n| `jointype` | `String` | no |  | Por ejemplo `left` o `inner`. |\n| `a` | `String` | yes |  | La columna de la tabla principal. |\n| `b` | `String` | yes |  | La columna de la tabla unida. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `{ type: 'join', name, table, join: jointype, on: [a, b] }`. Cómo construye el adaptador el join y dónde pone los datos unidos depende del adaptador.\n\nExample: Join\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFiltra por una columna de permisos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `type` | `String` | yes |  | Letras como `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roles o ids. |\n| `userid` | `String` | no |  | Un id de usuario que el adaptador también puede aceptar. |\n| `required` | `Boolean` | no | `true` | Si el permiso es obligatorio. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade un filtro `permit` para una columna que contiene permisos como strings `<type><value>`. `type` es una o varias letras (`R` lectura, `W` escritura, `D` borrado); cada letra se une con cada elemento de `value`, así que `permit('permissions', 'RW', ['admin'])` da `['Radmin', 'Wadmin']`. `userid` y `required` (por defecto `true`) se pasan al adaptador.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nSelecciona las columnas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Por ejemplo `'id,name,email'`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nUna lista de columnas separadas por comas. Llega al adaptador como un array en `filter.fields`.\n\nExample: Campos\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAñade un orden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La columna. |\n| `desc` | `Boolean|String` | no | `false` | Orden descendente. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAñade `name_asc`, o `name_desc` cuando `desc` es `true` o `'desc'`. Llámalo varias veces para más columnas.\n\n`builder.gridsort(sort, [localized])` añade órdenes a partir de un string como `'name_asc,price_desc'` (un elemento sin `_asc`/`_desc` es ascendente); `localized` asocia un nombre de campo a otro nombre de columna.\n\nExample: Ordenar\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Orden de grid\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimita el número de filas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | El número máximo de filas. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAsigna `filter.take` (alias `limit()`). `builder.first()` asigna `take: 1` y hace que la respuesta sea una fila o `null` en lugar de un array.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nAsigna la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | La página, desde 1. |\n| `limit` | `Number` | no |  | Filas por página. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAsigna `skip` a `(page - 1) * take`. Con `limit`, primero asigna `take`. `page` empieza en 1.\n\n`builder.skip(count)` asigna `filter.skip` (el desplazamiento) directamente.\n\nExample: Página\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nAsigna la página a partir de datos del usuario.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | La página, desde 1. |\n| `limit` | `String|Number` | yes |  | Filas por página. |\n| `maxlimit` | `Number` | no |  | El límite máximo y por defecto. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nComo `page()`, pero acepta strings de una query string, usa la página 1 para valores ausentes o incorrectos, limita `limit` a `maxlimit` y usa `maxlimit` cuando falta `limit`.\n\nExample: Paginate\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nAñade un filtro a partir de un valor de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clave en `obj`. |\n| `obj` | `Object` | yes |  | Normalmente la query string. |\n| `type` | `Function|String` | no | `String` | El tipo de la columna. |\n| `key` | `String` | no |  | La columna, cuando es distinta de `name`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nLee `obj[name]` y, cuando es un string no vacío, añade un filtro para la columna `key` (por defecto `name`). `type` es `String` (por defecto), `Number`, `Date`, `Boolean` o un string: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (un filtro `array()`) o `json` (un `search()`).\n\n- `a - b` es `between()`.\n- `a,b,c` es `in()`; para strings es un `or()` de búsquedas.\n- Para strings, `!text` es una coincidencia exacta y el resto de texto es `search()`.\n- Para números y fechas, un `>` o `<` inicial compara.\n- Las fechas aceptan `today`, `yesterday`, una fecha completa, `MM-DD` de este año, un año (mayor que 1000) o un número de mes, y un valor relativo con un espacio como `7 days` (ese día en el pasado). Un solo día coincide desde las 00:00:00 hasta las 23:59:59.\n\nExample: Filtro de grid\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nConstruye campos, filtros, orden y paginación a partir de la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, normalmente `$.query`. |\n| `fields` | `String` | yes |  | Las columnas y tipos permitidos. |\n| `sort` | `String` | no |  | El orden por defecto, por ejemplo `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | El máximo de filas por página. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\n`fields` lista las columnas permitidas con sus tipos, `'id,name,price:number,dtcreated:date'` (el tipo por defecto es `string`). Después:\n\n- `query.fields` elige columnas entre las permitidas; si no, se seleccionan todas las columnas permitidas.\n- Cada columna permitida presente en `query` recibe un `gridfilter()` con su tipo.\n- `query.sort` (por ejemplo `price_desc`) se usa para las columnas permitidas; si no, `sort` es el valor por defecto.\n- Con `maxlimit`, se llama a `paginate(query.page, query.limit, maxlimit)`. Sin él, no se aplica paginación.\n\nUn nombre de columna con `§` está localizado: `§` se mantiene en el nombre de columna enviado al adaptador y se elimina en el nombre usado en la query string.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nConstruye una consulta de grid a partir del esquema de $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Las opciones de una operación de esquema. |\n| `allowedfields` | `String` | no |  | Columnas extra, con tipos opcionales. |\n| `skipfields` | `String` | no |  | Columnas del esquema que se dejan fuera. |\n| `sort` | `String` | no |  | El orden por defecto. |\n| `maxlimit` | `Number` | no | `50` | El máximo de filas por página. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nFunciona como `autoquery()`, pero las columnas y sus tipos vienen del esquema de la operación actual (`$.schema`). Lee `$.query` (o `$.options`). `allowedfields` añade columnas que no están en el esquema (`'name:type,...'`), `skipfields` oculta columnas del esquema. La paginación siempre se aplica, con `maxlimit` 50 por defecto. Cuando el cuarto argumento es un número, es `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nPasa un idioma al adaptador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | El idioma, o un objeto con `language`. |\n| `prefix` | `String` | no |  | Texto antes del idioma. |\n| `skip` | `String` | no |  | El idioma que da un valor vacío. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAsigna `filter.language` a `prefix + value`. `value` puede ser `$` o un controlador; entonces se usa su `language`. Cuando `value` es igual a `skip` (por defecto `_`, consulta `db.language()`), el idioma queda vacío. El adaptador lo usa, por ejemplo, para reemplazar `§` en los nombres de columna.\n\nExample: Idioma\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nPide columnas de las filas modificadas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Por ejemplo `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nAsigna a `filter.returning` un array a partir de una lista separada por comas. El adaptador devuelve estas columnas después de `insert`, `update` o `remove`. Con upsert, un resultado devuelto vacío significa \"no actualizado\".\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepara los datos de un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | Un valor que se pasa a `fn`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nCon `update(table, data, true)`, cuando no se actualizó nada, se llama a `fn(data, param)` antes de insertar los datos. Úsalo para añadir columnas que solo tiene una fila nueva.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nConvierte un resultado vacío en un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | El error. |\n| `reverse` | `Boolean` | no | `false` | Falla cuando existe una fila. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nCuando la respuesta está vacía (ninguna fila, `null`, `0` o un array vacío), la consulta falla con `err` (como string, por ejemplo una clave de error de un recurso o `'404'`). Con `reverse`, la consulta falla cuando la respuesta **no** está vacía. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nGuarda la respuesta bajo una clave de una respuesta de DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clave. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nEn un controlador `DB()`, la respuesta de esta consulta va a `response[name]` en lugar de reemplazar toda la respuesta. `builder.nobind()` deja la respuesta completamente fuera de la respuesta del controlador. No es para `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nLlama a fn con la respuesta si tiene éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nSe llama solo cuando la consulta tiene éxito, antes de `callback()`. En una cadena `DB()` puedes añadir más consultas desde aquí.\n\n`builder.fail(fn)` es su contrapartida: `fn(err)` se llama solo cuando la consulta falla.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nLlama a fn con el resultado de esta consulta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nSe llama con `(err, response)`. También acepta `$`, y entonces usa `$.callback`, así que un error se convierte en el error de la operación.\n\n`builder.done($, fn, [param])` envía un error a `$.invalid(err)` y, si no, llama a `fn(response, param)`.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nDevuelve una promesa de esta consulta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Las opciones de un esquema o de una operación. |\n\nReturns: `Promise`\n\nSe resuelve con la respuesta. Con `$`, un error va a `$.invalid()` y la promesa queda pendiente, así que el resto de la función no se ejecuta. Sin `$`, la promesa se rechaza; el error recibe el nombre `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nEscribe un registro de auditoría tras el éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Las opciones de un esquema o de una operación. |\n| `message` | `String` | no |  | El texto. |\n| `type` | `String` | no |  | El tipo del registro. |\n\nReturns: `QueryBuilder` El builder de la consulta, para encadenar.\n\nCuando la consulta tiene éxito, llama a `$.audit(message, type)`. `message` puede contener argumentos dinámicos (`{user.name}`, `{model.key}`, `{data.key}`...); `data` es el payload de la consulta.\n\nExample: Auditoría\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nLa clase global del query builder SQL.\n\nCada método de `DB()` y `DATA` que empieza una consulta devuelve una instancia. Su prototipo `QueryBuilder.prototype` es global, así que puedes añadir tus propios métodos. La clase del controlador es la global `QueryBuilderDB`.\n\nExample: Método propio\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm931ci61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() et toutes les méthodes du SQL QueryBuilder.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() et toutes les méthodes du SQL QueryBuilder.\n\nLe SQL QueryBuilder décrit une requête avec des méthodes chaînées et la transmet à l'adaptateur enregistré avec `NEWDB()`. Le guide [QueryBuilder](../../guides/querybuilder/) explique comment l'utiliser avec des exemples ; cette page en est la référence exacte.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nEnregistre ou supprime l'adaptateur d'une connexion SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Le nom de la connexion. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, voir la fonction de l'adaptateur. Omets-la pour supprimer l'adaptateur. |\n\nReturns: `undefined`\n\nEnregistre `fn` comme adaptateur de la connexion `name` (par défaut `default`). Le nom `*` est un repli utilisé pour toute connexion sans adaptateur propre. Appeler `NEWDB(name)` sans fonction supprime l'adaptateur. Lorsqu'une requête s'exécute et qu'aucun adaptateur n'existe, elle échoue avec l'erreur `Database is not initialized`.\n\nL'adaptateur est appelé avec `this` défini sur l'objet de requête interne et reçoit les options de l'adaptateur (voir *Options de l'adaptateur*) ainsi qu'un callback.\n\nExample: Un adaptateur par défaut et un adaptateur nommé\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nLa fonction qui exécute une requête sur la base de données.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | La description de la requête. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nTu écris l'adaptateur et l'enregistres avec `NEWDB()`. Il lit `filter` (voir *Options de l'adaptateur*), construit et exécute le SQL, et appelle `callback(err, response)` exactement une fois.\n\nCe que doit contenir `response` dépend de `filter.exec` : un tableau pour `find`, une ligne ou un tableau pour `read` et `check`, `{ items, count }` pour `list`, un nombre pour `count`, et ce que tu juges utile pour le reste. Une `err` arrête une chaîne `DB()` et est transmise aux callbacks de la requête.\n\nExample: Squelette d'un adaptateur\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nLa description d'une requête que reçoit l'adaptateur.\n\nReturns: `Object`\n\n| Champ | Type | Signification |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` ou `drop` |\n| `table` | String | Le nom de la table, sans le préfixe de connexion (vide pour `query`) |\n| `filter` | Array | Les conditions dans leur ordre (voir ci-dessous) |\n| `fields` | Array | Les noms de colonnes de `fields()`, ou vide pour toutes |\n| `sort` | Array | Éléments de la forme `name_asc` ou `name_desc` |\n| `take`, `skip` | Number | Limite et décalage. `list` commence avec `take: 100, skip: 0` |\n| `first` | Boolean | `true` pour `read`, `check` et `first()` : une seule ligne est attendue |\n| `payload` | Object | Les données de `insert` et `update` |\n| `upsert` | Boolean | `true` pour une mise à jour avec upsert |\n| `returning` | Array | Les colonnes de `returning()` |\n| `query`, `params` | String, Array/Object | Le SQL et les arguments de `query()` |\n| `scalar` | Object | `{ type, key, key2 }` de `scalar()` |\n| `command` | String | Le nom de `command()` |\n| `language` | String | La valeur de `language()` |\n| `primarykey` | String | La valeur de `builder.primarykey(name)` |\n| `schema` | String | La valeur de `builder.schema(name)` |\n| `checksum` | String | Un hash de la forme des filtres (sans les valeurs), utile comme clé de cache des requêtes préparées |\n| `debug` | Boolean | `true` après `debug()` |\n\nLes éléments de `filter.filter` ont un `type` : `where` (`name`, `comparer`, `value`), `in` et `notin` (`name`, tableau `value`), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` et `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value` : un tableau d'éléments), `query` (`value` : SQL brut), `join` (`name`, `table`, `join`, `on`) et `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nCrée un contrôleur qui exécute plusieurs requêtes l'une après l'autre.\n\nReturns: `QueryBuilderDB` Le contrôleur.\n\nRenvoie un nouveau contrôleur (alias `DATABASE()`). Chaque méthode que tu appelles dessus ajoute une requête à une file. La file démarre au tick suivant et exécute les requêtes dans l'ordre. Après la dernière, le callback du contrôleur (`callback()`, `promise()` ou `done()`) reçoit l'erreur ou la réponse. Une erreur arrête la file.\n\nPar défaut, chaque requête remplace la réponse ; utilise `builder.set(name)` pour collecter plusieurs réponses, et `builder.nobind()` pour exclure une requête de la réponse. Une requête ajoutée depuis le callback d'une requête précédente est aussi exécutée.\n\nExample: Deux requêtes à la suite\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nUn contrôleur global pour les requêtes isolées.\n\nReturns: `QueryBuilderDB`\n\n`DATA` possède les mêmes méthodes de requête que `DB()` (`find`, `read`, `insert`...), mais chaque requête s'exécute indépendamment dès sa création, sans file. Il est plus rapide que `DB()` car aucun contrôleur n'est créé.\n\nLis le résultat avec les méthodes du builder : `callback()`, `promise()`, `done()`, `data()` ou `fail()`. N'utilise pas `set()` avec `DATA`, ni les méthodes de contrôleur `DATA.callback()`, `DATA.promise()` et `DATA.done()` : `DATA` est partagé par toute l'application.\n\nExample: Une requête isolée\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nRecherche des lignes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `find` (alias `all()`). La réponse est un tableau de lignes.\n\nExample: Find\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nRecherche une page de lignes avec les comptes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `list` avec `take: 100` et `skip: 0`. L'adaptateur renvoie `{ items, count }`, où `count` est le nombre total de lignes correspondantes. Le framework ajoute `page`, `limit` et `pages` (le nombre de pages).\n\nExample: Une page\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nLit une ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `read` (alias `one()`) avec `take: 1`. Lorsque l'adaptateur renvoie un tableau, la réponse est son premier élément ou `null`. Combine-la avec `error('404')`.\n\nExample: Read\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nVérifie si une ligne existe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `check` avec `take: 1`. L'adaptateur ne sélectionne généralement qu'une seule colonne. Utilise-la avec `error()` pour s'arrêter sur une ligne manquante, ou `error(err, true)` pour s'arrêter sur une ligne existante.\n\nExample: E-mail unique\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nExécute une agrégation.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n| `type` | `String` | yes |  | Le type d'agrégation. |\n| `key` | `String` | no | `'*'` | La colonne. |\n| `key2` | `String` | no |  | Une seconde colonne, par exemple pour le regroupement. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `scalar`. L'adaptateur reçoit `filter.scalar = { type, key, key2 }`. La signification de `type` (par exemple `sum`, `min`, `max`, `avg`, `group`) dépend de l'adaptateur.\n\n`db.count(table)` démarre une requête `count` ; la réponse est le nombre renvoyé par l'adaptateur.\n\nExample: Somme\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Comptage\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nInsère une ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n| `data` | `Object` | yes |  | La ligne. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `insert` (alias `ins()`). `data` est transmis à l'adaptateur sous la forme `filter.payload`.\n\nExample: Insertion\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nMet à jour des lignes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Les colonnes modifiées. |\n| `upsert` | `Boolean` | no | `false` | Insérer les données lorsque rien n'a été mis à jour. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `update` (alias `modify()`, `mod()`, `upd()`). `data` est transmis à l'adaptateur sous la forme `filter.payload`. Avec `upsert`, lorsque l'adaptateur renvoie une réponse vide (ou rien depuis `returning`), le framework appelle la fonction de `builder.insert()`, efface les filtres et exécute les données en tant qu'`insert`.\n\nExample: Mise à jour\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nSupprime des lignes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `remove` (alias `rem()`).\n\nExample: Suppression\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nExécute ton propre SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Le nom de la connexion. |\n| `sql` | `String` | yes |  | Le SQL. |\n| `params` | `Array|Object` | no |  | Les arguments pour les placeholders de ton driver. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nEnvoie `sql` en tant que `filter.query` et `params` en tant que `filter.params` à l'adaptateur de `conn`. Quand le deuxième argument est un tableau ou un objet, il est pris comme `params` et la connexion est `default`. Les filtres ajoutés au builder (par exemple `where()`) sont aussi transmis dans `filter.filter`.\n\n`db.command(table, name)` envoie `exec: 'command'` avec `filter.command = name`, pour les opérations de ton adaptateur que les autres méthodes ne couvrent pas.\n\nExample: SQL brut\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Commande\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nSupprime toutes les lignes d'une table.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Le nom de la table. Un préfixe `name/` choisit la connexion, par exemple `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDémarre une requête `truncate` (alias `clear()`). `db.drop(table)` démarre de la même façon une requête `drop`, pour supprimer la table elle-même.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nCrée une requête à partir d'un objet préparé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Le nom de la connexion. |\n| `options` | `Object` | yes |  | La requête préparée. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nCrée un builder à partir des champs de `options` : `table`, `exec`, `fields` (tableau), `sort` (tableau), `skip`, `take`, `query`, `payload`, `upsert`, `returning` et `filter` (un tableau d'éléments de filtre). Contrairement aux autres méthodes, `table` n'a pas de préfixe de connexion ; passe la connexion en tant que `conn`. Place toutes les conditions dans `options.filter`.\n\n`db.exec(options, callback)` exécute immédiatement un objet préparé : il démarre la requête désignée par `options.exec` sur `options.table` (pour `exec: 'query'`, `options.query` contient le SQL), copie les autres champs dans les options de l'adaptateur et appelle `callback(err, response)`. Il ne renvoie rien.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nDéfinit le callback final d'un contrôleur DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` ou `$`. |\n\nReturns: `QueryBuilderDB`\n\nAppelé après la dernière requête, ou après la première erreur, avec `(err, response)`. Accepte aussi `$` ; il utilise alors `$.callback`. Utilise-le uniquement sur `DB()`.\n\nDeux autres façons de terminer un contrôleur `DB()` : `db.promise([$])` renvoie une promesse de la réponse finale (avec `$`, une erreur est transmise à `$.invalid()` et la promesse reste en attente ; sans lui, la promesse est rejetée), et `db.done($, [fn])` envoie une erreur à `$.invalid(err)` et sinon appelle `fn(response)`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nAppelle fn en cas de succès, $.invalid() en cas d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options d'un schéma ou d'une opération. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nDéfinit le callback final d'un contrôleur `DB()` : une erreur est transmise à `$.invalid(err)`, sinon `fn(response)` est appelée.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nActive le mode debug pour les requêtes suivantes.\n\nReturns: `QueryBuilderDB`\n\nDéfinit `filter.debug = true` pour les requêtes créées sur ce contrôleur après l'appel, afin que l'adaptateur puisse afficher le SQL. Pour une seule requête, utilise plutôt `builder.debug()`.\n\n`builder.debug()` définit le flag sur une seule requête.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Debug\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nDéfinit le préfixe et la valeur à ignorer par défaut de builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Texte placé avant la langue. |\n| `skip` | `String` | yes |  | Une langue qui produit une valeur vide (la langue par défaut). |\n\nReturns: `QueryBuilderDB`\n\nLes valeurs sont globales : elles s'appliquent à tout appel ultérieur de `builder.language()` dans l'application, que ce soit sur `DB()` ou sur `DATA`. Les valeurs par défaut sont `prefix: ''` et `skip: '_'`.\n\nExample: Valeurs par défaut\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAjoute une condition.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` ou `<=`. |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'where', name, comparer, value }`. Sans comparateur, c'est `=`. `==` devient `=` et `!=` devient `<>`. Appelée avec un seul argument, elle ajoute une condition brute comme `builder.query()`.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltre par la colonne id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | Une valeur ou un tableau. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nRaccourci pour `where('id', id)`, ou `in('id', id)` lorsque `id` est un tableau. `builder.userid(id)` fait de même pour la colonne `userid`, et `builder.equal(obj)` ajoute `where(key, value)` pour chaque clé d'un objet.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nLa colonne est l'une des valeurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `value` | `Array|Object` | yes |  | Les valeurs. |\n| `key` | `String` | no |  | Prendre cette propriété de chaque objet de `value`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'in', name, value }`. Une valeur unique devient un tableau. Avec `key`, `value` est un tableau d'objets et leur propriété `key` est utilisée.\n\n`builder.notin(name, value, [key])` fait l'inverse, avec les mêmes arguments.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nLa colonne est comprise entre deux valeurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `a` | `Object` | yes |  | La valeur inférieure. |\n| `b` | `Object` | yes |  | La valeur supérieure. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'between', name, a, b }`.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nUne condition sur une colonne de type tableau.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `comparer` | `String` | no | `'&&'` | L'opérateur pour l'adaptateur. |\n| `value` | `Array` | yes |  | Les valeurs. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'array', name, comparer, value }` pour les colonnes qui contiennent des tableaux (par exemple `text[]` dans PostgreSQL). Le comparateur par défaut est `&&` (chevauchement).\n\nExample: Tags\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nRegroupe des conditions reliées par OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAppelle `fn(builder)` ; les conditions ajoutées à l'intérieur vont dans un seul élément `{ type: 'or', value: [...] }`.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nUne recherche textuelle (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `value` | `String` | yes |  | Le texte. |\n| `where` | `String` | no |  | L'indication de position pour l'adaptateur. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'search', name, value, comparer: where }`. `where` indique à l'adaptateur où le texte peut se trouver (par exemple au début ou à la fin) ; sans lui, n'importe où.\n\nExample: Recherche\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nLa colonne a une valeur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'contains', name }` ; l'adaptateur écrit un test de valeur non vide. `builder.empty(name)` ajoute le test inverse `{ type: 'empty', name }`.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nCompare une partie d'une date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne de date. |\n| `comparer` | `String` | no | `'='` | L'opérateur. |\n| `value` | `Number` | yes |  | L'année (ou le mois, le jour, l'heure, la minute). |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` et `minute()` fonctionnent de la même façon. Le comparateur par défaut est `=`.\n\nExample: Dates\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nAjoute une condition SQL brute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | La condition. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'query', value: sql }`. L'adaptateur place le texte tel quel dans la clause WHERE ; n'y mets donc jamais de saisie utilisateur.\n\nExample: Condition brute\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nAjoute une jointure.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom des données jointes. |\n| `table` | `String` | yes |  | La table jointe. |\n| `jointype` | `String` | no |  | Par exemple `left` ou `inner`. |\n| `a` | `String` | yes |  | La colonne de la table principale. |\n| `b` | `String` | yes |  | La colonne de la table jointe. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `{ type: 'join', name, table, join: jointype, on: [a, b] }`. La façon dont l'adaptateur construit la jointure et l'endroit où il place les données jointes dépendent de l'adaptateur.\n\nExample: Jointure\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFiltre par une colonne de permissions.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `type` | `String` | yes |  | Des lettres telles que `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Rôles ou identifiants. |\n| `userid` | `String` | no |  | Un identifiant d'utilisateur que l'adaptateur peut aussi accepter. |\n| `required` | `Boolean` | no | `true` | Indique si la permission est obligatoire. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute un filtre `permit` pour une colonne qui contient des permissions sous forme de chaînes `<type><value>`. `type` est une ou plusieurs lettres (`R` lecture, `W` écriture, `D` suppression) ; chaque lettre est combinée avec chaque élément de `value`, donc `permit('permissions', 'RW', ['admin'])` donne `['Radmin', 'Wadmin']`. `userid` et `required` (par défaut `true`) sont transmis à l'adaptateur.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nSélectionne les colonnes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Par exemple `'id,name,email'`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nUne liste de colonnes séparées par des virgules. Elle est transmise à l'adaptateur sous forme de tableau dans `filter.fields`.\n\nExample: Champs\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAjoute un tri.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonne. |\n| `desc` | `Boolean|String` | no | `false` | Ordre décroissant. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAjoute `name_asc`, ou `name_desc` lorsque `desc` vaut `true` ou `'desc'`. Appelle-la plusieurs fois pour plusieurs colonnes.\n\n`builder.gridsort(sort, [localized])` ajoute des tris à partir d'une chaîne telle que `'name_asc,price_desc'` (un élément sans `_asc`/`_desc` est croissant) ; `localized` associe un nom de champ à un autre nom de colonne.\n\nExample: Tri\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Tri de grille\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimite le nombre de lignes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Le nombre maximal de lignes. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDéfinit `filter.take` (alias `limit()`). `builder.first()` définit `take: 1` et fait de la réponse une seule ligne ou `null` au lieu d'un tableau.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nDéfinit la page.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | La page, à partir de 1. |\n| `limit` | `Number` | no |  | Lignes par page. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDéfinit `skip` à `(page - 1) * take`. Avec `limit`, elle définit d'abord `take`. `page` commence à 1.\n\n`builder.skip(count)` définit directement `filter.skip` (le décalage).\n\nExample: Page\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nDéfinit la page à partir d'une saisie utilisateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | La page, à partir de 1. |\n| `limit` | `String|Number` | yes |  | Lignes par page. |\n| `maxlimit` | `Number` | no |  | La limite maximale et par défaut. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nComme `page()`, mais accepte les chaînes d'une query string, utilise la page 1 pour les valeurs manquantes ou erronées, plafonne `limit` à `maxlimit` et utilise `maxlimit` lorsque `limit` est absent.\n\nExample: Pagination\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nAjoute un filtre à partir d'une valeur texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clé dans `obj`. |\n| `obj` | `Object` | yes |  | Généralement la query string. |\n| `type` | `Function|String` | no | `String` | Le type de la colonne. |\n| `key` | `String` | no |  | La colonne, lorsqu'elle diffère de `name`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nLit `obj[name]` et, s'il s'agit d'une chaîne non vide, ajoute un filtre pour la colonne `key` (par défaut `name`). `type` vaut `String` (par défaut), `Number`, `Date`, `Boolean` ou une chaîne : `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (un filtre `array()`) ou `json` (un `search()`).\n\n- `a - b` correspond à `between()`.\n- `a,b,c` correspond à `in()` ; pour les chaînes, c'est un `or()` de recherches.\n- Pour les chaînes, `!text` est une correspondance exacte et tout autre texte est un `search()`.\n- Pour les nombres et les dates, un `>` ou `<` initial effectue une comparaison.\n- Les dates acceptent `today`, `yesterday`, une date complète, `MM-DD` de l'année en cours, une année (supérieure à 1000) ou un numéro de mois, ainsi qu'une valeur relative avec un espace telle que `7 days` (ce jour dans le passé). Un jour unique correspond de 00:00:00 à 23:59:59.\n\nExample: Filtre de grille\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nConstruit les champs, les filtres, le tri et la pagination à partir de la query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, généralement `$.query`. |\n| `fields` | `String` | yes |  | Les colonnes autorisées et leurs types. |\n| `sort` | `String` | no |  | Le tri par défaut, par exemple `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | Le nombre maximal de lignes par page. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\n`fields` liste les colonnes autorisées avec leurs types, `'id,name,price:number,dtcreated:date'` (le type par défaut est `string`). Ensuite :\n\n- `query.fields` choisit des colonnes parmi celles autorisées ; sinon toutes les colonnes autorisées sont sélectionnées.\n- Chaque colonne autorisée présente dans `query` reçoit un `gridfilter()` avec son type.\n- `query.sort` (par exemple `price_desc`) est utilisé pour les colonnes autorisées ; sinon `sort` est la valeur par défaut.\n- Avec `maxlimit`, `paginate(query.page, query.limit, maxlimit)` est appelée. Sans lui, aucune pagination n'est définie.\n\nUn nom de colonne avec `§` est localisé : `§` reste dans le nom de colonne envoyé à l'adaptateur et est supprimé du nom utilisé dans la query string.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nConstruit une requête de grille à partir du schéma de $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options d'une opération de schéma. |\n| `allowedfields` | `String` | no |  | Colonnes supplémentaires, avec types optionnels. |\n| `skipfields` | `String` | no |  | Colonnes du schéma à exclure. |\n| `sort` | `String` | no |  | Le tri par défaut. |\n| `maxlimit` | `Number` | no | `50` | Le nombre maximal de lignes par page. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nFonctionne comme `autoquery()`, mais les colonnes et leurs types proviennent du schéma de l'opération en cours (`$.schema`). Elle lit `$.query` (ou `$.options`). `allowedfields` ajoute des colonnes absentes du schéma (`'name:type,...'`), `skipfields` masque des colonnes du schéma. La pagination est toujours définie, avec `maxlimit` à 50 par défaut. Lorsque le quatrième argument est un nombre, il s'agit de `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nTransmet une langue à l'adaptateur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | La langue, ou un objet avec `language`. |\n| `prefix` | `String` | no |  | Texte avant la langue. |\n| `skip` | `String` | no |  | La langue qui donne une valeur vide. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDéfinit `filter.language` à `prefix + value`. `value` peut être `$` ou un contrôleur ; sa `language` est alors utilisée. Lorsque `value` est égal à `skip` (par défaut `_`, voir `db.language()`), la langue est vide. L'adaptateur l'utilise, par exemple, pour remplacer `§` dans les noms de colonnes.\n\nExample: Langue\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nDemande des colonnes des lignes modifiées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Par exemple `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nDéfinit `filter.returning` à un tableau issu d'une liste séparée par des virgules. L'adaptateur renvoie ces colonnes après `insert`, `update` ou `remove`. Avec l'upsert, un résultat renvoyé vide signifie « non mis à jour ».\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrépare les données d'un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | Une valeur transmise à `fn`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAvec `update(table, data, true)`, lorsque rien n'a été mis à jour, `fn(data, param)` est appelée avant l'insertion des données. Utilise-la pour ajouter des colonnes propres à une nouvelle ligne.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nFait d'un résultat vide une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | L'erreur. |\n| `reverse` | `Boolean` | no | `false` | Échouer lorsqu'une ligne existe. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nLorsque la réponse est vide (aucune ligne, `null`, `0` ou un tableau vide), la requête échoue avec `err` (sous forme de chaîne, par exemple une clé d'erreur d'une ressource ou `'404'`). Avec `reverse`, la requête échoue lorsque la réponse n'est **pas** vide. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nStocke la réponse sous une clé d'une réponse DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La clé. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nSur un contrôleur `DB()`, la réponse de cette requête va dans `response[name]` au lieu de remplacer la réponse entière. `builder.nobind()` exclut complètement la réponse de celle du contrôleur. Pas pour `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nAppelle fn avec la réponse en cas de succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAppelée uniquement lorsque la requête réussit, avant `callback()`. Dans une chaîne `DB()`, tu peux ajouter d'autres requêtes depuis cet endroit.\n\n`builder.fail(fn)` est son pendant : `fn(err)` n'est appelée que lorsque la requête échoue.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nAppelle fn avec le résultat de cette requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` ou `$`. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nAppelée avec `(err, response)`. Accepte aussi `$` ; elle utilise alors `$.callback`, de sorte qu'une erreur devient l'erreur de l'opération.\n\n`builder.done($, fn, [param])` envoie une erreur à `$.invalid(err)` et sinon appelle `fn(response, param)`.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRenvoie une promesse de cette requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Les options d'un schéma ou d'une opération. |\n\nReturns: `Promise`\n\nEst résolue avec la réponse. Avec `$`, une erreur est transmise à `$.invalid()` et la promesse reste en attente ; le reste de la fonction ne s'exécute donc pas. Sans `$`, la promesse est rejetée ; l'erreur reçoit le nom `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nÉcrit un enregistrement d'audit après un succès.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Les options d'un schéma ou d'une opération. |\n| `message` | `String` | no |  | Le texte. |\n| `type` | `String` | no |  | Le type de l'enregistrement. |\n\nReturns: `QueryBuilder` Le builder de la requête, pour le chaînage.\n\nLorsque la requête réussit, appelle `$.audit(message, type)`. `message` peut contenir des arguments dynamiques (`{user.name}`, `{model.key}`, `{data.key}`...) ; `data` est le payload de la requête.\n\nExample: Audit\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nLa classe globale du query builder SQL.\n\nChaque méthode de `DB()` et de `DATA` qui démarre une requête renvoie une instance. Son prototype `QueryBuilder.prototype` est global ; tu peux donc ajouter tes propres méthodes. La classe du contrôleur est la classe globale `QueryBuilderDB`.\n\nExample: Méthode personnalisée\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm931ci61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() e tutti i metodi del QueryBuilder SQL.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() e tutti i metodi del QueryBuilder SQL.\n\nIl QueryBuilder SQL descrive una query con metodi concatenati e la passa all'adapter registrato con `NEWDB()`. La guida [QueryBuilder](../../guides/querybuilder/) spiega come usarlo con degli esempi; questa pagina è il riferimento preciso.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nRegistra o rimuove l'adapter di una connessione SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Il nome della connessione. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, vedi la funzione adapter. Omettila per rimuovere l'adapter. |\n\nReturns: `undefined`\n\nRegistra `fn` come adapter per la connessione `name` (predefinita `default`). Il nome `*` è un fallback usato per ogni connessione senza un adapter proprio. Chiamare `NEWDB(name)` senza funzione rimuove l'adapter. Quando una query viene eseguita e non esiste alcun adapter, fallisce con l'errore `Database is not initialized`.\n\nL'adapter viene chiamato con `this` impostato sull'oggetto query interno e riceve le opzioni dell'adapter (vedi *Opzioni dell'adapter*) e una callback.\n\nExample: Un adapter predefinito e uno con nome\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nLa funzione che esegue una query sul database.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | La descrizione della query. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nScrivi tu l'adapter e lo registri con `NEWDB()`. Legge `filter` (vedi *Opzioni dell'adapter*), costruisce ed esegue l'SQL e chiama `callback(err, response)` esattamente una volta.\n\nCosa deve contenere `response` dipende da `filter.exec`: un array per `find`, una riga o un array per `read` e `check`, `{ items, count }` per `list`, un numero per `count`, e ciò che ritieni utile per il resto. Un `err` interrompe una catena `DB()` e va alle callback della query.\n\nExample: Scheletro di un adapter\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nLa descrizione di una query che l'adapter riceve.\n\nReturns: `Object`\n\n| Campo | Tipo | Significato |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` o `drop` |\n| `table` | String | Il nome della tabella, senza il prefisso della connessione (vuoto per `query`) |\n| `filter` | Array | Le condizioni nel loro ordine (vedi sotto) |\n| `fields` | Array | I nomi delle colonne di `fields()`, o vuoto per tutte |\n| `sort` | Array | Elementi nella forma `name_asc` o `name_desc` |\n| `take`, `skip` | Number | Limite e offset. `list` inizia con `take: 100, skip: 0` |\n| `first` | Boolean | `true` per `read`, `check` e `first()`: è attesa una sola riga |\n| `payload` | Object | I dati di `insert` e `update` |\n| `upsert` | Boolean | `true` per un aggiornamento con upsert |\n| `returning` | Array | Le colonne di `returning()` |\n| `query`, `params` | String, Array/Object | L'SQL e gli argomenti di `query()` |\n| `scalar` | Object | `{ type, key, key2 }` di `scalar()` |\n| `command` | String | Il nome di `command()` |\n| `language` | String | Il valore di `language()` |\n| `primarykey` | String | Il valore di `builder.primarykey(name)` |\n| `schema` | String | Il valore di `builder.schema(name)` |\n| `checksum` | String | Un hash della forma dei filtri (senza i valori), utile come chiave di cache dei prepared statement |\n| `debug` | Boolean | `true` dopo `debug()` |\n\nGli elementi di `filter.filter` hanno un `type`: `where` (`name`, `comparer`, `value`), `in` e `notin` (`name`, array `value`), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` ed `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: un array di elementi), `query` (`value`: SQL grezzo), `join` (`name`, `table`, `join`, `on`) e `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nCrea un controller che esegue più query una dopo l'altra.\n\nReturns: `QueryBuilderDB` Il controller.\n\nRestituisce un nuovo controller (alias `DATABASE()`). Ogni metodo che chiami su di esso aggiunge una query a una coda. La coda parte al tick successivo ed esegue le query in ordine. Dopo l'ultima, la callback del controller (`callback()`, `promise()` o `done()`) riceve l'errore o la risposta. Un errore interrompe la coda.\n\nPer impostazione predefinita ogni query sostituisce la risposta; usa `builder.set(name)` per raccogliere più risposte e `builder.nobind()` per escludere una query dalla risposta. Viene eseguita anche una query aggiunta dalla callback di una query precedente.\n\nExample: Due query di seguito\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nUn controller globale per le query singole.\n\nReturns: `QueryBuilderDB`\n\n`DATA` ha gli stessi metodi di query di `DB()` (`find`, `read`, `insert`...), ma ogni query viene eseguita da sola appena viene creata, senza coda. È più veloce di `DB()` perché non viene creato alcun controller.\n\nLeggi il risultato con i metodi del builder: `callback()`, `promise()`, `done()`, `data()` o `fail()`. Non usare `set()` con `DATA` e non usare i metodi del controller `DATA.callback()`, `DATA.promise()` e `DATA.done()`: `DATA` è condiviso da tutta l'app.\n\nExample: Una query singola\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nTrova righe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `find` (alias `all()`). La risposta è un array di righe.\n\nExample: Find\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nTrova una pagina di righe con i conteggi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `list` con `take: 100` e `skip: 0`. L'adapter restituisce `{ items, count }`, dove `count` è il numero di tutte le righe corrispondenti. Il framework aggiunge `page`, `limit` e `pages` (il numero di pagine).\n\nExample: Una pagina\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nLegge una riga.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `read` (alias `one()`) con `take: 1`. Quando l'adapter restituisce un array, la risposta è il suo primo elemento oppure `null`. Combinala con `error('404')`.\n\nExample: Read\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nControlla se una riga esiste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `check` con `take: 1`. Di solito l'adapter seleziona una sola colonna. Usala con `error()` per fermarti su una riga mancante, oppure con `error(err, true)` per fermarti su una riga esistente.\n\nExample: E-mail univoca\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nEsegue un'aggregazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n| `type` | `String` | yes |  | Il tipo di aggregazione. |\n| `key` | `String` | no | `'*'` | La colonna. |\n| `key2` | `String` | no |  | Una seconda colonna, ad esempio per il raggruppamento. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `scalar`. L'adapter riceve `filter.scalar = { type, key, key2 }`. Il significato di `type` (ad esempio `sum`, `min`, `max`, `avg`, `group`) dipende dall'adapter.\n\n`db.count(table)` avvia una query `count`; la risposta è il numero restituito dall'adapter.\n\nExample: Somma\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Conteggio\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nInserisce una riga.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n| `data` | `Object` | yes |  | La riga. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `insert` (alias `ins()`). `data` arriva all'adapter come `filter.payload`.\n\nExample: Insert\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAggiorna righe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Le colonne modificate. |\n| `upsert` | `Boolean` | no | `false` | Inserisci i dati quando non è stato aggiornato nulla. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `update` (alias `modify()`, `mod()`, `upd()`). `data` arriva all'adapter come `filter.payload`. Con `upsert`, quando l'adapter restituisce una risposta vuota (o niente da `returning`), il framework chiama la funzione di `builder.insert()`, svuota i filtri ed esegue i dati come `insert`.\n\nExample: Update\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nRimuove righe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `remove` (alias `rem()`).\n\nExample: Remove\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nEsegue il tuo SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Il nome della connessione. |\n| `sql` | `String` | yes |  | L'SQL. |\n| `params` | `Array|Object` | no |  | Gli argomenti per i segnaposto del tuo driver. |\n\nReturns: `QueryBuilder` Il builder della query, per la concatenazione.\n\nInvia `sql` come `filter.query` e `params` come `filter.params` all'adapter di `conn`. Quando il secondo argomento è un array o un oggetto, viene preso come `params` e la connessione è `default`. Anche i filtri aggiunti al builder (per esempio `where()`) vengono passati in `filter.filter`.\n\n`db.command(table, name)` invia `exec: 'command'` con `filter.command = name`, per le operazioni del tuo adapter che gli altri metodi non coprono.\n\nExample: SQL grezzo\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Comando\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nRimuove tutte le righe di una tabella.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Il nome della tabella. Un prefisso `name/` sceglie la connessione, ad esempio `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAvvia una query `truncate` (alias `clear()`). `db.drop(table)` avvia allo stesso modo una query `drop`, per rimuovere la tabella stessa.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nCrea una query da un oggetto preparato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Il nome della connessione. |\n| `options` | `Object` | yes |  | La query preparata. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nCrea un builder dai campi di `options`: `table`, `exec`, `fields` (array), `sort` (array), `skip`, `take`, `query`, `payload`, `upsert`, `returning` e `filter` (un array di elementi di filtro). A differenza degli altri metodi, `table` non ha il prefisso della connessione; passa la connessione come `conn`. Metti tutte le condizioni in `options.filter`.\n\n`db.exec(options, callback)` esegue subito un oggetto preparato: avvia la query indicata da `options.exec` su `options.table` (per `exec: 'query'`, `options.query` contiene l'SQL), copia gli altri campi nelle opzioni dell'adapter e chiama `callback(err, response)`. Non restituisce nulla.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nImposta la callback finale di un controller DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilderDB`\n\nViene chiamata dopo l'ultima query, o dopo il primo errore, con `(err, response)`. Accetta anche `$`, e in quel caso usa `$.callback`. Usala solo su `DB()`.\n\nAltri due modi per concludere un controller `DB()`: `db.promise([$])` restituisce una promise della risposta finale (con `$`, un errore va a `$.invalid()` e la promise resta in sospeso; senza, la promise viene rifiutata), e `db.done($, [fn])` invia un errore a `$.invalid(err)` e altrimenti chiama `fn(response)`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nChiama fn in caso di successo, $.invalid() in caso di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le opzioni di uno schema o di un'operazione. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nImposta la callback finale di un controller `DB()`: un errore va a `$.invalid(err)`, altrimenti viene chiamata `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nAttiva la modalità di debug per le query successive.\n\nReturns: `QueryBuilderDB`\n\nImposta `filter.debug = true` per le query create su questo controller dopo la chiamata, così l'adapter può stampare l'SQL. Su una singola query, usa invece `builder.debug()`.\n\n`builder.debug()` imposta il flag su una sola query.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Debug\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nImposta il prefisso e il valore di skip predefiniti di builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Testo messo prima della lingua. |\n| `skip` | `String` | yes |  | Una lingua che produce un valore vuoto (la lingua predefinita). |\n\nReturns: `QueryBuilderDB`\n\nI valori sono globali: si applicano a ogni successiva chiamata di `builder.language()` nell'app, sia su `DB()` che su `DATA`. I valori predefiniti sono `prefix: ''` e `skip: '_'`.\n\nExample: Valori predefiniti\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nAggiunge una condizione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` o `<=`. |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'where', name, comparer, value }`. Senza operatore di confronto è `=`. `==` diventa `=` e `!=` diventa `<>`. Chiamato con un solo argomento, aggiunge una condizione grezza come `builder.query()`.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltra per la colonna id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | Un valore o un array. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nScorciatoia per `where('id', id)`, oppure `in('id', id)` quando `id` è un array. `builder.userid(id)` fa lo stesso per la colonna `userid`, e `builder.equal(obj)` aggiunge `where(key, value)` per ogni chiave di un oggetto.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nLa colonna è uno dei valori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `value` | `Array|Object` | yes |  | I valori. |\n| `key` | `String` | no |  | Prende questa proprietà da ogni oggetto di `value`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'in', name, value }`. Un valore singolo diventa un array. Con `key`, `value` è un array di oggetti e viene usata la loro proprietà `key`.\n\n`builder.notin(name, value, [key])` è l'opposto, con gli stessi argomenti.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nLa colonna è compresa tra due valori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `a` | `Object` | yes |  | Il valore inferiore. |\n| `b` | `Object` | yes |  | Il valore superiore. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'between', name, a, b }`.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nUna condizione su una colonna array.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `comparer` | `String` | no | `'&&'` | L'operatore per l'adapter. |\n| `value` | `Array` | yes |  | I valori. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'array', name, comparer, value }` per le colonne che contengono array (ad esempio `text[]` in PostgreSQL). L'operatore di confronto predefinito è `&&` (sovrapposizione).\n\nExample: Tag\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nRaggruppa condizioni unite con OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nChiama `fn(builder)`; le condizioni aggiunte al suo interno finiscono in un unico elemento `{ type: 'or', value: [...] }`.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nUna ricerca testuale (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `value` | `String` | yes |  | Il testo. |\n| `where` | `String` | no |  | L'indicazione di posizione per l'adapter. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'search', name, value, comparer: where }`. `where` è un'indicazione per l'adapter su dove può trovarsi il testo (ad esempio all'inizio o alla fine); senza di essa, ovunque.\n\nExample: Search\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nLa colonna ha un valore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'contains', name }`; l'adapter scrive un test per un valore non vuoto. `builder.empty(name)` aggiunge il test opposto `{ type: 'empty', name }`.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nConfronta una parte di una data.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna data. |\n| `comparer` | `String` | no | `'='` | L'operatore. |\n| `value` | `Number` | yes |  | L'anno (o mese, giorno, ora, minuto). |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` e `minute()` funzionano allo stesso modo. L'operatore di confronto predefinito è `=`.\n\nExample: Date\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nAggiunge una condizione SQL grezza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | La condizione. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'query', value: sql }`. L'adapter inserisce il testo nella clausola WHERE così com'è, quindi non metterci mai input degli utenti.\n\nExample: Condizione grezza\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nAggiunge un join.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dei dati uniti. |\n| `table` | `String` | yes |  | La tabella unita. |\n| `jointype` | `String` | no |  | Ad esempio `left` o `inner`. |\n| `a` | `String` | yes |  | La colonna della tabella principale. |\n| `b` | `String` | yes |  | La colonna della tabella unita. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `{ type: 'join', name, table, join: jointype, on: [a, b] }`. Come l'adapter costruisce il join e dove mette i dati uniti dipende dall'adapter.\n\nExample: Join\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFiltra per una colonna di permessi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `type` | `String` | yes |  | Lettere come `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Ruoli o id. |\n| `userid` | `String` | no |  | Un id utente che l'adapter può anche accettare. |\n| `required` | `Boolean` | no | `true` | Se il permesso è obbligatorio. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge un filtro `permit` per una colonna che contiene i permessi come stringhe `<type><value>`. `type` è una o più lettere (`R` lettura, `W` scrittura, `D` eliminazione); ogni lettera viene unita a ogni elemento di `value`, quindi `permit('permissions', 'RW', ['admin'])` dà `['Radmin', 'Wadmin']`. `userid` e `required` (predefinito `true`) vengono passati all'adapter.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nSeleziona le colonne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Ad esempio `'id,name,email'`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nUn elenco di colonne separate da virgole. Arriva all'adapter come array in `filter.fields`.\n\nExample: Fields\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nAggiunge un ordinamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La colonna. |\n| `desc` | `Boolean|String` | no | `false` | Ordine decrescente. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nAggiunge `name_asc`, oppure `name_desc` quando `desc` è `true` o `'desc'`. Chiamalo più volte per più colonne.\n\n`builder.gridsort(sort, [localized])` aggiunge ordinamenti da una stringa come `'name_asc,price_desc'` (un elemento senza `_asc`/`_desc` è crescente); `localized` associa il nome di un campo al nome di un'altra colonna.\n\nExample: Sort\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Grid sort\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nLimita il numero di righe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Il numero massimo di righe. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nImposta `filter.take` (alias `limit()`). `builder.first()` imposta `take: 1` e rende la risposta una riga o `null` invece di un array.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nImposta la pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | La pagina, da 1. |\n| `limit` | `Number` | no |  | Righe per pagina. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nImposta `skip` a `(page - 1) * take`. Con `limit`, imposta prima `take`. `page` parte da 1.\n\n`builder.skip(count)` imposta direttamente `filter.skip` (l'offset).\n\nExample: Page\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nImposta la pagina dall'input dell'utente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | La pagina, da 1. |\n| `limit` | `String|Number` | yes |  | Righe per pagina. |\n| `maxlimit` | `Number` | no |  | Il limite massimo e predefinito. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nCome `page()`, ma accetta stringhe da una query string, usa la pagina 1 per valori mancanti o errati, limita `limit` a `maxlimit` e usa `maxlimit` quando `limit` manca.\n\nExample: Paginate\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nAggiunge un filtro da un valore testuale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La chiave in `obj`. |\n| `obj` | `Object` | yes |  | Di solito la query string. |\n| `type` | `Function|String` | no | `String` | Il tipo della colonna. |\n| `key` | `String` | no |  | La colonna, quando è diversa da `name`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nLegge `obj[name]` e, quando è una stringa non vuota, aggiunge un filtro per la colonna `key` (predefinita `name`). `type` è `String` (predefinito), `Number`, `Date`, `Boolean` o una stringa: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (un filtro `array()`) o `json` (un `search()`).\n\n- `a - b` è `between()`.\n- `a,b,c` è `in()`; per le stringhe è un `or()` di ricerche.\n- Per le stringhe, `!text` è una corrispondenza esatta e qualsiasi altro testo è `search()`.\n- Per numeri e date, un `>` o `<` iniziale effettua un confronto.\n- Le date accettano `today`, `yesterday`, una data completa, `MM-DD` dell'anno corrente, un anno (maggiore di 1000) o il numero di un mese, e un valore relativo con uno spazio come `7 days` (quel giorno nel passato). Un singolo giorno corrisponde dalle 00:00:00 alle 23:59:59.\n\nExample: Grid filter\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nCostruisce campi, filtri, ordinamento e paginazione dalla query string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | La query string, di solito `$.query`. |\n| `fields` | `String` | yes |  | Le colonne ammesse e i tipi. |\n| `sort` | `String` | no |  | L'ordinamento predefinito, ad esempio `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | Il numero massimo di righe per pagina. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\n`fields` elenca le colonne ammesse con i loro tipi, `'id,name,price:number,dtcreated:date'` (il tipo predefinito è `string`). Poi:\n\n- `query.fields` sceglie le colonne tra quelle ammesse; altrimenti vengono selezionate tutte le colonne ammesse.\n- Ogni colonna ammessa presente in `query` riceve un `gridfilter()` con il suo tipo.\n- `query.sort` (ad esempio `price_desc`) viene usato per le colonne ammesse; altrimenti si usa `sort` come predefinito.\n- Con `maxlimit`, viene chiamato `paginate(query.page, query.limit, maxlimit)`. Senza, non viene impostata alcuna paginazione.\n\nIl nome di una colonna con `§` è localizzato: `§` resta nel nome della colonna inviato all'adapter e viene rimosso nel nome usato nella query string.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nCostruisce una query per griglia dallo schema di $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le opzioni di un'operazione di schema. |\n| `allowedfields` | `String` | no |  | Colonne aggiuntive, con tipi facoltativi. |\n| `skipfields` | `String` | no |  | Colonne dello schema da escludere. |\n| `sort` | `String` | no |  | L'ordinamento predefinito. |\n| `maxlimit` | `Number` | no | `50` | Il numero massimo di righe per pagina. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nFunziona come `autoquery()`, ma le colonne e i loro tipi provengono dallo schema dell'operazione corrente (`$.schema`). Legge `$.query` (o `$.options`). `allowedfields` aggiunge colonne che non sono nello schema (`'name:type,...'`), `skipfields` nasconde colonne dello schema. La paginazione viene sempre impostata, con `maxlimit` 50 come predefinito. Quando il quarto argomento è un numero, è `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nPassa una lingua all'adapter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | La lingua, o un oggetto con `language`. |\n| `prefix` | `String` | no |  | Testo prima della lingua. |\n| `skip` | `String` | no |  | La lingua che dà un valore vuoto. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nImposta `filter.language` a `prefix + value`. `value` può essere `$` o un controller; in quel caso viene usata la sua `language`. Quando `value` è uguale a `skip` (per impostazione predefinita `_`, vedi `db.language()`), la lingua è vuota. L'adapter la usa, ad esempio, per sostituire `§` nei nomi delle colonne.\n\nExample: Language\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nRichiede colonne delle righe modificate.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Ad esempio `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nImposta `filter.returning` a un array ricavato da un elenco separato da virgole. L'adapter restituisce queste colonne dopo `insert`, `update` o `remove`. Con l'upsert, un risultato restituito vuoto significa \"non aggiornato\".\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPrepara i dati di un upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | Un valore passato a `fn`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nCon `update(table, data, true)`, quando non è stato aggiornato nulla, viene chiamata `fn(data, param)` prima che i dati vengano inseriti. Usala per aggiungere colonne che ha solo una nuova riga.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nRende un risultato vuoto un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | L'errore. |\n| `reverse` | `Boolean` | no | `false` | Fallisce quando una riga esiste. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nQuando la risposta è vuota (nessuna riga, `null`, `0` o un array vuoto), la query fallisce con `err` (come stringa, ad esempio la chiave di errore di una risorsa o `'404'`). Con `reverse`, la query fallisce quando la risposta **non** è vuota. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nSalva la risposta in una chiave di una risposta DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | La chiave. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nSu un controller `DB()`, la risposta di questa query va in `response[name]` invece di sostituire l'intera risposta. `builder.nobind()` esclude completamente la risposta dalla risposta del controller. Non per `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nChiama fn con la risposta in caso di successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nViene chiamata solo quando la query ha successo, prima di `callback()`. In una catena `DB()` puoi aggiungere altre query da qui.\n\n`builder.fail(fn)` è la controparte: `fn(err)` viene chiamata solo quando la query fallisce.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nChiama fn con il risultato di questa query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` o `$`. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nViene chiamata con `(err, response)`. Accetta anche `$`, e in quel caso usa `$.callback`, così un errore diventa l'errore dell'operazione.\n\n`builder.done($, fn, [param])` invia un errore a `$.invalid(err)` e altrimenti chiama `fn(response, param)`.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nRestituisce una promise di questa query.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Le opzioni di uno schema o di un'operazione. |\n\nReturns: `Promise`\n\nSi risolve con la risposta. Con `$`, un errore va a `$.invalid()` e la promise resta in sospeso, quindi il resto della funzione non viene eseguito. Senza `$`, la promise viene rifiutata; l'errore riceve il nome `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nScrive un record di audit dopo il successo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le opzioni di uno schema o di un'operazione. |\n| `message` | `String` | no |  | Il testo. |\n| `type` | `String` | no |  | Il tipo del record. |\n\nReturns: `QueryBuilder` Il builder della query, per concatenare le chiamate.\n\nQuando la query ha successo, chiama `$.audit(message, type)`. `message` può contenere argomenti dinamici (`{user.name}`, `{model.key}`, `{data.key}`...); `data` è il payload della query.\n\nExample: Audit\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nLa classe globale del query builder SQL.\n\nOgni metodo di `DB()` e `DATA` che avvia una query restituisce un'istanza. Il suo prototipo `QueryBuilder.prototype` è globale, quindi puoi aggiungere metodi tuoi. La classe del controller è la globale `QueryBuilderDB`.\n\nExample: Metodo personalizzato\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm931ci61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/querybuilder/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"QueryBuilder","summary":"DATA, DB(), NEWDB() a všetky metódy SQL QueryBuildera.","markdown":"---\ntitle: QueryBuilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/querybuilder/\nupdated: 2026-11-19T20:13:41.295Z\n---\n\n# QueryBuilder\n\n> DATA, DB(), NEWDB() a všetky metódy SQL QueryBuildera.\n\nSQL QueryBuilder opisuje dotaz reťazenými metódami a odovzdá ho adaptéru registrovanému cez `NEWDB()`. Návod [QueryBuilder](../../guides/querybuilder/) vysvetľuje jeho použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### NEWDB([name], [fn])\n\nType: `method`\n\nZaregistruje alebo odstráni adaptér SQL pripojenia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `'default'` | Názov pripojenia. |\n| `fn` | `Function` | no |  | `function(filter, callback)`, pozri funkciu adaptéra. Vynechaj ju, ak chceš adaptér odstrániť. |\n\nReturns: `undefined`\n\nZaregistruje `fn` ako adaptér pre pripojenie `name` (predvolene `default`). Názov `*` je záloha, ktorá sa použije pre každé pripojenie bez vlastného adaptéra. Volanie `NEWDB(name)` bez funkcie adaptér odstráni. Keď sa dotaz spustí a žiadny adaptér neexistuje, zlyhá s chybou `Database is not initialized`.\n\nAdaptér sa volá s `this` nastaveným na interný objekt dotazu a dostane voľby adaptéra (pozri *Voľby adaptéra*) a callback.\n\nExample: Predvolený a pomenovaný adaptér\n```js\nNEWDB(function(filter, callback) {\n\tpgadapter(CONF.database, filter, callback);\n});\n\nNEWDB('analytics', function(filter, callback) {\n\tpgadapter(CONF.database_analytics, filter, callback);\n});\n\n// Remove\nNEWDB('analytics');\n```\n\n### function(filter, callback)\n\nType: `delegate`\n\nFunkcia, ktorá spustí dotaz nad databázou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filter` | `Object` | yes |  | Opis dotazu. |\n| `callback` | `Function` | yes |  | `function(err, response)`. |\n\nReturns: `undefined`\n\nAdaptér napíšeš ty a zaregistruješ ho cez `NEWDB()`. Načíta `filter` (pozri *Voľby adaptéra*), zostaví a spustí SQL a zavolá `callback(err, response)` práve raz.\n\nČo musí `response` obsahovať, závisí od `filter.exec`: pole pre `find`, riadok alebo pole pre `read` a `check`, `{ items, count }` pre `list`, číslo pre `count` a pre ostatné to, čo považuješ za užitočné. `err` zastaví reťaz `DB()` a ide do callbackov dotazu.\n\nExample: Kostra adaptéra\n```js\nNEWDB(function(filter, callback) {\n\tvar sql;\n\tswitch (filter.exec) {\n\t\tcase 'query':\n\t\t\tclient.query(filter.query, filter.params, (err, res) => callback(err, res && res.rows));\n\t\t\treturn;\n\t\tcase 'find':\n\t\tcase 'read':\n\t\tcase 'check':\n\t\t\tsql = 'SELECT ' + (filter.fields ? filter.fields.join(',') : '*') + ' FROM ' + filter.table + where(filter.filter);\n\t\t\tif (filter.sort)\n\t\t\t\tsql += ' ORDER BY ' + filter.sort.map(s => s.replace(/_(asc|desc)$/, ' $1')).join(',');\n\t\t\tif (filter.take)\n\t\t\t\tsql += ' LIMIT ' + filter.take;\n\t\t\tif (filter.skip)\n\t\t\t\tsql += ' OFFSET ' + filter.skip;\n\t\t\tbreak;\n\t\t// ... count, list, insert, update, remove\n\t}\n\tclient.query(sql, (err, res) => callback(err, res && res.rows));\n});\n```\n\n### filter {Object}\n\nType: `type`\n\nOpis dotazu, ktorý dostane adaptér.\n\nReturns: `Object`\n\n| Pole | Typ | Význam |\n| --- | --- | --- |\n| `exec` | String | `find`, `list`, `read`, `check`, `count`, `scalar`, `insert`, `update`, `remove`, `query`, `command`, `truncate` alebo `drop` |\n| `table` | String | Názov tabuľky bez prefixu pripojenia (pri `query` prázdny) |\n| `filter` | Array | Podmienky v ich poradí (pozri nižšie) |\n| `fields` | Array | Názvy stĺpcov z `fields()` alebo prázdne pre všetky |\n| `sort` | Array | Položky v tvare `name_asc` alebo `name_desc` |\n| `take`, `skip` | Number | Limit a posun. `list` začína s `take: 100, skip: 0` |\n| `first` | Boolean | `true` pre `read`, `check` a `first()`: očakáva sa jeden riadok |\n| `payload` | Object | Dáta pre `insert` a `update` |\n| `upsert` | Boolean | `true` pre aktualizáciu s upsertom |\n| `returning` | Array | Stĺpce z `returning()` |\n| `query`, `params` | String, Array/Object | SQL a argumenty z `query()` |\n| `scalar` | Object | `{ type, key, key2 }` zo `scalar()` |\n| `command` | String | Názov z `command()` |\n| `language` | String | Hodnota z `language()` |\n| `primarykey` | String | Hodnota z `builder.primarykey(name)` |\n| `schema` | String | Hodnota z `builder.schema(name)` |\n| `checksum` | String | Hash tvaru filtrov (bez hodnôt), užitočný ako kľúč cache pre prepared statements |\n| `debug` | Boolean | `true` po `debug()` |\n\nPoložky `filter.filter` majú `type`: `where` (`name`, `comparer`, `value`), `in` a `notin` (`name`, pole `value`), `between` (`name`, `a`, `b`), `array` (`name`, `comparer`, `value`), `search` (`name`, `value`, `comparer`), `contains` a `empty` (`name`), `year`, `month`, `day`, `hour`, `minute` (`name`, `comparer`, `value`), `or` (`value`: pole položiek), `query` (`value`: surové SQL), `join` (`name`, `table`, `join`, `on`) a `permit` (`name`, `value`, `userid`, `required`).\n\n### DB()\n\nType: `method`\n\nVytvorí kontrolér, ktorý spúšťa viac dotazov jeden po druhom.\n\nReturns: `QueryBuilderDB` Kontrolér.\n\nVráti nový kontrolér (alias `DATABASE()`). Každá metóda, ktorú na ňom zavoláš, pridá dotaz do fronty. Fronta sa spustí v ďalšom ticku a vykoná dotazy v poradí. Po poslednom dostane chybu alebo odpoveď callback kontroléra (`callback()`, `promise()` alebo `done()`). Chyba frontu zastaví.\n\nPredvolene každý dotaz nahradí odpoveď; na zbieranie viacerých odpovedí použi `builder.set(name)` a na vynechanie dotazu z odpovede `builder.nobind()`. Spustí sa aj dotaz pridaný z callbacku predchádzajúceho dotazu.\n\nExample: Dva dotazy za sebou\n```js\nvar db = DB();\ndb.insert('tbl_user', model);\ndb.insert('tbl_user_role', { userid: model.id, role: 'user' });\ndb.callback(function(err) {\n\t$.success();\n});\n```\n\n### DATA\n\nType: `property`\n\nGlobálny kontrolér pre jednotlivé dotazy.\n\nReturns: `QueryBuilderDB`\n\n`DATA` má rovnaké metódy dotazov ako `DB()` (`find`, `read`, `insert`...), ale každý dotaz beží samostatne hneď po vytvorení, bez fronty. Je rýchlejší ako `DB()`, pretože sa nevytvára žiadny kontrolér.\n\nVýsledok čítaj metódami buildera: `callback()`, `promise()`, `done()`, `data()` alebo `fail()`. Nepoužívaj `set()` s `DATA` a nepoužívaj metódy kontroléra `DATA.callback()`, `DATA.promise()` a `DATA.done()`: `DATA` zdieľa celá aplikácia.\n\nExample: Jednotlivý dotaz\n```js\nvar user = await DATA.read('tbl_user').id(id).promise();\n```\n\n### db.find(table)\n\nType: `method`\n\nNájde riadky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `find` (alias `all()`). Odpoveď je pole riadkov.\n\nExample: Find\n```js\nDATA.find('tbl_product').where('category', 'phones').sort('name').callback(console.log);\n```\n\n### db.list(table)\n\nType: `method`\n\nNájde jednu stranu riadkov s počtami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `list` s `take: 100` a `skip: 0`. Adaptér vráti `{ items, count }`, kde `count` je počet všetkých zodpovedajúcich riadkov. Framework pridá `page`, `limit` a `pages` (počet strán).\n\nExample: Strana\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 50).callback(function(err, response) {\n\t// response.items, response.count, response.page, response.pages, response.limit\n});\n```\n\n### db.read(table)\n\nType: `method`\n\nNačíta jeden riadok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `read` (alias `one()`) s `take: 1`. Keď adaptér vráti pole, odpoveď je jeho prvá položka alebo `null`. Kombinuj ho s `error('404')`.\n\nExample: Read\n```js\nDATA.read('tbl_user').fields('id,name').id($.id).error('404').callback($.callback);\n```\n\n### db.check(table)\n\nType: `method`\n\nOverí, či riadok existuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `check` s `take: 1`. Adaptér zvyčajne vyberá iba jeden stĺpec. Použi ho s `error()`, ak chceš skončiť pri chýbajúcom riadku, alebo s `error(err, true)`, ak chceš skončiť pri existujúcom.\n\nExample: Jedinečný e-mail\n```js\nDATA.check('tbl_user').where('email', model.email).error('E-mail is already used', true).promise($);\n```\n\n### db.scalar(table, type, [key], [key2])\n\nType: `method`\n\nSpustí agregáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n| `type` | `String` | yes |  | Druh agregácie. |\n| `key` | `String` | no | `'*'` | Stĺpec. |\n| `key2` | `String` | no |  | Druhý stĺpec, napríklad na zoskupenie. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `scalar`. Adaptér dostane `filter.scalar = { type, key, key2 }`. Význam `type` (napríklad `sum`, `min`, `max`, `avg`, `group`) závisí od adaptéra.\n\n`db.count(table)` spustí dotaz `count`; odpoveď je číslo, ktoré vráti adaptér.\n\nExample: Súčet\n```js\nDATA.scalar('tbl_order', 'sum', 'price').where('status', 'paid').callback(console.log);\n```\n\nExample: Počet\n```js\nDATA.count('tbl_order').where('status', 'new').callback(console.log);\n```\n\n### db.insert(table, data)\n\nType: `method`\n\nVloží riadok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Riadok. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `insert` (alias `ins()`). `data` ide do adaptéra ako `filter.payload`.\n\nExample: Insert\n```js\nDATA.insert('tbl_user', { id: UID(), name: model.name, dtcreated: NOW }).callback($.done());\n```\n\n### db.update(table, data, [upsert])\n\nType: `method`\n\nAktualizuje riadky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n| `data` | `Object` | yes |  | Zmenené stĺpce. |\n| `upsert` | `Boolean` | no | `false` | Vložiť dáta, keď sa nič neaktualizovalo. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `update` (aliasy `modify()`, `mod()`, `upd()`). `data` ide do adaptéra ako `filter.payload`. S `upsert`, keď adaptér vráti prázdnu odpoveď (alebo nič z `returning`), framework zavolá funkciu z `builder.insert()`, vymaže filtre a spustí dáta ako `insert`.\n\nExample: Update\n```js\nDATA.modify('tbl_user', { name: model.name, dtupdated: NOW }).id($.id).error('404').done($, () => $.success());\n```\n\n### db.remove(table)\n\nType: `method`\n\nOdstráni riadky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `remove` (alias `rem()`).\n\nExample: Remove\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### db.query([conn], sql, [params])\n\nType: `method`\n\nSpustí tvoje vlastné SQL.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Názov spojenia. |\n| `sql` | `String` | yes |  | SQL. |\n| `params` | `Array|Object` | no |  | Argumenty pre zástupné symboly tvojho ovládača. |\n\nReturns: `QueryBuilder` Builder dotazu, na reťazenie.\n\nPošle `sql` ako `filter.query` a `params` ako `filter.params` adaptéru `conn`. Keď je druhý argument pole alebo objekt, berie sa ako `params` a spojenie je `default`. Filtre pridané do buildera (napríklad `where()`) sa tiež odovzdajú vo `filter.filter`.\n\n`db.command(table, name)` pošle `exec: 'command'` s `filter.command = name` pre operácie tvojho adaptéra, ktoré ostatné metódy nepokrývajú.\n\nExample: Surové SQL\n```js\nDATA.query('SELECT id, name FROM tbl_user WHERE email=$1', [email]).first().callback(console.log);\nDATA.query('logs', 'TRUNCATE tbl_request').callback(console.log);\n```\n\nExample: Príkaz\n```js\nDATA.command('tbl_product', 'reindex').callback(console.log);\n```\n\n### db.truncate(table)\n\nType: `method`\n\nOdstráni všetky riadky tabuľky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `table` | `String` | yes |  | Názov tabuľky. Prefix `name/` vyberá pripojenie, napríklad `logs/tbl_request`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSpustí dotaz `truncate` (alias `clear()`). `db.drop(table)` rovnakým spôsobom spustí dotaz `drop`, ktorý odstráni samotnú tabuľku.\n\nExample: Truncate\n```js\nDATA.truncate('tbl_log').callback(console.log);\n```\n\n### db.load([conn], options)\n\nType: `method`\n\nVytvorí dotaz z pripraveného objektu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `conn` | `String` | no | `'default'` | Názov pripojenia. |\n| `options` | `Object` | yes |  | Pripravený dotaz. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nVytvorí builder z polí `options`: `table`, `exec`, `fields` (pole), `sort` (pole), `skip`, `take`, `query`, `payload`, `upsert`, `returning` a `filter` (pole položiek filtra). Na rozdiel od ostatných metód nemá `table` prefix pripojenia; pripojenie odovzdaj ako `conn`. Všetky podmienky daj do `options.filter`.\n\n`db.exec(options, callback)` spustí pripravený objekt okamžite: spustí dotaz pomenovaný v `options.exec` nad `options.table` (pri `exec: 'query'` obsahuje SQL `options.query`), skopíruje ostatné polia do volieb adaptéra a zavolá `callback(err, response)`. Nič nevracia.\n\nExample: Load\n```js\nDATA.load({ table: 'tbl_user', exec: 'find', fields: ['id', 'name'], take: 10, filter: [{ type: 'where', name: 'isremoved', comparer: '=', value: false }] }).callback(console.log);\n```\n\nExample: Exec\n```js\nDATA.exec({ exec: 'find', table: 'tbl_user', take: 5 }, console.log);\n```\n\n### db.callback(fn)\n\nType: `method`\n\nNastaví záverečný callback kontroléra DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` alebo `$`. |\n\nReturns: `QueryBuilderDB`\n\nVolá sa po poslednom dotaze alebo po prvej chybe s `(err, response)`. Prijíma aj `$`, vtedy použije `$.callback`. Používaj ho iba na `DB()`.\n\nDva ďalšie spôsoby, ako ukončiť kontrolér `DB()`: `db.promise([$])` vráti promise výslednej odpovede (s `$` ide chyba do `$.invalid()` a promise zostane nevyriešený; bez neho sa promise zamietne) a `db.done($, [fn])` pošle chybu do `$.invalid(err)`, inak zavolá `fn(response)`.\n\nExample: Callback\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.find('tbl_role').where('userid', id).set('roles');\ndb.callback($);\n```\n\nExample: Await\n```js\nvar db = DB();\ndb.remove('tbl_user_role').where('userid', $.id);\ndb.remove('tbl_user').id($.id);\nawait db.promise($);\n$.success();\n```\n\n### db.done($, [fn])\n\nType: `method`\n\nPri úspechu zavolá fn, pri chybe $.invalid().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby schémy alebo operácie. |\n| `fn` | `Function` | no |  | `function(response)`. |\n\nReturns: `QueryBuilderDB`\n\nNastaví záverečný callback kontroléra `DB()`: chyba ide do `$.invalid(err)`, inak sa zavolá `fn(response)`.\n\nExample: Done\n```js\nvar db = DB();\ndb.update('tbl_user', { isremoved: true }).id($.id);\ndb.done($, () => $.success());\n```\n\n### db.debug()\n\nType: `method`\n\nZapne režim ladenia pre nasledujúce dotazy.\n\nReturns: `QueryBuilderDB`\n\nNastaví `filter.debug = true` pre dotazy vytvorené na tomto kontroléri po volaní, takže adaptér môže vypísať SQL. Pre jeden dotaz použi namiesto toho `builder.debug()`.\n\n`builder.debug()` nastaví príznak iba pre jeden dotaz.\n\nExample: Debug\n```js\nvar db = DB().debug();\ndb.find('tbl_user').take(1);\n```\n\nExample: Debug\n```js\nDATA.find('tbl_user').where('email', email).debug().callback(console.log);\n```\n\n### db.language(prefix, skip)\n\nType: `method`\n\nNastaví predvolený prefix a hodnotu skip pre builder.language().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `prefix` | `String` | yes |  | Text vložený pred jazyk. |\n| `skip` | `String` | yes |  | Jazyk, ktorý dá prázdnu hodnotu (predvolený jazyk). |\n\nReturns: `QueryBuilderDB`\n\nHodnoty sú globálne: platia pre každé neskoršie volanie `builder.language()` v aplikácii, či už na `DB()` alebo `DATA`. Predvolené hodnoty sú `prefix: ''` a `skip: '_'`.\n\nExample: Predvolené hodnoty\n```js\n// definitions/db.js\nDATA.language('_', 'en');\n// DATA.find(...).language('sk') gives filter.language = '_sk', and 'en' gives ''\n```\n\n### builder.where(name, [comparer], value)\n\nType: `method`\n\nPridá podmienku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `comparer` | `String` | no | `'='` | `=`, `<>`, `>`, `<`, `>=` alebo `<=`. |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'where', name, comparer, value }`. Bez porovnávacieho operátora je to `=`. `==` sa stane `=` a `!=` sa stane `<>`. Pri volaní s jedným argumentom pridá surovú podmienku ako `builder.query()`.\n\nExample: Where\n```js\nDATA.find('tbl_order').where('status', 'paid').where('price', '>=', 100).callback(console.log);\n```\n\n### builder.id(id)\n\nType: `method`\n\nFiltruje podľa stĺpca id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `Object|Array` | yes |  | Jedna hodnota alebo pole. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nSkratka pre `where('id', id)` alebo `in('id', id)`, keď je `id` pole. `builder.userid(id)` robí to isté pre stĺpec `userid` a `builder.equal(obj)` pridá `where(key, value)` pre každý kľúč objektu.\n\nExample: Id\n```js\nDATA.read('tbl_user').id($.id).callback($.callback);\nDATA.find('tbl_order').equal({ userid: $.user.id, status: 'new' }).callback($.callback);\n```\n\n### builder.in(name, value, [key])\n\nType: `method`\n\nStĺpec má jednu z hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `value` | `Array|Object` | yes |  | Hodnoty. |\n| `key` | `String` | no |  | Vezme túto vlastnosť z každého objektu vo `value`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'in', name, value }`. Jedna hodnota sa stane poľom. S `key` je `value` pole objektov a použije sa ich vlastnosť `key`.\n\n`builder.notin(name, value, [key])` je opak, s rovnakými argumentmi.\n\nExample: In\n```js\nDATA.find('tbl_product').in('id', items, 'productid').callback(console.log);\n```\n\nExample: Not in\n```js\nDATA.find('tbl_user').notin('role', ['admin', 'root']).callback(console.log);\n```\n\n### builder.between(name, a, b)\n\nType: `method`\n\nStĺpec je medzi dvoma hodnotami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `a` | `Object` | yes |  | Dolná hodnota. |\n| `b` | `Object` | yes |  | Horná hodnota. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'between', name, a, b }`.\n\nExample: Between\n```js\nDATA.find('tbl_order').between('dtcreated', NOW.add('-7 days'), NOW).callback(console.log);\n```\n\n### builder.array(name, [comparer], value)\n\nType: `method`\n\nPodmienka na stĺpec s poľom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `comparer` | `String` | no | `'&&'` | Operátor pre adaptér. |\n| `value` | `Array` | yes |  | Hodnoty. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'array', name, comparer, value }` pre stĺpce, ktoré obsahujú polia (napríklad `text[]` v PostgreSQL). Predvolený porovnávací operátor je `&&` (prekryv).\n\nExample: Tagy\n```js\nDATA.find('tbl_article').array('tags', ['news', 'sport']).callback(console.log);\n```\n\n### builder.or(fn)\n\nType: `method`\n\nZoskupí podmienky spojené cez OR.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(builder)`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nZavolá `fn(builder)`; podmienky pridané vo vnútri idú do jednej položky `{ type: 'or', value: [...] }`.\n\nExample: Or\n```js\nDATA.find('tbl_user').or(function(builder) {\n\tbuilder.where('email', login);\n\tbuilder.where('phone', login);\n}).callback(console.log);\n```\n\n### builder.search(name, value, [where])\n\nType: `method`\n\nTextové vyhľadávanie (LIKE).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `value` | `String` | yes |  | Text. |\n| `where` | `String` | no |  | Nápoveda pozície pre adaptér. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'search', name, value, comparer: where }`. `where` je pre adaptér nápoveda, kde sa text môže nachádzať (napríklad na začiatku alebo na konci); bez nej kdekoľvek.\n\nExample: Vyhľadávanie\n```js\nDATA.find('tbl_product').search('name', $.query.q).callback($.callback);\n```\n\n### builder.contains(name)\n\nType: `method`\n\nStĺpec má hodnotu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'contains', name }`; adaptér zapíše test na neprázdnu hodnotu. `builder.empty(name)` pridá opačný test `{ type: 'empty', name }`.\n\nExample: Contains\n```js\nDATA.find('tbl_user').contains('phone').empty('dtremoved').callback(console.log);\n```\n\n### builder.year(name, [comparer], value)\n\nType: `method`\n\nPorovná časť dátumu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Dátumový stĺpec. |\n| `comparer` | `String` | no | `'='` | Operátor. |\n| `value` | `Number` | yes |  | Rok (alebo mesiac, deň, hodina, minúta). |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'year', name, comparer, value }`. `month()`, `day()`, `hour()` a `minute()` fungujú rovnako. Predvolený porovnávací operátor je `=`.\n\nExample: Dátumy\n```js\nDATA.find('tbl_order').year('dtcreated', 2022).month('dtcreated', '>=', 6).callback(console.log);\n```\n\n### builder.query(sql)\n\nType: `method`\n\nPridá surovú SQL podmienku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `sql` | `String` | yes |  | Podmienka. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'query', value: sql }`. Adaptér vloží text do klauzuly WHERE tak, ako je, preto doň nikdy nedávaj vstup od používateľov.\n\nExample: Surová podmienka\n```js\nDATA.find('tbl_user').query('dtcreated > NOW() - INTERVAL \\'1 day\\'').callback(console.log);\n```\n\n### builder.join(name, table, [jointype], a, b)\n\nType: `method`\n\nPridá join.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pripojených dát. |\n| `table` | `String` | yes |  | Pripojená tabuľka. |\n| `jointype` | `String` | no |  | Napríklad `left` alebo `inner`. |\n| `a` | `String` | yes |  | Stĺpec hlavnej tabuľky. |\n| `b` | `String` | yes |  | Stĺpec pripojenej tabuľky. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `{ type: 'join', name, table, join: jointype, on: [a, b] }`. Ako adaptér zostaví join a kam uloží pripojené dáta, závisí od adaptéra.\n\nExample: Join\n```js\nDATA.find('tbl_order').join('user', 'tbl_user', 'left', 'userid', 'id').callback(console.log);\n```\n\n### builder.permit(name, type, value, [userid], [required])\n\nType: `method`\n\nFiltruje podľa stĺpca s oprávneniami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `type` | `String` | yes |  | Písmená ako `R`, `W`, `D`. |\n| `value` | `Array` | yes |  | Roly alebo id. |\n| `userid` | `String` | no |  | Id používateľa, ktoré adaptér môže tiež akceptovať. |\n| `required` | `Boolean` | no | `true` | Či je oprávnenie povinné. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá filter `permit` pre stĺpec, ktorý obsahuje oprávnenia ako reťazce `<type><value>`. `type` je jedno alebo viac písmen (`R` čítanie, `W` zápis, `D` mazanie); každé písmeno sa spojí s každou položkou `value`, takže `permit('permissions', 'RW', ['admin'])` dá `['Radmin', 'Wadmin']`. `userid` a `required` (predvolene `true`) sa odovzdajú adaptéru.\n\nExample: Permit\n```js\nDATA.find('tbl_document').permit('permissions', 'R', $.user.roles, $.user.id).callback($.callback);\n```\n\n### builder.fields(fields)\n\nType: `method`\n\nVyberie stĺpce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Napríklad `'id,name,email'`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nZoznam stĺpcov oddelených čiarkami. Ide do adaptéra ako pole vo `filter.fields`.\n\nExample: Polia\n```js\nDATA.find('tbl_user').fields('id,name,email').callback(console.log);\n```\n\n### builder.sort(name, [desc])\n\nType: `method`\n\nPridá triedenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Stĺpec. |\n| `desc` | `Boolean|String` | no | `false` | Zostupné poradie. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPridá `name_asc` alebo `name_desc`, keď je `desc` `true` alebo `'desc'`. Pre viac stĺpcov ju zavolaj viackrát.\n\n`builder.gridsort(sort, [localized])` pridá triedenia z reťazca, napríklad `'name_asc,price_desc'` (položka bez `_asc`/`_desc` je vzostupná); `localized` mapuje názov poľa na iný názov stĺpca.\n\nExample: Triedenie\n```js\nDATA.find('tbl_product').sort('category').sort('price', true).callback(console.log);\n```\n\nExample: Triedenie gridu\n```js\nDATA.find('tbl_product').gridsort($.query.sort || 'name_asc').callback($.callback);\n```\n\n### builder.take(count)\n\nType: `method`\n\nObmedzí počet riadkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number` | yes |  | Maximálny počet riadkov. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNastaví `filter.take` (alias `limit()`). `builder.first()` nastaví `take: 1` a odpoveďou bude jeden riadok alebo `null` namiesto poľa.\n\nExample: Take\n```js\nDATA.find('tbl_article').sort('dtcreated', true).take(10).callback(console.log);\nDATA.find('tbl_article').where('slug', slug).first().callback(console.log);\n```\n\n### builder.page(page, [limit])\n\nType: `method`\n\nNastaví stranu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `Number` | yes |  | Strana, od 1. |\n| `limit` | `Number` | no |  | Riadky na stranu. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNastaví `skip` na `(page - 1) * take`. S `limit` najprv nastaví `take`. `page` začína od 1.\n\n`builder.skip(count)` nastaví `filter.skip` (posun) priamo.\n\nExample: Strana\n```js\nDATA.list('tbl_product').page(2, 20).callback(console.log);\n```\n\nExample: Skip\n```js\nDATA.find('tbl_article').skip(20).take(10).callback(console.log);\n```\n\n### builder.paginate(page, limit, [maxlimit])\n\nType: `method`\n\nNastaví stranu podľa vstupu používateľa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `page` | `String|Number` | yes |  | Strana, od 1. |\n| `limit` | `String|Number` | yes |  | Riadky na stranu. |\n| `maxlimit` | `Number` | no |  | Najväčší a zároveň predvolený limit. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nAko `page()`, ale prijíma reťazce z query stringu, pri chýbajúcich alebo zlých hodnotách použije stranu 1, obmedzí `limit` na `maxlimit` a použije `maxlimit`, keď `limit` chýba.\n\nExample: Paginate\n```js\nDATA.list('tbl_product').paginate($.query.page, $.query.limit, 100).callback($.callback);\n```\n\n### builder.gridfilter(name, obj, [type], [key])\n\nType: `method`\n\nPridá filter z textovej hodnoty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Kľúč v `obj`. |\n| `obj` | `Object` | yes |  | Zvyčajne query string. |\n| `type` | `Function|String` | no | `String` | Typ stĺpca. |\n| `key` | `String` | no |  | Stĺpec, ak sa líši od `name`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNačíta `obj[name]` a keď je to neprázdny reťazec, pridá filter pre stĺpec `key` (predvolene `name`). `type` je `String` (predvolene), `Number`, `Date`, `Boolean` alebo reťazec: `string`, `number`, `decimal`, `float`, `date`, `datetime`, `boolean`, `bool`, `[string]` (filter `array()`) alebo `json` (`search()`).\n\n- `a - b` je `between()`.\n- `a,b,c` je `in()`; pri reťazcoch je to `or()` vyhľadávaní.\n- Pri reťazcoch je `!text` presná zhoda a iný text je `search()`.\n- Pri číslach a dátumoch úvodné `>` alebo `<` porovnáva.\n- Dátumy prijímajú `today`, `yesterday`, celý dátum, `MM-DD` tohto roka, rok (viac ako 1000) alebo číslo mesiaca a relatívnu hodnotu s medzerou, napríklad `7 days` (daný deň v minulosti). Jeden deň zodpovedá rozsahu od 00:00:00 do 23:59:59.\n\nExample: Filter gridu\n```js\n// ?price=10 - 50&dtcreated=today&name=phone\nDATA.list('tbl_product')\n\t.gridfilter('name', $.query)\n\t.gridfilter('price', $.query, Number)\n\t.gridfilter('dtcreated', $.query, Date)\n\t.paginate($.query.page, $.query.limit, 50)\n\t.callback($.callback);\n```\n\n### builder.autoquery(query, fields, [sort], [maxlimit])\n\nType: `method`\n\nZostaví polia, filtre, triedenie a stránkovanie z query stringu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `query` | `Object` | yes |  | Query string, zvyčajne `$.query`. |\n| `fields` | `String` | yes |  | Povolené stĺpce a typy. |\n| `sort` | `String` | no |  | Predvolené triedenie, napríklad `'dtcreated_desc'`. |\n| `maxlimit` | `Number` | no |  | Maximálny počet riadkov na stranu. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\n`fields` uvádza povolené stĺpce s ich typmi, `'id,name,price:number,dtcreated:date'` (predvolený typ je `string`). Potom:\n\n- `query.fields` vyberá stĺpce spomedzi povolených; inak sa vyberú všetky povolené stĺpce.\n- Každý povolený stĺpec prítomný v `query` dostane `gridfilter()` so svojím typom.\n- `query.sort` (napríklad `price_desc`) sa použije pre povolené stĺpce; inak je predvolené `sort`.\n- S `maxlimit` sa zavolá `paginate(query.page, query.limit, maxlimit)`. Bez neho sa stránkovanie nenastaví.\n\nNázov stĺpca s `§` je lokalizovaný: `§` zostane v názve stĺpca odoslanom adaptéru a odstráni sa z názvu použitého v query stringu.\n\nExample: Autoquery\n```js\nschema.setQuery(function($) {\n\tDATA.list('tbl_product').autoquery($.query, 'id,name,category,price:number,dtcreated:date', 'dtcreated_desc', 100).callback($.callback);\n});\n```\n\n### builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])\n\nType: `method`\n\nZostaví dotaz pre grid zo schémy $.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby operácie schémy. |\n| `allowedfields` | `String` | no |  | Ďalšie stĺpce, voliteľne s typmi. |\n| `skipfields` | `String` | no |  | Stĺpce schémy, ktoré sa vynechajú. |\n| `sort` | `String` | no |  | Predvolené triedenie. |\n| `maxlimit` | `Number` | no | `50` | Maximálny počet riadkov na stranu. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nFunguje ako `autoquery()`, ale stĺpce a ich typy pochádzajú zo schémy aktuálnej operácie (`$.schema`). Načíta `$.query` (alebo `$.options`). `allowedfields` pridá stĺpce, ktoré nie sú v schéme (`'name:type,...'`), `skipfields` skryje stĺpce schémy. Stránkovanie sa nastaví vždy, predvolene s `maxlimit` 50. Keď je štvrtý argument číslo, je to `maxlimit`.\n\nExample: Autofill\n```js\nNEWSCHEMA('Products', function(schema) {\n\tschema.define('id', 'UID');\n\tschema.define('name', String);\n\tschema.define('price', Number);\n\tschema.setQuery(function($) {\n\t\tDATA.list('tbl_product').autofill($, 'dtcreated:date', null, 'dtcreated_desc', 100).callback($.callback);\n\t});\n});\n```\n\n### builder.language(value, [prefix], [skip])\n\nType: `method`\n\nOdovzdá adaptéru jazyk.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String|Object` | yes |  | Jazyk alebo objekt s `language`. |\n| `prefix` | `String` | no |  | Text pred jazykom. |\n| `skip` | `String` | no |  | Jazyk, ktorý dá prázdnu hodnotu. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNastaví `filter.language` na `prefix + value`. `value` môže byť `$` alebo kontrolér; vtedy sa použije jeho `language`. Keď sa `value` rovná `skip` (predvolene `_`, pozri `db.language()`), jazyk je prázdny. Adaptér ho používa napríklad na nahradenie `§` v názvoch stĺpcov.\n\nExample: Jazyk\n```js\nDATA.find('tbl_product').fields('id,name§').language($).callback($.callback);\n```\n\n### builder.returning(fields)\n\nType: `method`\n\nVyžiada stĺpce zmenených riadkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fields` | `String` | yes |  | Napríklad `'id,dtcreated'`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNastaví `filter.returning` na pole zo zoznamu oddeleného čiarkami. Adaptér vráti tieto stĺpce po `insert`, `update` alebo `remove`. Pri upserte znamená prázdny vrátený výsledok „neaktualizované“.\n\nExample: Returning\n```js\nDATA.insert('tbl_user', model).returning('id').first().callback(console.log);\n```\n\n### builder.insert(fn, [param])\n\nType: `method`\n\nPripraví dáta pre upsert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(data, param)`. |\n| `param` | `Object` | no |  | Hodnota odovzdaná do `fn`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nPri `update(table, data, true)`, keď sa nič neaktualizovalo, sa pred vložením dát zavolá `fn(data, param)`. Použi ju na pridanie stĺpcov, ktoré má iba nový riadok.\n\nExample: Upsert\n```js\nDATA.modify('tbl_setting', { value: value, dtupdated: NOW }, true).id(key).insert(function(data) {\n\tdata.id = key;\n\tdata.dtcreated = NOW;\n}).callback(console.log);\n```\n\n### builder.error(err, [reverse])\n\nType: `method`\n\nZ prázdneho výsledku urobí chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | Chyba. |\n| `reverse` | `Boolean` | no | `false` | Zlyhať, keď riadok existuje. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nKeď je odpoveď prázdna (žiadny riadok, `null`, `0` alebo prázdne pole), dotaz zlyhá s `err` (ako reťazec, napríklad chybový kľúč resource alebo `'404'`). S `reverse` dotaz zlyhá, keď odpoveď **nie je** prázdna. Alias `err()`.\n\nExample: 404\n```js\nDATA.read('tbl_user').id($.id).error('404').callback($.callback);\n```\n\n### builder.set(name)\n\nType: `method`\n\nUloží odpoveď pod kľúč odpovede DB().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Kľúč. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nNa kontroléri `DB()` ide odpoveď tohto dotazu do `response[name]` namiesto toho, aby nahradila celú odpoveď. `builder.nobind()` úplne vynechá odpoveď z odpovede kontroléra. Nie pre `DATA`.\n\nExample: Set\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).set('user');\ndb.count('tbl_order').where('userid', id).set('orders');\ndb.find('tbl_log').where('userid', id).nobind().data(console.log);\ndb.callback(console.log); // { user: {...}, orders: 3 }\n```\n\n### builder.data(fn)\n\nType: `method`\n\nPri úspechu zavolá fn s odpoveďou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nVolá sa iba vtedy, keď dotaz uspeje, pred `callback()`. V reťazi `DB()` odtiaľto môžeš pridávať ďalšie dotazy.\n\n`builder.fail(fn)` je náprotivok: `fn(err)` sa volá iba vtedy, keď dotaz zlyhá.\n\nExample: Data\n```js\nvar db = DB();\ndb.read('tbl_user').id(id).error('404').data(function(user) {\n\tdb.find('tbl_order').where('userid', user.id).set('orders');\n});\ndb.callback($.callback);\n```\n\nExample: Fail\n```js\nDATA.insert('tbl_log', item).fail(err => console.error('log', err));\n```\n\n### builder.callback(fn)\n\nType: `method`\n\nZavolá fn s výsledkom tohto dotazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` alebo `$`. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nVolá sa s `(err, response)`. Prijíma aj `$`, vtedy použije `$.callback`, takže chyba sa stane chybou operácie.\n\n`builder.done($, fn, [param])` pošle chybu do `$.invalid(err)`, inak zavolá `fn(response, param)`.\n\nExample: Callback\n```js\nDATA.find('tbl_user').take(10).callback(function(err, response) {\n\tconsole.log(err, response);\n});\nDATA.find('tbl_user').take(10).callback($);\n```\n\nExample: Done\n```js\nDATA.remove('tbl_user').id($.id).error('404').done($, () => $.success());\n```\n\n### builder.promise([$])\n\nType: `method`\n\nVráti promise tohto dotazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Voľby schémy alebo operácie. |\n\nReturns: `Promise`\n\nSplní sa s odpoveďou. S `$` ide chyba do `$.invalid()` a promise zostane nevyriešený, takže zvyšok funkcie sa nespustí. Bez `$` sa promise zamietne; chyba dostane názov `QueryBuilder(table --> exec)`.\n\nExample: Await\n```js\nschema.setRead(async function($) {\n\tvar user = await DATA.read('tbl_user').id($.id).error('404').promise($);\n\tuser.orders = await DATA.count('tbl_order').where('userid', user.id).promise($);\n\t$.callback(user);\n});\n```\n\n### builder.audit($, [message], [type])\n\nType: `method`\n\nPo úspechu zapíše auditný záznam.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Voľby schémy alebo operácie. |\n| `message` | `String` | no |  | Text. |\n| `type` | `String` | no |  | Typ záznamu. |\n\nReturns: `QueryBuilder` Builder dotazu na reťazenie.\n\nKeď dotaz uspeje, zavolá `$.audit(message, type)`. `message` môže obsahovať dynamické argumenty (`{user.name}`, `{model.key}`, `{data.key}`...); `data` je payload dotazu.\n\nExample: Audit\n```js\nDATA.modify('tbl_user', $.model).id($.id).audit($, 'Updated user {data.name}').done($, () => $.success());\n```\n\n### QueryBuilder\n\nType: `class`\n\nGlobálna trieda SQL query buildera.\n\nKaždá metóda `DB()` a `DATA`, ktorá spúšťa dotaz, vracia inštanciu. Jej prototyp `QueryBuilder.prototype` je globálny, takže doň môžeš pridávať vlastné metódy. Trieda kontroléra je globálna `QueryBuilderDB`.\n\nExample: Vlastná metóda\n```js\nQueryBuilder.prototype.active = function() {\n\treturn this.where('isremoved', false).where('isdisabled', false);\n};\n\nDATA.find('tbl_user').active().callback(console.log);\n```\n","entries":[{"type":"method","name":"NEWDB()","signature":"NEWDB([name], [fn])","since":"","deprecated":false},{"type":"delegate","name":"adapter function","signature":"function(filter, callback)","since":"","deprecated":false},{"type":"type","name":"Adapter options","signature":"filter {Object}","since":"","deprecated":false},{"type":"method","name":"DB()","signature":"DB()","since":"","deprecated":false},{"type":"property","name":"DATA","signature":"DATA","since":"","deprecated":false},{"type":"method","name":"db.find()","signature":"db.find(table)","since":"","deprecated":false},{"type":"method","name":"db.list()","signature":"db.list(table)","since":"","deprecated":false},{"type":"method","name":"db.read()","signature":"db.read(table)","since":"","deprecated":false},{"type":"method","name":"db.check()","signature":"db.check(table)","since":"","deprecated":false},{"type":"method","name":"db.scalar()","signature":"db.scalar(table, type, [key], [key2])","since":"","deprecated":false},{"type":"method","name":"db.insert()","signature":"db.insert(table, data)","since":"","deprecated":false},{"type":"method","name":"db.update()","signature":"db.update(table, data, [upsert])","since":"","deprecated":false},{"type":"method","name":"db.remove()","signature":"db.remove(table)","since":"","deprecated":false},{"type":"method","name":"db.query()","signature":"db.query([conn], sql, [params])","since":"","deprecated":false},{"type":"method","name":"db.truncate()","signature":"db.truncate(table)","since":"","deprecated":false},{"type":"method","name":"db.load()","signature":"db.load([conn], options)","since":"","deprecated":false},{"type":"method","name":"db.callback()","signature":"db.callback(fn)","since":"","deprecated":false},{"type":"method","name":"db.done()","signature":"db.done($, [fn])","since":"","deprecated":false},{"type":"method","name":"db.debug()","signature":"db.debug()","since":"","deprecated":false},{"type":"method","name":"db.language()","signature":"db.language(prefix, skip)","since":"","deprecated":false},{"type":"method","name":"builder.where()","signature":"builder.where(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.id()","signature":"builder.id(id)","since":"","deprecated":false},{"type":"method","name":"builder.in()","signature":"builder.in(name, value, [key])","since":"","deprecated":false},{"type":"method","name":"builder.between()","signature":"builder.between(name, a, b)","since":"","deprecated":false},{"type":"method","name":"builder.array()","signature":"builder.array(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.or()","signature":"builder.or(fn)","since":"","deprecated":false},{"type":"method","name":"builder.search()","signature":"builder.search(name, value, [where])","since":"","deprecated":false},{"type":"method","name":"builder.contains()","signature":"builder.contains(name)","since":"","deprecated":false},{"type":"method","name":"builder.year()","signature":"builder.year(name, [comparer], value)","since":"","deprecated":false},{"type":"method","name":"builder.query()","signature":"builder.query(sql)","since":"","deprecated":false},{"type":"method","name":"builder.join()","signature":"builder.join(name, table, [jointype], a, b)","since":"","deprecated":false},{"type":"method","name":"builder.permit()","signature":"builder.permit(name, type, value, [userid], [required])","since":"","deprecated":false},{"type":"method","name":"builder.fields()","signature":"builder.fields(fields)","since":"","deprecated":false},{"type":"method","name":"builder.sort()","signature":"builder.sort(name, [desc])","since":"","deprecated":false},{"type":"method","name":"builder.take()","signature":"builder.take(count)","since":"","deprecated":false},{"type":"method","name":"builder.page()","signature":"builder.page(page, [limit])","since":"","deprecated":false},{"type":"method","name":"builder.paginate()","signature":"builder.paginate(page, limit, [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.gridfilter()","signature":"builder.gridfilter(name, obj, [type], [key])","since":"","deprecated":false},{"type":"method","name":"builder.autoquery()","signature":"builder.autoquery(query, fields, [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.autofill()","signature":"builder.autofill($, [allowedfields], [skipfields], [sort], [maxlimit])","since":"","deprecated":false},{"type":"method","name":"builder.language()","signature":"builder.language(value, [prefix], [skip])","since":"","deprecated":false},{"type":"method","name":"builder.returning()","signature":"builder.returning(fields)","since":"","deprecated":false},{"type":"method","name":"builder.insert()","signature":"builder.insert(fn, [param])","since":"","deprecated":false},{"type":"method","name":"builder.error()","signature":"builder.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"builder.set()","signature":"builder.set(name)","since":"","deprecated":false},{"type":"method","name":"builder.data()","signature":"builder.data(fn)","since":"","deprecated":false},{"type":"method","name":"builder.callback()","signature":"builder.callback(fn)","since":"","deprecated":false},{"type":"method","name":"builder.promise()","signature":"builder.promise([$])","since":"","deprecated":false},{"type":"method","name":"builder.audit()","signature":"builder.audit($, [message], [type])","since":"","deprecated":false},{"type":"class","name":"QueryBuilder","signature":"QueryBuilder","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-19T20:13:41.295Z"}
{"id":"Jabm6L4vr60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"JSON schemas","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), the jsonschemas/ directory and the supported keywords.","markdown":"---\ntitle: JSON schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# JSON schemas\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), the jsonschemas/ directory and the supported keywords.\n\nJSON schemas validate and convert data. They are loaded from `jsonschemas/*.json` and `jsonschemas/*.txt` files or declared with `NEWJSONSCHEMA()` and `String.toJSONSchema()`, and they are used by `JSONSCHEMA()`, by the `input`, `output`, `params` and `query` options of actions and by Total.js schemas.\n\nRead the guide [JSON schemas](../../guides/json-schemas/) for the inline syntax, the supported keywords and examples.\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValidates and converts a value with a JSON schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Name of a registered JSON schema, or a schema object |\n| `value` | `Object` | yes |  | Data to validate |\n| `callback` | `Function` | no |  | `function(err, response)`; without it a promise is returned |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | An existing error builder to add the errors to |\n\nReturns: `Promise|undefined` A promise when no callback is given\n\n`schema` is the name of a registered schema (a key of `F.jsonschemas`) or a schema object. The value is converted to the types of the schema and the properties that the schema does not declare are removed.\n\nWith a callback, it calls `callback(err, response)`, where `err` is an `ErrorBuilder` or `null`. Without a callback, it returns a promise that resolves with the response or rejects with the `ErrorBuilder`. If the schema does not exist, the error is `404`.\n\n`JSONSCHEMA()` always validates all properties; for partial validation use the `transform()` method of the schema object.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promise\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nRegisters or removes a JSON schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Name of the schema, or a schema object with `$id` |\n| `declaration` | `String` | no |  | Inline declaration such as `'name:String, *email:Email'`; omit it to remove the schema |\n\n- `NEWJSONSCHEMA(object)` registers a schema object under its `$id`.\n- `NEWJSONSCHEMA(name, declaration)` converts an inline declaration with `String.toJSONSchema(name)` and registers it under `name`.\n- `NEWJSONSCHEMA(name)` without a declaration removes the schema.\n\nA schema object registered with `NEWJSONSCHEMA(object)` is stored as it is, without the `transform()` method. Use it with `JSONSCHEMA()`; for actions, prefer a file in `jsonschemas/` or an inline declaration.\n\nExample: Inline declaration\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Remove\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nConverts an inline declaration to a JSON schema object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Name to register the schema under; it is also used in `$id` |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | Base URL of `$id` |\n\nReturns: `Object` The JSON schema object\n\nParses `name:Type` pairs separated by commas or new lines and returns a JSON schema object with `type: 'object'`, `properties`, `required` and a `transform()` method. With `name`, the schema is also registered in `F.jsonschemas`.\n\nThe `$id` is `url + name + '.json'`. The default URL is `CONF.url`, or `https://schemas.totaljs.com/`; without a name a hash of the declaration is used. `$schema` is `https://json-schema.org/draft/2020-12/schema`.\n\n| Syntax | Result |\n| --- | --- |\n| `*name`, `!name` | Required property |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Array of a type |\n| `name:{a\\|b\\|c}` | String enum (`;` works too) |\n| `name:{a:String, b:Number}` | Nested object |\n| `name:[{a:String}]` | Array of nested objects |\n| `name:@Other` | Another Total.js schema, JSON schema or action input |\n\n`@Other` throws an error if nothing with that name exists.\n\nExample: Nested objects and enums\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nValidates a value with this schema object and returns the result synchronously.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Data to validate |\n| `partial` | `Boolean` | no | `false` | Validate only the properties present in the value |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | An existing error builder to add the errors to |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nSchema objects from `jsonschemas/` files and from `String.toJSONSchema()` have this method. It returns `{ error, response }`: `error` is an `ErrorBuilder` with the errors or `null`, and `response` is the converted value.\n\nWith `partial`, properties that are `undefined` in the value are skipped, so missing required properties are not errors. This applies at every level, also to the properties of nested objects.\n\nExample: Partial update\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nAll registered JSON schemas, by name and by `$id`.\n\nReturns: `Object` Schema objects by key\n\nAn object with every registered schema. Files from `jsonschemas/` are stored under their file name (and under `$id` for `.json` files), `NEWJSONSCHEMA()` and `String.toJSONSchema(name)` under the name, and converted Total.js schemas under the schema name and their `$id`.\n\nExample: Read a schema\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nThe directory with JSON schema files.\n\nReturns: `String` Default `/jsonschemas/`\n\nThe framework reads `.json` and `.txt` files from this directory and its subdirectories when the application starts. Set the option to an empty value to disable loading.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nReturns the path to the JSON schemas directory or to a file in it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name |\n\nReturns: `String` The path\n\nCombines `CONF.directory_jsonschemas` with `filename`.\n\nExample: Read a file\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nA JSON schema in a JSON file.\n\nA standard JSON schema object, read at start. It is registered under the file name without the extension (with the subdirectory, e.g. `users/address`) and under its `$id`. The framework adds the `transform()` method. An invalid file is reported as an error and skipped.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nA JSON schema written in the inline syntax.\n\nThe content is converted with `String.toJSONSchema()` and registered under the file name without the extension. Write one property per line or separate them with commas.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nA string property, optionally with a subtype.\n\nValues that are not strings are converted to strings; empty values become `null`. The `subtype` keyword adds formatting or a check: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` and `capitalize2`. String keywords: `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nA number property; `integer` is accepted as a type name too.\n\nStrings with digits are parsed with `String.parseFloat()`; other values become `null`. The `smallint` subtype allows -32767 to 32767 and `tinyint` 0 to 255. Number keywords: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. The value is not rounded, even for the `int` subtype.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nA boolean property; `bool` is accepted too.\n\nValues that are not booleans are parsed with `String.parseBoolean()`.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nA date property (a Total.js extension of JSON schema).\n\nValues that are not `Date` objects are parsed with `String.parseDate()`. An invalid date becomes `null`; it is an error only when the property is required.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nAn object property, validated by its own `properties`.\n\nOnly the declared `properties` are copied to the response. An object without `properties` is copied as it is. Object keywords: `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nAn array property; each item is validated by `items`.\n\nWithout `items` the array is copied as it is (with duplicates removed when `uniqueItems` is set). Invalid items are left out and their errors are reported. Array keywords: `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nThe list of required properties of an object.\n\nA required property that is missing, empty or invalid is an error named after the property. In the inline syntax, start the name with `*` or `!`. With partial validation, missing properties are skipped.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nThe properties of an object and their schemas.\n\nEach key is a property name and each value its schema. Properties that are not declared are removed from the response.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nA Total.js keyword that adds a format check or a conversion to strings and numbers.\n\nString subtypes: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (Font Awesome or Total.js Icons classes), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Number subtypes with a check: `smallint`, `tinyint`. `String.toJSONSchema()` sets the subtype from the type name.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nThe maximum length of a string.\n\nA longer string is an error. In the inline syntax, write `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nThe minimum length of a non-empty string.\n\nA shorter string is an error. An empty value is checked only by `required`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nThe allowed values of a string.\n\nA value that is not in the list is an error. An empty value is allowed unless the property is required. In the inline syntax, write `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nThe smallest allowed number.\n\nA smaller number is an error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nThe largest allowed number.\n\nA larger number is an error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nThe number must be greater than this value.\n\nA number less than or equal to the value is an error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nThe number must be smaller than this value.\n\nA number greater than or equal to the value is an error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nThe number must be a multiple of this value.\n\nA number with a remainder is an error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nThe schema of the items of an array.\n\nEach item is validated by this schema; invalid items are left out and reported. The schema may be a simple type, an object with `properties`, or a `$ref`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nThe minimum number of valid items in an array.\n\nCounted after invalid items are removed. An empty array of a required property is always an error.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nRemoves duplicate items from an array.\n\nDuplicates are removed silently; they are not an error. Objects are compared by reference, so the option is useful for simple values.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nThe minimum number of valid properties in an object.\n\nCounts the properties that end in the response.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nUses another registered JSON schema for a property.\n\nA property without `type` and with `$ref` is validated by the schema `F.jsonschemas[$ref]`: the name of a file in `jsonschemas/`, a name from `NEWJSONSCHEMA()` or an `$id`. If the schema does not exist, it is an error. In the inline syntax, `@Name` embeds the other schema instead.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nConverts a Total.js schema to a JSON schema object.\n\nReturns: `Object` The JSON schema object\n\nConverts the fields of the schema (and the fields from `schema.jsonschema_define()`) to `properties` and the required fields to `required`. The `$id` is `CONF.url` (or `https://schemas.totaljs.com/`) + the schema name + `.json`. The result is registered in `F.jsonschemas` under the schema name and the `$id`.\n\nExample: Export\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDeclares a field that appears only in the JSON schema made by `schema.toJSONSchema()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Field name or names |\n| `type` | `String|Object` | yes |  | Field type as in `schema.define()`, or `null` to remove |\n| `required` | `Boolean` | no | `false` | Marks the field as required |\n| `invalid` | `String` | no | `'@'` | Error message |\n\nReturns: `Function` A function that sets a default value and returns the schema\n\nThe field uses the same types as `schema.define()`, but it does not take part in the normal validation of the Total.js schema. `type` set to `null` removes the field. `name` may be an array of names. A string as the third argument is the error message and makes the field required.\n\nExample: Extra field\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nMakes and validates a model of a Total.js schema synchronously.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name of the Total.js schema |\n| `model` | `Object` | yes |  | Data |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Skip validation |\n| `arg` | `Object` | no |  | A value passed to the callback |\n| `controller` | `Controller|SchemaOptions` | no |  | Context of the request |\n\nReturns: `Object` The made model\n\nCalls `schema.make()` and returns the made model. Errors go to `callback(err, response, arg)`. With `novalidate`, the model is converted but not validated. For a promise use `MAKE()` (see [Schemas](../schemas/)). Returns `undefined` if the schema does not exist.\n\nExample: Make\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nCreates a new model of a Total.js schema with default values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name of the Total.js schema |\n\nReturns: `Object|null` A new model with default values\n\nReturns the default object of the schema (`schema.default()`), or `null` if the schema does not exist. The defaults come from the fields of the Total.js schema.\n\nExample: Defaults\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm6L4vr60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"JSON-Schemas","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), das Verzeichnis jsonschemas/ und die unterstützten Keywords.","markdown":"---\ntitle: JSON-Schemas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# JSON-Schemas\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), das Verzeichnis jsonschemas/ und die unterstützten Keywords.\n\nJSON-Schemas validieren und konvertieren Daten. Sie werden aus den Dateien `jsonschemas/*.json` und `jsonschemas/*.txt` geladen oder mit `NEWJSONSCHEMA()` und `String.toJSONSchema()` deklariert, und sie werden von `JSONSCHEMA()`, von den Optionen `input`, `output`, `params` und `query` von Aktionen und von Total.js-Schemas genutzt.\n\nLies den Guide [JSON-Schemas](../../guides/json-schemas/) für die Inline-Syntax, die unterstützten Keywords und Beispiele.\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValidiert und konvertiert einen Wert mit einem JSON-Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Name eines registrierten JSON-Schemas oder ein Schema-Objekt |\n| `value` | `Object` | yes |  | Zu validierende Daten |\n| `callback` | `Function` | no |  | `function(err, response)`; ohne ihn wird eine Promise zurückgegeben |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Ein vorhandener Error-Builder, dem die Fehler hinzugefügt werden |\n\nReturns: `Promise|undefined` Eine Promise, wenn kein Callback angegeben ist\n\n`schema` ist der Name eines registrierten Schemas (ein Schlüssel von `F.jsonschemas`) oder ein Schema-Objekt. Der Wert wird in die Typen des Schemas konvertiert, und die Eigenschaften, die das Schema nicht deklariert, werden entfernt.\n\nMit einem Callback ruft es `callback(err, response)` auf, wobei `err` ein `ErrorBuilder` oder `null` ist. Ohne Callback gibt es eine Promise zurück, die mit der Antwort aufgelöst oder mit dem `ErrorBuilder` abgelehnt wird. Existiert das Schema nicht, ist der Fehler `404`.\n\n`JSONSCHEMA()` validiert immer alle Eigenschaften; für eine partielle Validierung nutze die Methode `transform()` des Schema-Objekts.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promise\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nRegistriert oder entfernt ein JSON-Schema.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Name des Schemas oder ein Schema-Objekt mit `$id` |\n| `declaration` | `String` | no |  | Inline-Deklaration wie `'name:String, *email:Email'`; lass sie weg, um das Schema zu entfernen |\n\n- `NEWJSONSCHEMA(object)` registriert ein Schema-Objekt unter seiner `$id`.\n- `NEWJSONSCHEMA(name, declaration)` konvertiert eine Inline-Deklaration mit `String.toJSONSchema(name)` und registriert sie unter `name`.\n- `NEWJSONSCHEMA(name)` ohne Deklaration entfernt das Schema.\n\nEin mit `NEWJSONSCHEMA(object)` registriertes Schema-Objekt wird unverändert gespeichert, ohne die Methode `transform()`. Nutze es mit `JSONSCHEMA()`; für Aktionen ist eine Datei in `jsonschemas/` oder eine Inline-Deklaration vorzuziehen.\n\nExample: Inline-Deklaration\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Entfernen\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nKonvertiert eine Inline-Deklaration in ein JSON-Schema-Objekt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Name, unter dem das Schema registriert wird; er wird auch in `$id` verwendet |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | Basis-URL von `$id` |\n\nReturns: `Object` Das JSON-Schema-Objekt\n\nParst `name:Type`-Paare, getrennt durch Kommas oder Zeilenumbrüche, und gibt ein JSON-Schema-Objekt mit `type: 'object'`, `properties`, `required` und einer Methode `transform()` zurück. Mit `name` wird das Schema zusätzlich in `F.jsonschemas` registriert.\n\nDie `$id` ist `url + name + '.json'`. Die Standard-URL ist `CONF.url` oder `https://schemas.totaljs.com/`; ohne Namen wird ein Hash der Deklaration verwendet. `$schema` ist `https://json-schema.org/draft/2020-12/schema`.\n\n| Syntax | Ergebnis |\n| --- | --- |\n| `*name`, `!name` | Pflichteigenschaft |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Array eines Typs |\n| `name:{a\\|b\\|c}` | String-Enum (`;` funktioniert auch) |\n| `name:{a:String, b:Number}` | Verschachteltes Objekt |\n| `name:[{a:String}]` | Array verschachtelter Objekte |\n| `name:@Other` | Ein anderes Total.js-Schema, JSON-Schema oder der Input einer Aktion |\n\n`@Other` wirft einen Fehler, wenn nichts mit diesem Namen existiert.\n\nExample: Verschachtelte Objekte und Enums\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nValidiert einen Wert mit diesem Schema-Objekt und gibt das Ergebnis synchron zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Zu validierende Daten |\n| `partial` | `Boolean` | no | `false` | Nur die im Wert vorhandenen Eigenschaften validieren |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Ein bestehender Error-Builder, dem die Fehler hinzugefügt werden |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nSchema-Objekte aus `jsonschemas/`-Dateien und aus `String.toJSONSchema()` haben diese Methode. Sie gibt `{ error, response }` zurück: `error` ist ein `ErrorBuilder` mit den Fehlern oder `null`, und `response` ist der umgewandelte Wert.\n\nMit `partial` werden Eigenschaften, die im Wert `undefined` sind, übersprungen, sodass fehlende Pflichteigenschaften keine Fehler sind. Das gilt auf jeder Ebene, auch für die Eigenschaften verschachtelter Objekte.\n\nExample: Teilweises Update\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nAlle registrierten JSON-Schemas, nach Name und nach `$id`.\n\nReturns: `Object` Schema-Objekte nach Schlüssel\n\nEin Objekt mit jedem registrierten Schema. Dateien aus `jsonschemas/` werden unter ihrem Dateinamen gespeichert (und bei `.json`-Dateien unter `$id`), `NEWJSONSCHEMA()` und `String.toJSONSchema(name)` unter dem Namen, und konvertierte Total.js-Schemas unter dem Schemanamen und ihrer `$id`.\n\nExample: Ein Schema lesen\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nDas Verzeichnis mit den JSON-Schema-Dateien.\n\nReturns: `String` Standard `/jsonschemas/`\n\nDas Framework liest beim Start der Anwendung `.json`- und `.txt`-Dateien aus diesem Verzeichnis und seinen Unterverzeichnissen. Setze die Option auf einen leeren Wert, um das Laden zu deaktivieren.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nGibt den Pfad zum Verzeichnis der JSON-Schemas oder zu einer Datei darin zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname |\n\nReturns: `String` Der Pfad\n\nKombiniert `CONF.directory_jsonschemas` mit `filename`.\n\nExample: Eine Datei lesen\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nEin JSON-Schema in einer JSON-Datei.\n\nEin Standard-JSON-Schema-Objekt, das beim Start gelesen wird. Es wird unter dem Dateinamen ohne Endung (mit dem Unterverzeichnis, z. B. `users/address`) und unter seiner `$id` registriert. Das Framework fügt die Methode `transform()` hinzu. Eine ungültige Datei wird als Fehler gemeldet und übersprungen.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nEin JSON-Schema in der Inline-Syntax.\n\nDer Inhalt wird mit `String.toJSONSchema()` konvertiert und unter dem Dateinamen ohne Endung registriert. Schreibe eine Eigenschaft pro Zeile oder trenne sie mit Kommas.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nEine String-Eigenschaft, optional mit einem Subtyp.\n\nWerte, die keine Strings sind, werden in Strings konvertiert; leere Werte werden zu `null`. Das Keyword `subtype` fügt eine Formatierung oder eine Prüfung hinzu: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` und `capitalize2`. String-Keywords: `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nEine Zahleneigenschaft; `integer` wird ebenfalls als Typname akzeptiert.\n\nStrings mit Ziffern werden mit `String.parseFloat()` geparst; andere Werte werden zu `null`. Der Subtyp `smallint` erlaubt -32767 bis 32767 und `tinyint` 0 bis 255. Zahlen-Keywords: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. Der Wert wird nicht gerundet, auch nicht beim Subtyp `int`.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nEine Boolean-Eigenschaft; `bool` wird ebenfalls akzeptiert.\n\nWerte, die keine Booleans sind, werden mit `String.parseBoolean()` geparst.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nEine Datumseigenschaft (eine Total.js-Erweiterung von JSON-Schema).\n\nWerte, die keine `Date`-Objekte sind, werden mit `String.parseDate()` geparst. Ein ungültiges Datum wird zu `null`; ein Fehler ist es nur, wenn die Eigenschaft Pflicht ist.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nEine Objekteigenschaft, validiert durch ihre eigenen `properties`.\n\nNur die deklarierten `properties` werden in die Antwort kopiert. Ein Objekt ohne `properties` wird unverändert kopiert. Objekt-Keywords: `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nEine Array-Eigenschaft; jedes Element wird durch `items` validiert.\n\nOhne `items` wird das Array unverändert kopiert (mit entfernten Duplikaten, wenn `uniqueItems` gesetzt ist). Ungültige Elemente werden weggelassen und ihre Fehler gemeldet. Array-Keywords: `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nDie Liste der Pflichteigenschaften eines Objekts.\n\nEine Pflichteigenschaft, die fehlt, leer oder ungültig ist, ist ein Fehler, der nach der Eigenschaft benannt ist. In der Inline-Syntax beginnst du den Namen mit `*` oder `!`. Bei partieller Validierung werden fehlende Eigenschaften übersprungen.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nDie Eigenschaften eines Objekts und ihre Schemas.\n\nJeder Schlüssel ist ein Eigenschaftsname und jeder Wert sein Schema. Nicht deklarierte Eigenschaften werden aus der Antwort entfernt.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nEin Total.js-Keyword, das Strings und Zahlen eine Formatprüfung oder eine Konvertierung hinzufügt.\n\nString-Subtypen: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (Klassen von Font Awesome oder Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Zahlen-Subtypen mit Prüfung: `smallint`, `tinyint`. `String.toJSONSchema()` setzt den Subtyp anhand des Typnamens.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nDie maximale Länge eines Strings.\n\nEin längerer String ist ein Fehler. In der Inline-Syntax schreibst du `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nDie minimale Länge eines nicht leeren Strings.\n\nEin kürzerer String ist ein Fehler. Ein leerer Wert wird nur durch `required` geprüft.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nDie erlaubten Werte eines Strings.\n\nEin Wert, der nicht in der Liste steht, ist ein Fehler. Ein leerer Wert ist erlaubt, sofern die Eigenschaft keine Pflicht ist. In der Inline-Syntax schreibst du `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nDie kleinste erlaubte Zahl.\n\nEine kleinere Zahl ist ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nDie größte erlaubte Zahl.\n\nEine größere Zahl ist ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nDie Zahl muss größer als dieser Wert sein.\n\nEine Zahl kleiner oder gleich dem Wert ist ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nDie Zahl muss kleiner als dieser Wert sein.\n\nEine Zahl größer oder gleich dem Wert ist ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nDie Zahl muss ein Vielfaches dieses Werts sein.\n\nEine Zahl mit Rest ist ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nDas Schema der Elemente eines Arrays.\n\nJedes Element wird durch dieses Schema validiert; ungültige Elemente werden weggelassen und gemeldet. Das Schema kann ein einfacher Typ, ein Objekt mit `properties` oder eine `$ref` sein.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nDie minimale Anzahl gültiger Elemente in einem Array.\n\nGezählt wird, nachdem ungültige Elemente entfernt wurden. Ein leeres Array bei einer Pflichteigenschaft ist immer ein Fehler.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nEntfernt doppelte Elemente aus einem Array.\n\nDuplikate werden stillschweigend entfernt; sie sind kein Fehler. Objekte werden per Referenz verglichen, daher ist die Option für einfache Werte nützlich.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nDie minimale Anzahl gültiger Eigenschaften in einem Objekt.\n\nZählt die Eigenschaften, die in der Antwort landen.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nVerwendet ein anderes registriertes JSON-Schema für eine Eigenschaft.\n\nEine Eigenschaft ohne `type` und mit `$ref` wird durch das Schema `F.jsonschemas[$ref]` validiert: den Namen einer Datei in `jsonschemas/`, einen Namen aus `NEWJSONSCHEMA()` oder eine `$id`. Existiert das Schema nicht, ist das ein Fehler. In der Inline-Syntax bettet `@Name` stattdessen das andere Schema ein.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nKonvertiert ein Total.js-Schema in ein JSON-Schema-Objekt.\n\nReturns: `Object` Das JSON-Schema-Objekt\n\nKonvertiert die Felder des Schemas (und die Felder aus `schema.jsonschema_define()`) in `properties` und die Pflichtfelder in `required`. Die `$id` ist `CONF.url` (oder `https://schemas.totaljs.com/`) + der Schemaname + `.json`. Das Ergebnis wird in `F.jsonschemas` unter dem Schemanamen und der `$id` registriert.\n\nExample: Export\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDeklariert ein Feld, das nur in dem von `schema.toJSONSchema()` erzeugten JSON-Schema erscheint.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Feldname oder Feldnamen |\n| `type` | `String|Object` | yes |  | Feldtyp wie in `schema.define()` oder `null` zum Entfernen |\n| `required` | `Boolean` | no | `false` | Markiert das Feld als Pflicht |\n| `invalid` | `String` | no | `'@'` | Fehlermeldung |\n\nReturns: `Function` Eine Funktion, die einen Standardwert setzt und das Schema zurückgibt\n\nDas Feld verwendet dieselben Typen wie `schema.define()`, nimmt aber nicht an der normalen Validierung des Total.js-Schemas teil. `type` auf `null` gesetzt entfernt das Feld. `name` kann ein Array von Namen sein. Ein String als drittes Argument ist die Fehlermeldung und macht das Feld zur Pflicht.\n\nExample: Zusätzliches Feld\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nErstellt und validiert synchron ein Modell eines Total.js-Schemas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name des Total.js-Schemas |\n| `model` | `Object` | yes |  | Daten |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Validierung überspringen |\n| `arg` | `Object` | no |  | Ein Wert, der an den Callback übergeben wird |\n| `controller` | `Controller|SchemaOptions` | no |  | Kontext des Requests |\n\nReturns: `Object` Das erstellte Modell\n\nRuft `schema.make()` auf und gibt das erstellte Modell zurück. Fehler gehen an `callback(err, response, arg)`. Mit `novalidate` wird das Modell konvertiert, aber nicht validiert. Für eine Promise nutze `MAKE()` (siehe [Schemas](../schemas/)). Gibt `undefined` zurück, wenn das Schema nicht existiert.\n\nExample: Erstellen\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nErstellt ein neues Modell eines Total.js-Schemas mit Standardwerten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Name des Total.js-Schemas |\n\nReturns: `Object|null` Ein neues Modell mit Standardwerten\n\nGibt das Standardobjekt des Schemas zurück (`schema.default()`) oder `null`, wenn das Schema nicht existiert. Die Standardwerte stammen aus den Feldern des Total.js-Schemas.\n\nExample: Standardwerte\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm6L4vr60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Esquemas JSON","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), el directorio jsonschemas/ y las palabras clave admitidas.","markdown":"---\ntitle: Esquemas JSON\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Esquemas JSON\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), el directorio jsonschemas/ y las palabras clave admitidas.\n\nLos esquemas JSON validan y convierten datos. Se cargan desde archivos `jsonschemas/*.json` y `jsonschemas/*.txt` o se declaran con `NEWJSONSCHEMA()` y `String.toJSONSchema()`, y los usan `JSONSCHEMA()`, las opciones `input`, `output`, `params` y `query` de las acciones y los esquemas de Total.js.\n\nLee la guía [Esquemas JSON](../../guides/json-schemas/) para conocer la sintaxis inline, las palabras clave admitidas y ejemplos.\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValida y convierte un valor con un esquema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Nombre de un esquema JSON registrado, o un objeto de esquema |\n| `value` | `Object` | yes |  | Datos a validar |\n| `callback` | `Function` | no |  | `function(err, response)`; sin él se devuelve una promesa |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder existente al que añadir los errores |\n\nReturns: `Promise|undefined` Una promesa cuando no se pasa callback\n\n`schema` es el nombre de un esquema registrado (una clave de `F.jsonschemas`) o un objeto de esquema. El valor se convierte a los tipos del esquema y se eliminan las propiedades que el esquema no declara.\n\nCon callback, llama a `callback(err, response)`, donde `err` es un `ErrorBuilder` o `null`. Sin callback, devuelve una promesa que se resuelve con la respuesta o se rechaza con el `ErrorBuilder`. Si el esquema no existe, el error es `404`.\n\n`JSONSCHEMA()` siempre valida todas las propiedades; para una validación parcial usa el método `transform()` del objeto de esquema.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promesa\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nRegistra o elimina un esquema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Nombre del esquema, o un objeto de esquema con `$id` |\n| `declaration` | `String` | no |  | Declaración inline como `'name:String, *email:Email'`; omítela para eliminar el esquema |\n\n- `NEWJSONSCHEMA(object)` registra un objeto de esquema con su `$id`.\n- `NEWJSONSCHEMA(name, declaration)` convierte una declaración inline con `String.toJSONSchema(name)` y la registra con `name`.\n- `NEWJSONSCHEMA(name)` sin declaración elimina el esquema.\n\nUn objeto de esquema registrado con `NEWJSONSCHEMA(object)` se guarda tal cual, sin el método `transform()`. Úsalo con `JSONSCHEMA()`; para acciones, mejor un archivo en `jsonschemas/` o una declaración inline.\n\nExample: Declaración inline\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Eliminar\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nConvierte una declaración inline en un objeto de esquema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Nombre con el que registrar el esquema; también se usa en `$id` |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | URL base de `$id` |\n\nReturns: `Object` El objeto de esquema JSON\n\nParsea pares `name:Type` separados por comas o saltos de línea y devuelve un objeto de esquema JSON con `type: 'object'`, `properties`, `required` y un método `transform()`. Con `name`, el esquema también se registra en `F.jsonschemas`.\n\nEl `$id` es `url + name + '.json'`. La URL por defecto es `CONF.url`, o `https://schemas.totaljs.com/`; sin nombre se usa un hash de la declaración. `$schema` es `https://json-schema.org/draft/2020-12/schema`.\n\n| Sintaxis | Resultado |\n| --- | --- |\n| `*name`, `!name` | Propiedad obligatoria |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Array de un tipo |\n| `name:{a\\|b\\|c}` | Enum de strings (`;` también funciona) |\n| `name:{a:String, b:Number}` | Objeto anidado |\n| `name:[{a:String}]` | Array de objetos anidados |\n| `name:@Other` | Otro esquema de Total.js, esquema JSON o input de acción |\n\n`@Other` lanza un error si no existe nada con ese nombre.\n\nExample: Objetos anidados y enums\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nValida un valor con este objeto de esquema y devuelve el resultado de forma síncrona.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Datos que se validan |\n| `partial` | `Boolean` | no | `false` | Valida solo las propiedades presentes en el valor |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder existente al que se añaden los errores |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nLos objetos de esquema de los archivos de `jsonschemas/` y de `String.toJSONSchema()` tienen este método. Devuelve `{ error, response }`: `error` es un `ErrorBuilder` con los errores o `null`, y `response` es el valor convertido.\n\nCon `partial`, las propiedades que son `undefined` en el valor se omiten, así que las propiedades obligatorias que faltan no son errores. Esto se aplica en todos los niveles, también a las propiedades de los objetos anidados.\n\nExample: Actualización parcial\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTodos los esquemas JSON registrados, por nombre y por `$id`.\n\nReturns: `Object` Objetos de esquema por clave\n\nUn objeto con cada esquema registrado. Los archivos de `jsonschemas/` se guardan con su nombre de archivo (y con `$id` para los archivos `.json`), `NEWJSONSCHEMA()` y `String.toJSONSchema(name)` con el nombre, y los esquemas de Total.js convertidos con el nombre del esquema y su `$id`.\n\nExample: Leer un esquema\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nEl directorio con los archivos de esquemas JSON.\n\nReturns: `String` Por defecto `/jsonschemas/`\n\nEl framework lee los archivos `.json` y `.txt` de este directorio y de sus subdirectorios cuando arranca la aplicación. Asigna a la opción un valor vacío para desactivar la carga.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nDevuelve la ruta al directorio de esquemas JSON o a un archivo dentro de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo |\n\nReturns: `String` La ruta\n\nCombina `CONF.directory_jsonschemas` con `filename`.\n\nExample: Leer un archivo\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nUn esquema JSON en un archivo JSON.\n\nUn objeto de esquema JSON estándar, leído al arrancar. Se registra con el nombre del archivo sin la extensión (con el subdirectorio, p. ej. `users/address`) y con su `$id`. El framework añade el método `transform()`. Un archivo no válido se notifica como error y se omite.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nUn esquema JSON escrito con la sintaxis inline.\n\nEl contenido se convierte con `String.toJSONSchema()` y se registra con el nombre del archivo sin la extensión. Escribe una propiedad por línea o sepáralas con comas.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nUna propiedad de tipo string, opcionalmente con un subtipo.\n\nLos valores que no son strings se convierten a string; los valores vacíos se convierten en `null`. La palabra clave `subtype` añade formato o una comprobación: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` y `capitalize2`. Palabras clave de string: `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nUna propiedad numérica; `integer` también se acepta como nombre de tipo.\n\nLos strings con dígitos se parsean con `String.parseFloat()`; los otros valores se convierten en `null`. El subtipo `smallint` permite de -32767 a 32767 y `tinyint` de 0 a 255. Palabras clave numéricas: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. El valor no se redondea, ni siquiera con el subtipo `int`.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nUna propiedad booleana; `bool` también se acepta.\n\nLos valores que no son booleanos se parsean con `String.parseBoolean()`.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nUna propiedad de fecha (una extensión de Total.js al esquema JSON).\n\nLos valores que no son objetos `Date` se parsean con `String.parseDate()`. Una fecha no válida se convierte en `null`; solo es un error cuando la propiedad es obligatoria.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nUna propiedad de tipo objeto, validada por sus propias `properties`.\n\nSolo se copian a la respuesta las `properties` declaradas. Un objeto sin `properties` se copia tal cual. Palabras clave de objeto: `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nUna propiedad de tipo array; cada elemento se valida con `items`.\n\nSin `items`, el array se copia tal cual (sin duplicados cuando se indica `uniqueItems`). Los elementos no válidos se descartan y se notifican sus errores. Palabras clave de array: `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nLa lista de propiedades obligatorias de un objeto.\n\nUna propiedad obligatoria que falta, está vacía o no es válida es un error con el nombre de la propiedad. En la sintaxis inline, empieza el nombre con `*` o `!`. Con la validación parcial, las propiedades que faltan se omiten.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nLas propiedades de un objeto y sus esquemas.\n\nCada clave es un nombre de propiedad y cada valor su esquema. Las propiedades no declaradas se eliminan de la respuesta.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nUna palabra clave de Total.js que añade una comprobación de formato o una conversión a strings y números.\n\nSubtipos de string: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (clases de Font Awesome o de Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Subtipos numéricos con comprobación: `smallint`, `tinyint`. `String.toJSONSchema()` asigna el subtipo a partir del nombre del tipo.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nLa longitud máxima de un string.\n\nUn string más largo es un error. En la sintaxis inline, escribe `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nLa longitud mínima de un string no vacío.\n\nUn string más corto es un error. Un valor vacío solo lo comprueba `required`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nLos valores permitidos de un string.\n\nUn valor que no está en la lista es un error. Un valor vacío está permitido salvo que la propiedad sea obligatoria. En la sintaxis inline, escribe `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nEl número más pequeño permitido.\n\nUn número menor es un error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nEl número más grande permitido.\n\nUn número mayor es un error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nEl número debe ser mayor que este valor.\n\nUn número menor o igual que el valor es un error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nEl número debe ser menor que este valor.\n\nUn número mayor o igual que el valor es un error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nEl número debe ser múltiplo de este valor.\n\nUn número con resto es un error.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nEl esquema de los elementos de un array.\n\nCada elemento se valida con este esquema; los elementos no válidos se descartan y se notifican. El esquema puede ser un tipo simple, un objeto con `properties` o un `$ref`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nEl número mínimo de elementos válidos de un array.\n\nSe cuenta después de eliminar los elementos no válidos. Un array vacío de una propiedad obligatoria siempre es un error.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nElimina los elementos duplicados de un array.\n\nLos duplicados se eliminan sin avisar; no son un error. Los objetos se comparan por referencia, así que la opción es útil para valores simples.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nEl número mínimo de propiedades válidas de un objeto.\n\nCuenta las propiedades que acaban en la respuesta.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nUsa otro esquema JSON registrado para una propiedad.\n\nUna propiedad sin `type` y con `$ref` se valida con el esquema `F.jsonschemas[$ref]`: el nombre de un archivo de `jsonschemas/`, un nombre de `NEWJSONSCHEMA()` o un `$id`. Si el esquema no existe, es un error. En la sintaxis inline, `@Name` incrusta el otro esquema en su lugar.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nConvierte un esquema de Total.js en un objeto de esquema JSON.\n\nReturns: `Object` El objeto de esquema JSON\n\nConvierte los campos del esquema (y los campos de `schema.jsonschema_define()`) en `properties` y los campos obligatorios en `required`. El `$id` es `CONF.url` (o `https://schemas.totaljs.com/`) + el nombre del esquema + `.json`. El resultado se registra en `F.jsonschemas` con el nombre del esquema y con el `$id`.\n\nExample: Exportar\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDeclara un campo que solo aparece en el esquema JSON generado por `schema.toJSONSchema()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nombre o nombres del campo |\n| `type` | `String|Object` | yes |  | Tipo del campo como en `schema.define()`, o `null` para eliminarlo |\n| `required` | `Boolean` | no | `false` | Marca el campo como obligatorio |\n| `invalid` | `String` | no | `'@'` | Mensaje de error |\n\nReturns: `Function` Una función que asigna un valor por defecto y devuelve el esquema\n\nEl campo usa los mismos tipos que `schema.define()`, pero no participa en la validación normal del esquema de Total.js. `type` en `null` elimina el campo. `name` puede ser un array de nombres. Un string como tercer argumento es el mensaje de error y hace que el campo sea obligatorio.\n\nExample: Campo extra\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nCrea y valida un modelo de un esquema de Total.js de forma síncrona.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nombre del esquema de Total.js |\n| `model` | `Object` | yes |  | Datos |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Omite la validación |\n| `arg` | `Object` | no |  | Un valor que se pasa al callback |\n| `controller` | `Controller|SchemaOptions` | no |  | Contexto de la petición |\n\nReturns: `Object` El modelo creado\n\nLlama a `schema.make()` y devuelve el modelo creado. Los errores van a `callback(err, response, arg)`. Con `novalidate`, el modelo se convierte pero no se valida. Para una promesa usa `MAKE()` (consulta [Esquemas](../schemas/)). Devuelve `undefined` si el esquema no existe.\n\nExample: Crear\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nCrea un nuevo modelo de un esquema de Total.js con valores por defecto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nombre del esquema de Total.js |\n\nReturns: `Object|null` Un nuevo modelo con valores por defecto\n\nDevuelve el objeto por defecto del esquema (`schema.default()`), o `null` si el esquema no existe. Los valores por defecto vienen de los campos del esquema de Total.js.\n\nExample: Valores por defecto\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm6L4vr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Schémas JSON","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), le répertoire jsonschemas/ et les mots-clés pris en charge.","markdown":"---\ntitle: \"Schémas JSON\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Schémas JSON\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), le répertoire jsonschemas/ et les mots-clés pris en charge.\n\nLes schémas JSON valident et convertissent des données. Ils sont chargés depuis les fichiers `jsonschemas/*.json` et `jsonschemas/*.txt` ou déclarés avec `NEWJSONSCHEMA()` et `String.toJSONSchema()`, et ils sont utilisés par `JSONSCHEMA()`, par les options `input`, `output`, `params` et `query` des actions et par les schémas Total.js.\n\nLis le guide [Schémas JSON](../../guides/json-schemas/) pour la syntaxe inline, les mots-clés pris en charge et des exemples.\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValide et convertit une valeur avec un schéma JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Nom d'un schéma JSON enregistré, ou un objet de schéma |\n| `value` | `Object` | yes |  | Données à valider |\n| `callback` | `Function` | no |  | `function(err, response)` ; sans lui, une promesse est renvoyée |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder existant auquel ajouter les erreurs |\n\nReturns: `Promise|undefined` Une promesse lorsqu'aucun callback n'est fourni\n\n`schema` est le nom d'un schéma enregistré (une clé de `F.jsonschemas`) ou un objet de schéma. La valeur est convertie dans les types du schéma et les propriétés que le schéma ne déclare pas sont supprimées.\n\nAvec un callback, elle appelle `callback(err, response)`, où `err` est un `ErrorBuilder` ou `null`. Sans callback, elle renvoie une promesse qui est résolue avec la réponse ou rejetée avec l'`ErrorBuilder`. Si le schéma n'existe pas, l'erreur est `404`.\n\n`JSONSCHEMA()` valide toujours toutes les propriétés ; pour une validation partielle, utilise la méthode `transform()` de l'objet de schéma.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promesse\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nEnregistre ou supprime un schéma JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Nom du schéma, ou un objet de schéma avec `$id` |\n| `declaration` | `String` | no |  | Déclaration inline telle que `'name:String, *email:Email'` ; omets-la pour supprimer le schéma |\n\n- `NEWJSONSCHEMA(object)` enregistre un objet de schéma sous son `$id`.\n- `NEWJSONSCHEMA(name, declaration)` convertit une déclaration inline avec `String.toJSONSchema(name)` et l'enregistre sous `name`.\n- `NEWJSONSCHEMA(name)` sans déclaration supprime le schéma.\n\nUn objet de schéma enregistré avec `NEWJSONSCHEMA(object)` est stocké tel quel, sans la méthode `transform()`. Utilise-le avec `JSONSCHEMA()` ; pour les actions, préfère un fichier dans `jsonschemas/` ou une déclaration inline.\n\nExample: Déclaration inline\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Supprimer\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nConvertit une déclaration inline en objet de schéma JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Nom sous lequel enregistrer le schéma ; il est aussi utilisé dans `$id` |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | URL de base de `$id` |\n\nReturns: `Object` L'objet de schéma JSON\n\nAnalyse des paires `name:Type` séparées par des virgules ou des retours à la ligne et renvoie un objet de schéma JSON avec `type: 'object'`, `properties`, `required` et une méthode `transform()`. Avec `name`, le schéma est aussi enregistré dans `F.jsonschemas`.\n\nLe `$id` vaut `url + name + '.json'`. L'URL par défaut est `CONF.url`, ou `https://schemas.totaljs.com/` ; sans nom, un hash de la déclaration est utilisé. `$schema` vaut `https://json-schema.org/draft/2020-12/schema`.\n\n| Syntaxe | Résultat |\n| --- | --- |\n| `*name`, `!name` | Propriété obligatoire |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Tableau d'un type |\n| `name:{a\\|b\\|c}` | Énumération de chaînes (`;` fonctionne aussi) |\n| `name:{a:String, b:Number}` | Objet imbriqué |\n| `name:[{a:String}]` | Tableau d'objets imbriqués |\n| `name:@Other` | Un autre schéma Total.js, schéma JSON ou input d'action |\n\n`@Other` lève une erreur si rien n'existe sous ce nom.\n\nExample: Objets imbriqués et énumérations\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nValide une valeur avec cet objet de schéma et renvoie le résultat de manière synchrone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Données à valider |\n| `partial` | `Boolean` | no | `false` | Valider uniquement les propriétés présentes dans la valeur |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder existant auquel ajouter les erreurs |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nLes objets de schéma issus des fichiers `jsonschemas/` et de `String.toJSONSchema()` possèdent cette méthode. Elle renvoie `{ error, response }` : `error` est un `ErrorBuilder` contenant les erreurs, ou `null`, et `response` est la valeur convertie.\n\nAvec `partial`, les propriétés `undefined` dans la valeur sont ignorées ; les propriétés obligatoires manquantes ne sont donc pas des erreurs. Cela s'applique à tous les niveaux, y compris aux propriétés des objets imbriqués.\n\nExample: Mise à jour partielle\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTous les schémas JSON enregistrés, par nom et par `$id`.\n\nReturns: `Object` Objets de schéma par clé\n\nUn objet contenant chaque schéma enregistré. Les fichiers de `jsonschemas/` sont stockés sous leur nom de fichier (et sous `$id` pour les fichiers `.json`), `NEWJSONSCHEMA()` et `String.toJSONSchema(name)` sous le nom, et les schémas Total.js convertis sous le nom du schéma et leur `$id`.\n\nExample: Lire un schéma\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nLe répertoire contenant les fichiers de schémas JSON.\n\nReturns: `String` Par défaut `/jsonschemas/`\n\nLe framework lit les fichiers `.json` et `.txt` de ce répertoire et de ses sous-répertoires au démarrage de l'application. Définis l'option à une valeur vide pour désactiver le chargement.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nRenvoie le chemin du répertoire des schémas JSON ou d'un fichier qu'il contient.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier |\n\nReturns: `String` Le chemin\n\nCombine `CONF.directory_jsonschemas` avec `filename`.\n\nExample: Lire un fichier\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nUn schéma JSON dans un fichier JSON.\n\nUn objet de schéma JSON standard, lu au démarrage. Il est enregistré sous le nom du fichier sans l'extension (avec le sous-répertoire, par ex. `users/address`) et sous son `$id`. Le framework ajoute la méthode `transform()`. Un fichier invalide est signalé comme une erreur et ignoré.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nUn schéma JSON écrit avec la syntaxe inline.\n\nLe contenu est converti avec `String.toJSONSchema()` et enregistré sous le nom du fichier sans l'extension. Écris une propriété par ligne ou sépare-les par des virgules.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nUne propriété chaîne, éventuellement avec un sous-type.\n\nLes valeurs qui ne sont pas des chaînes sont converties en chaînes ; les valeurs vides deviennent `null`. Le mot-clé `subtype` ajoute un formatage ou une vérification : `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` et `capitalize2`. Mots-clés des chaînes : `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nUne propriété numérique ; `integer` est aussi accepté comme nom de type.\n\nLes chaînes contenant des chiffres sont analysées avec `String.parseFloat()` ; les autres valeurs deviennent `null`. Le sous-type `smallint` autorise de -32767 à 32767 et `tinyint` de 0 à 255. Mots-clés des nombres : `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. La valeur n'est pas arrondie, même pour le sous-type `int`.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nUne propriété booléenne ; `bool` est aussi accepté.\n\nLes valeurs qui ne sont pas des booléens sont analysées avec `String.parseBoolean()`.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nUne propriété date (une extension Total.js du schéma JSON).\n\nLes valeurs qui ne sont pas des objets `Date` sont analysées avec `String.parseDate()`. Une date invalide devient `null` ; ce n'est une erreur que si la propriété est obligatoire.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nUne propriété objet, validée par ses propres `properties`.\n\nSeules les `properties` déclarées sont copiées dans la réponse. Un objet sans `properties` est copié tel quel. Mots-clés des objets : `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nUne propriété tableau ; chaque élément est validé par `items`.\n\nSans `items`, le tableau est copié tel quel (avec suppression des doublons lorsque `uniqueItems` est défini). Les éléments invalides sont écartés et leurs erreurs sont signalées. Mots-clés des tableaux : `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nLa liste des propriétés obligatoires d'un objet.\n\nUne propriété obligatoire manquante, vide ou invalide est une erreur portant le nom de la propriété. Dans la syntaxe inline, faites commencer le nom par `*` ou `!`. En validation partielle, les propriétés manquantes sont ignorées.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nLes propriétés d'un objet et leurs schémas.\n\nChaque clé est un nom de propriété et chaque valeur son schéma. Les propriétés non déclarées sont supprimées de la réponse.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nUn mot-clé Total.js qui ajoute une vérification de format ou une conversion aux chaînes et aux nombres.\n\nSous-types de chaînes : `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (classes Font Awesome ou Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Sous-types numériques avec vérification : `smallint`, `tinyint`. `String.toJSONSchema()` définit le sous-type à partir du nom de type.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nLa longueur maximale d'une chaîne.\n\nUne chaîne plus longue est une erreur. Dans la syntaxe inline, écris `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nLa longueur minimale d'une chaîne non vide.\n\nUne chaîne plus courte est une erreur. Une valeur vide n'est vérifiée que par `required`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nLes valeurs autorisées d'une chaîne.\n\nUne valeur absente de la liste est une erreur. Une valeur vide est autorisée sauf si la propriété est obligatoire. Dans la syntaxe inline, écris `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nLe plus petit nombre autorisé.\n\nUn nombre plus petit est une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nLe plus grand nombre autorisé.\n\nUn nombre plus grand est une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nLe nombre doit être strictement supérieur à cette valeur.\n\nUn nombre inférieur ou égal à la valeur est une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nLe nombre doit être strictement inférieur à cette valeur.\n\nUn nombre supérieur ou égal à la valeur est une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nLe nombre doit être un multiple de cette valeur.\n\nUn nombre avec un reste est une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nLe schéma des éléments d'un tableau.\n\nChaque élément est validé par ce schéma ; les éléments invalides sont écartés et signalés. Le schéma peut être un type simple, un objet avec `properties` ou un `$ref`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nLe nombre minimal d'éléments valides dans un tableau.\n\nCompté après la suppression des éléments invalides. Un tableau vide pour une propriété obligatoire est toujours une erreur.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nSupprime les éléments en double d'un tableau.\n\nLes doublons sont supprimés silencieusement ; ce ne sont pas des erreurs. Les objets sont comparés par référence ; l'option est donc utile pour les valeurs simples.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nLe nombre minimal de propriétés valides dans un objet.\n\nCompte les propriétés qui se retrouvent dans la réponse.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nUtilise un autre schéma JSON enregistré pour une propriété.\n\nUne propriété sans `type` et avec `$ref` est validée par le schéma `F.jsonschemas[$ref]` : le nom d'un fichier dans `jsonschemas/`, un nom provenant de `NEWJSONSCHEMA()` ou un `$id`. Si le schéma n'existe pas, c'est une erreur. Dans la syntaxe inline, `@Name` intègre l'autre schéma à la place.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nConvertit un schéma Total.js en objet de schéma JSON.\n\nReturns: `Object` L'objet de schéma JSON\n\nConvertit les champs du schéma (et les champs de `schema.jsonschema_define()`) en `properties` et les champs obligatoires en `required`. Le `$id` vaut `CONF.url` (ou `https://schemas.totaljs.com/`) + le nom du schéma + `.json`. Le résultat est enregistré dans `F.jsonschemas` sous le nom du schéma et sous le `$id`.\n\nExample: Exporter\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDéclare un champ qui n'apparaît que dans le schéma JSON produit par `schema.toJSONSchema()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nom ou noms du champ |\n| `type` | `String|Object` | yes |  | Type du champ comme dans `schema.define()`, ou `null` pour le supprimer |\n| `required` | `Boolean` | no | `false` | Marque le champ comme obligatoire |\n| `invalid` | `String` | no | `'@'` | Message d'erreur |\n\nReturns: `Function` Une fonction qui définit une valeur par défaut et renvoie le schéma\n\nLe champ utilise les mêmes types que `schema.define()`, mais il ne participe pas à la validation normale du schéma Total.js. `type` défini à `null` supprime le champ. `name` peut être un tableau de noms. Une chaîne comme troisième argument est le message d'erreur et rend le champ obligatoire.\n\nExample: Champ supplémentaire\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nConstruit et valide un modèle d'un schéma Total.js de manière synchrone.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nom du schéma Total.js |\n| `model` | `Object` | yes |  | Données |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Ignorer la validation |\n| `arg` | `Object` | no |  | Une valeur transmise au callback |\n| `controller` | `Controller|SchemaOptions` | no |  | Contexte de la requête |\n\nReturns: `Object` Le modèle construit\n\nAppelle `schema.make()` et renvoie le modèle construit. Les erreurs sont transmises à `callback(err, response, arg)`. Avec `novalidate`, le modèle est converti mais pas validé. Pour une promesse, utilise `MAKE()` (voir [Schémas](../schemas/)). Renvoie `undefined` si le schéma n'existe pas.\n\nExample: Construire\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nCrée un nouveau modèle d'un schéma Total.js avec les valeurs par défaut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nom du schéma Total.js |\n\nReturns: `Object|null` Un nouveau modèle avec les valeurs par défaut\n\nRenvoie l'objet par défaut du schéma (`schema.default()`), ou `null` si le schéma n'existe pas. Les valeurs par défaut proviennent des champs du schéma Total.js.\n\nExample: Valeurs par défaut\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm6L4vr60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Schemi JSON","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), la directory jsonschemas/ e le parole chiave supportate.","markdown":"---\ntitle: Schemi JSON\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Schemi JSON\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), la directory jsonschemas/ e le parole chiave supportate.\n\nGli schemi JSON validano e convertono i dati. Vengono caricati dai file `jsonschemas/*.json` e `jsonschemas/*.txt` oppure dichiarati con `NEWJSONSCHEMA()` e `String.toJSONSchema()`, e vengono usati da `JSONSCHEMA()`, dalle opzioni `input`, `output`, `params` e `query` delle azioni e dagli schemi Total.js.\n\nLeggi la guida [Schemi JSON](../../guides/json-schemas/) per la sintassi inline, le parole chiave supportate e gli esempi.\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValida e converte un valore con uno schema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Nome di uno schema JSON registrato, o un oggetto schema |\n| `value` | `Object` | yes |  | Dati da validare |\n| `callback` | `Function` | no |  | `function(err, response)`; senza di essa viene restituita una promise |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder esistente a cui aggiungere gli errori |\n\nReturns: `Promise|undefined` Una promise quando non viene passata una callback\n\n`schema` è il nome di uno schema registrato (una chiave di `F.jsonschemas`) o un oggetto schema. Il valore viene convertito nei tipi dello schema e le proprietà che lo schema non dichiara vengono rimosse.\n\nCon una callback chiama `callback(err, response)`, dove `err` è un `ErrorBuilder` o `null`. Senza callback restituisce una promise che si risolve con la risposta o viene rifiutata con l'`ErrorBuilder`. Se lo schema non esiste, l'errore è `404`.\n\n`JSONSCHEMA()` valida sempre tutte le proprietà; per la validazione parziale usa il metodo `transform()` dell'oggetto schema.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promise\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nRegistra o rimuove uno schema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Nome dello schema, o un oggetto schema con `$id` |\n| `declaration` | `String` | no |  | Dichiarazione inline come `'name:String, *email:Email'`; omettila per rimuovere lo schema |\n\n- `NEWJSONSCHEMA(object)` registra un oggetto schema con il suo `$id`.\n- `NEWJSONSCHEMA(name, declaration)` converte una dichiarazione inline con `String.toJSONSchema(name)` e la registra come `name`.\n- `NEWJSONSCHEMA(name)` senza dichiarazione rimuove lo schema.\n\nUn oggetto schema registrato con `NEWJSONSCHEMA(object)` viene salvato così com'è, senza il metodo `transform()`. Usalo con `JSONSCHEMA()`; per le azioni preferisci un file in `jsonschemas/` o una dichiarazione inline.\n\nExample: Dichiarazione inline\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Rimozione\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nConverte una dichiarazione inline in un oggetto schema JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Nome con cui registrare lo schema; viene usato anche in `$id` |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | URL di base di `$id` |\n\nReturns: `Object` L'oggetto schema JSON\n\nInterpreta coppie `name:Type` separate da virgole o da a capo e restituisce un oggetto schema JSON con `type: 'object'`, `properties`, `required` e un metodo `transform()`. Con `name`, lo schema viene anche registrato in `F.jsonschemas`.\n\nL'`$id` è `url + name + '.json'`. L'URL predefinito è `CONF.url`, oppure `https://schemas.totaljs.com/`; senza nome viene usato un hash della dichiarazione. `$schema` è `https://json-schema.org/draft/2020-12/schema`.\n\n| Sintassi | Risultato |\n| --- | --- |\n| `*name`, `!name` | Proprietà obbligatoria |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Array di un tipo |\n| `name:{a\\|b\\|c}` | Enum di stringhe (funziona anche `;`) |\n| `name:{a:String, b:Number}` | Oggetto annidato |\n| `name:[{a:String}]` | Array di oggetti annidati |\n| `name:@Other` | Un altro schema Total.js, schema JSON o input di un'azione |\n\n`@Other` lancia un errore se non esiste nulla con quel nome.\n\nExample: Oggetti annidati ed enum\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nValida un valore con questo oggetto schema e restituisce il risultato in modo sincrono.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Dati da validare |\n| `partial` | `Boolean` | no | `false` | Valida solo le proprietà presenti nel valore |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Un error builder esistente a cui aggiungere gli errori |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nGli oggetti schema dei file `jsonschemas/` e di `String.toJSONSchema()` hanno questo metodo. Restituisce `{ error, response }`: `error` è un `ErrorBuilder` con gli errori oppure `null`, e `response` è il valore convertito.\n\nCon `partial`, le proprietà che sono `undefined` nel valore vengono saltate, quindi le proprietà obbligatorie mancanti non sono errori. Questo vale a ogni livello, anche per le proprietà degli oggetti annidati.\n\nExample: Aggiornamento parziale\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nTutti gli schemi JSON registrati, per nome e per `$id`.\n\nReturns: `Object` Oggetti schema per chiave\n\nUn oggetto con ogni schema registrato. I file di `jsonschemas/` vengono salvati con il nome del file (e con `$id` per i file `.json`), `NEWJSONSCHEMA()` e `String.toJSONSchema(name)` con il nome, e gli schemi Total.js convertiti con il nome dello schema e il loro `$id`.\n\nExample: Leggere uno schema\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nLa directory con i file degli schemi JSON.\n\nReturns: `String` Predefinito `/jsonschemas/`\n\nIl framework legge i file `.json` e `.txt` da questa directory e dalle sue sottodirectory all'avvio dell'applicazione. Imposta l'opzione a un valore vuoto per disattivare il caricamento.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nRestituisce il percorso della directory degli schemi JSON o di un file al suo interno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file |\n\nReturns: `String` Il percorso\n\nCombina `CONF.directory_jsonschemas` con `filename`.\n\nExample: Leggere un file\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nUno schema JSON in un file JSON.\n\nUn oggetto schema JSON standard, letto all'avvio. Viene registrato con il nome del file senza estensione (con la sottodirectory, ad es. `users/address`) e con il suo `$id`. Il framework aggiunge il metodo `transform()`. Un file non valido viene segnalato come errore e ignorato.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nUno schema JSON scritto con la sintassi inline.\n\nIl contenuto viene convertito con `String.toJSONSchema()` e registrato con il nome del file senza estensione. Scrivi una proprietà per riga oppure separale con virgole.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nUna proprietà stringa, eventualmente con un sottotipo.\n\nI valori che non sono stringhe vengono convertiti in stringhe; i valori vuoti diventano `null`. La parola chiave `subtype` aggiunge una formattazione o un controllo: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` e `capitalize2`. Parole chiave per le stringhe: `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nUna proprietà numerica; anche `integer` è accettato come nome di tipo.\n\nLe stringhe con cifre vengono interpretate con `String.parseFloat()`; gli altri valori diventano `null`. Il sottotipo `smallint` ammette da -32767 a 32767 e `tinyint` da 0 a 255. Parole chiave per i numeri: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. Il valore non viene arrotondato, nemmeno con il sottotipo `int`.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nUna proprietà booleana; è accettato anche `bool`.\n\nI valori che non sono booleani vengono interpretati con `String.parseBoolean()`.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nUna proprietà data (un'estensione Total.js dello schema JSON).\n\nI valori che non sono oggetti `Date` vengono interpretati con `String.parseDate()`. Una data non valida diventa `null`; è un errore solo quando la proprietà è obbligatoria.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nUna proprietà oggetto, validata dalle sue `properties`.\n\nNella risposta vengono copiate solo le `properties` dichiarate. Un oggetto senza `properties` viene copiato così com'è. Parole chiave per gli oggetti: `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nUna proprietà array; ogni elemento viene validato da `items`.\n\nSenza `items` l'array viene copiato così com'è (con i duplicati rimossi quando è impostato `uniqueItems`). Gli elementi non validi vengono esclusi e i loro errori vengono segnalati. Parole chiave per gli array: `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nL'elenco delle proprietà obbligatorie di un oggetto.\n\nUna proprietà obbligatoria mancante, vuota o non valida è un errore con il nome della proprietà. Nella sintassi inline, fai iniziare il nome con `*` o `!`. Con la validazione parziale, le proprietà mancanti vengono saltate.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nLe proprietà di un oggetto e i loro schemi.\n\nOgni chiave è il nome di una proprietà e ogni valore il suo schema. Le proprietà non dichiarate vengono rimosse dalla risposta.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nUna parola chiave Total.js che aggiunge un controllo di formato o una conversione a stringhe e numeri.\n\nSottotipi di stringa: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (classi Font Awesome o Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Sottotipi numerici con controllo: `smallint`, `tinyint`. `String.toJSONSchema()` imposta il sottotipo in base al nome del tipo.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nLa lunghezza massima di una stringa.\n\nUna stringa più lunga è un errore. Nella sintassi inline, scrivi `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nLa lunghezza minima di una stringa non vuota.\n\nUna stringa più corta è un errore. Un valore vuoto viene controllato solo da `required`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nI valori ammessi di una stringa.\n\nUn valore che non è nell'elenco è un errore. Un valore vuoto è ammesso, a meno che la proprietà non sia obbligatoria. Nella sintassi inline, scrivi `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nIl numero più piccolo ammesso.\n\nUn numero più piccolo è un errore.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nIl numero più grande ammesso.\n\nUn numero più grande è un errore.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nIl numero deve essere maggiore di questo valore.\n\nUn numero minore o uguale al valore è un errore.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nIl numero deve essere minore di questo valore.\n\nUn numero maggiore o uguale al valore è un errore.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nIl numero deve essere un multiplo di questo valore.\n\nUn numero con un resto è un errore.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nLo schema degli elementi di un array.\n\nOgni elemento viene validato da questo schema; gli elementi non validi vengono esclusi e segnalati. Lo schema può essere un tipo semplice, un oggetto con `properties` o un `$ref`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nIl numero minimo di elementi validi in un array.\n\nIl conteggio avviene dopo la rimozione degli elementi non validi. Un array vuoto di una proprietà obbligatoria è sempre un errore.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nRimuove gli elementi duplicati da un array.\n\nI duplicati vengono rimossi in silenzio; non sono un errore. Gli oggetti vengono confrontati per riferimento, quindi l'opzione è utile per i valori semplici.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nIl numero minimo di proprietà valide in un oggetto.\n\nConta le proprietà che finiscono nella risposta.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nUsa un altro schema JSON registrato per una proprietà.\n\nUna proprietà senza `type` e con `$ref` viene validata dallo schema `F.jsonschemas[$ref]`: il nome di un file in `jsonschemas/`, un nome di `NEWJSONSCHEMA()` o un `$id`. Se lo schema non esiste, è un errore. Nella sintassi inline, `@Name` incorpora invece l'altro schema.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nConverte uno schema Total.js in un oggetto schema JSON.\n\nReturns: `Object` L'oggetto schema JSON\n\nConverte i campi dello schema (e i campi di `schema.jsonschema_define()`) in `properties` e i campi obbligatori in `required`. L'`$id` è `CONF.url` (o `https://schemas.totaljs.com/`) + il nome dello schema + `.json`. Il risultato viene registrato in `F.jsonschemas` con il nome dello schema e con l'`$id`.\n\nExample: Esportazione\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDichiara un campo che compare solo nello schema JSON creato da `schema.toJSONSchema()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Nome o nomi del campo |\n| `type` | `String|Object` | yes |  | Tipo del campo come in `schema.define()`, oppure `null` per rimuoverlo |\n| `required` | `Boolean` | no | `false` | Contrassegna il campo come obbligatorio |\n| `invalid` | `String` | no | `'@'` | Messaggio di errore |\n\nReturns: `Function` Una funzione che imposta un valore predefinito e restituisce lo schema\n\nIl campo usa gli stessi tipi di `schema.define()`, ma non partecipa alla normale validazione dello schema Total.js. `type` impostato a `null` rimuove il campo. `name` può essere un array di nomi. Una stringa come terzo argomento è il messaggio di errore e rende il campo obbligatorio.\n\nExample: Campo aggiuntivo\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nCrea e valida in modo sincrono un modello di uno schema Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nome dello schema Total.js |\n| `model` | `Object` | yes |  | Dati |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Salta la validazione |\n| `arg` | `Object` | no |  | Un valore passato alla callback |\n| `controller` | `Controller|SchemaOptions` | no |  | Contesto della richiesta |\n\nReturns: `Object` Il modello creato\n\nChiama `schema.make()` e restituisce il modello creato. Gli errori vanno a `callback(err, response, arg)`. Con `novalidate` il modello viene convertito ma non validato. Per una promise usa `MAKE()` (vedi [Schemi](../schemas/)). Restituisce `undefined` se lo schema non esiste.\n\nExample: Creazione\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nCrea un nuovo modello di uno schema Total.js con i valori predefiniti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Nome dello schema Total.js |\n\nReturns: `Object|null` Un nuovo modello con i valori predefiniti\n\nRestituisce l'oggetto predefinito dello schema (`schema.default()`), oppure `null` se lo schema non esiste. I valori predefiniti provengono dai campi dello schema Total.js.\n\nExample: Valori predefiniti\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabm6L4vr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/json-schemas/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"JSON schémy","summary":"JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), adresár jsonschemas/ a podporované kľúčové slová.","markdown":"---\ntitle: \"JSON schémy\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/json-schemas/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# JSON schémy\n\n> JSONSCHEMA(), NEWJSONSCHEMA(), String.toJSONSchema(), adresár jsonschemas/ a podporované kľúčové slová.\n\nJSON schémy validujú a konvertujú dáta. Načítavajú sa zo súborov `jsonschemas/*.json` a `jsonschemas/*.txt` alebo sa deklarujú cez `NEWJSONSCHEMA()` a `String.toJSONSchema()`. Používa ich `JSONSCHEMA()`, voľby `input`, `output`, `params` a `query` akcií a Total.js schémy.\n\nInline syntax, podporované kľúčové slová a príklady nájdeš v návode [JSON schémy](../../guides/json-schemas/).\n\n## API\n\n### JSONSCHEMA(schema, value, [callback], [error])\n\nType: `method` · Since: `0.0.42`\n\nValiduje a konvertuje hodnotu pomocou JSON schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String|Object` | yes |  | Názov registrovanej JSON schémy alebo objekt schémy |\n| `value` | `Object` | yes |  | Dáta na validáciu |\n| `callback` | `Function` | no |  | `function(err, response)`; bez neho sa vráti promise |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Existujúci error builder, do ktorého sa pridajú chyby |\n\nReturns: `Promise|undefined` Promise, keď nie je zadaný callback\n\n`schema` je názov registrovanej schémy (kľúč v `F.jsonschemas`) alebo objekt schémy. Hodnota sa prevedie na typy schémy a vlastnosti, ktoré schéma nedeklaruje, sa odstránia.\n\nS callbackom volá `callback(err, response)`, kde `err` je `ErrorBuilder` alebo `null`. Bez callbacku vráti promise, ktorý sa splní s odpoveďou alebo zamietne s `ErrorBuilder`. Ak schéma neexistuje, chyba je `404`.\n\n`JSONSCHEMA()` vždy validuje všetky vlastnosti; na čiastočnú validáciu použi metódu `transform()` objektu schémy.\n\nExample: Callback\n```js\nJSONSCHEMA('product', { name: 'Table', price: '120.5' }, function(err, response) {\n\tif (err)\n\t\tconsole.log(err.items);\n\telse\n\t\tconsole.log(response.price); // 120.5\n});\n```\n\nExample: Promise\n```js\nvar model = await JSONSCHEMA('product', $.body);\n```\n\n### NEWJSONSCHEMA(name, [declaration])\n\nType: `method` · Since: `0.0.42`\n\nZaregistruje alebo odstráni JSON schému.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Object` | yes |  | Názov schémy alebo objekt schémy s `$id` |\n| `declaration` | `String` | no |  | Inline deklarácia, napríklad `'name:String, *email:Email'`; vynechaj ju, ak chceš schému odstrániť |\n\n- `NEWJSONSCHEMA(object)` zaregistruje objekt schémy pod jeho `$id`.\n- `NEWJSONSCHEMA(name, declaration)` prevedie inline deklaráciu cez `String.toJSONSchema(name)` a zaregistruje ju pod `name`.\n- `NEWJSONSCHEMA(name)` bez deklarácie schému odstráni.\n\nObjekt schémy registrovaný cez `NEWJSONSCHEMA(object)` sa uloží tak, ako je, bez metódy `transform()`. Používaj ho s `JSONSCHEMA()`; pre akcie radšej použi súbor v `jsonschemas/` alebo inline deklaráciu.\n\nExample: Inline deklarácia\n```js\nNEWJSONSCHEMA('Contact', 'name:String(50), *email:Email, phone:Phone');\n```\n\nExample: Odstránenie\n```js\nNEWJSONSCHEMA('Contact');\n```\n\n### String.toJSONSchema([name], [url])\n\nType: `method` · Since: `0.0.42`\n\nPrevedie inline deklaráciu na objekt JSON schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov, pod ktorým sa schéma zaregistruje; použije sa aj v `$id` |\n| `url` | `String` | no | `CONF.url or https://schemas.totaljs.com/` | Základná URL pre `$id` |\n\nReturns: `Object` Objekt JSON schémy\n\nParsuje dvojice `name:Type` oddelené čiarkami alebo novými riadkami a vráti objekt JSON schémy s `type: 'object'`, `properties`, `required` a metódou `transform()`. S `name` sa schéma zaregistruje aj v `F.jsonschemas`.\n\n`$id` je `url + name + '.json'`. Predvolená URL je `CONF.url` alebo `https://schemas.totaljs.com/`; bez názvu sa použije hash deklarácie. `$schema` je `https://json-schema.org/draft/2020-12/schema`.\n\n| Syntax | Výsledok |\n| --- | --- |\n| `*name`, `!name` | Povinná vlastnosť |\n| `name:String(50)` | `maxLength: 50` |\n| `name:[Type]` | Pole daného typu |\n| `name:{a\\|b\\|c}` | Reťazcový enum (funguje aj `;`) |\n| `name:{a:String, b:Number}` | Vnorený objekt |\n| `name:[{a:String}]` | Pole vnorených objektov |\n| `name:@Other` | Iná Total.js schéma, JSON schéma alebo vstup akcie |\n\n`@Other` vyhodí chybu, ak nič s takým názvom neexistuje.\n\nExample: Vnorené objekty a enumy\n```js\nvar schema = '*name:String(100), role:{admin|user}, address:{street:String, city:String}, items:[{id:UID, qty:Number}]'.toJSONSchema('order');\nvar res = schema.transform({ name: 'Peter', role: 'user', items: [{ id: '', qty: '2' }] });\n```\n\n### jsonschema.transform(value, [partial], [error])\n\nType: `method` · Since: `0.0.66`\n\nZvaliduje hodnotu týmto objektom schémy a výsledok vráti synchrónne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Dáta na validáciu |\n| `partial` | `Boolean` | no | `false` | Validovať len vlastnosti prítomné v hodnote |\n| `error` | `ErrorBuilder` | no | `new ErrorBuilder()` | Existujúci error builder, do ktorého sa pridajú chyby |\n\nReturns: `Object` `{ error: ErrorBuilder|null, response: Object }`\n\nObjekty schém zo súborov `jsonschemas/` a zo `String.toJSONSchema()` majú túto metódu. Vracia `{ error, response }`: `error` je `ErrorBuilder` s chybami alebo `null` a `response` je prevedená hodnota.\n\nS `partial` sa vlastnosti, ktoré sú v hodnote `undefined`, preskočia, takže chýbajúce povinné vlastnosti nie sú chybami. Platí to na každej úrovni, aj pre vlastnosti vnorených objektov.\n\nExample: Čiastočná aktualizácia\n```js\nvar schema = F.jsonschemas.product;\nvar res = schema.transform({ price: '99' }, true);\nif (res.error)\n\t$.invalid(res.error);\nelse\n\t$.success();\n```\n\n### F.jsonschemas\n\nType: `property`\n\nVšetky registrované JSON schémy, podľa názvu a podľa `$id`.\n\nReturns: `Object` Objekty schém podľa kľúča\n\nObjekt so všetkými registrovanými schémami. Súbory z `jsonschemas/` sa ukladajú pod názvom súboru (a pri súboroch `.json` aj pod `$id`), `NEWJSONSCHEMA()` a `String.toJSONSchema(name)` pod názvom a prevedené Total.js schémy pod názvom schémy a svojím `$id`.\n\nExample: Čítanie schémy\n```js\nvar schema = F.jsonschemas.product;\nconsole.log(Object.keys(schema.properties));\n```\n\n### directory_jsonschemas : /jsonschemas/\n\nType: `config` · Since: `0.0.42`\n\nAdresár so súbormi JSON schém.\n\nReturns: `String` Predvolene `/jsonschemas/`\n\nFramework pri štarte aplikácie načíta súbory `.json` a `.txt` z tohto adresára a jeho podadresárov. Ak chceš načítavanie vypnúť, nastav voľbu na prázdnu hodnotu.\n\nExample: config\n```text\ndirectory_jsonschemas : /schemas/json/\n```\n\n### PATH.jsonschemas([filename])\n\nType: `method`\n\nVráti cestu k adresáru JSON schém alebo k súboru v ňom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru |\n\nReturns: `String` Cesta\n\nSpojí `CONF.directory_jsonschemas` s `filename`.\n\nExample: Čítanie súboru\n```js\nvar raw = require('fs').readFileSync(PATH.jsonschemas('product.json'), 'utf8');\n```\n\n### jsonschemas/{name}.json\n\nType: `type` · Since: `0.0.42`\n\nJSON schéma v JSON súbore.\n\nŠtandardný objekt JSON schémy, načítaný pri štarte. Registruje sa pod názvom súboru bez prípony (s podadresárom, napr. `users/address`) a pod svojím `$id`. Framework pridá metódu `transform()`. Neplatný súbor sa nahlási ako chyba a preskočí sa.\n\nExample: jsonschemas/user.json\n```json\n{\n\t\"$id\": \"https://example.com/user.json\",\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"name\": { \"type\": \"string\", \"subtype\": \"name\", \"maxLength\": 50 },\n\t\t\"email\": { \"type\": \"string\", \"subtype\": \"email\" },\n\t\t\"role\": { \"type\": \"string\", \"enum\": [\"admin\", \"user\"] }\n\t},\n\t\"required\": [\"name\", \"email\"]\n}\n```\n\n### jsonschemas/{name}.txt\n\nType: `type` · Since: `0.0.92`\n\nJSON schéma zapísaná v inline syntaxi.\n\nObsah sa prevedie cez `String.toJSONSchema()` a zaregistruje sa pod názvom súboru bez prípony. Píš jednu vlastnosť na riadok alebo ich oddeľ čiarkami.\n\nExample: jsonschemas/user.txt\n```text\n*name:Name(50)\n*email:Email\nrole:{admin|user}\ntags:[String]\n```\n\n### { \"type\": \"string\", \"subtype\": \"...\" }\n\nType: `type`\n\nReťazcová vlastnosť, voliteľne s podtypom.\n\nHodnoty, ktoré nie sú reťazce, sa prevedú na reťazce; prázdne hodnoty sa stanú `null`. Kľúčové slovo `subtype` pridáva formátovanie alebo kontrolu: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color`, `icon`, `name`, `lower`/`lowercase`, `upper`/`uppercase`, `capitalize` a `capitalize2`. Kľúčové slová pre reťazce: `minLength`, `maxLength`, `enum`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"email\", \"maxLength\": 120 }\n```\n\n### { \"type\": \"number\" }\n\nType: `type`\n\nČíselná vlastnosť; ako názov typu sa akceptuje aj `integer`.\n\nReťazce s číslicami sa parsujú cez `String.parseFloat()`; ostatné hodnoty sa stanú `null`. Podtyp `smallint` povoľuje -32767 až 32767 a `tinyint` 0 až 255. Kľúčové slová pre čísla: `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf`. Hodnota sa nezaokrúhľuje, ani pri podtype `int`.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1, \"maximum\": 100 }\n```\n\n### { \"type\": \"boolean\" }\n\nType: `type`\n\nBooleovská vlastnosť; akceptuje sa aj `bool`.\n\nHodnoty, ktoré nie sú booleany, sa parsujú cez `String.parseBoolean()`.\n\nExample: JSON\n```json\n{ \"type\": \"boolean\" }\n```\n\n### { \"type\": \"date\" }\n\nType: `type`\n\nDátumová vlastnosť (rozšírenie JSON schémy v Total.js).\n\nHodnoty, ktoré nie sú objekty `Date`, sa parsujú cez `String.parseDate()`. Neplatný dátum sa stane `null`; chybou je iba vtedy, keď je vlastnosť povinná.\n\nExample: JSON\n```json\n{ \"type\": \"date\" }\n```\n\n### { \"type\": \"object\", \"properties\": {...} }\n\nType: `type`\n\nObjektová vlastnosť, validovaná vlastnými `properties`.\n\nDo odpovede sa kopírujú iba deklarované `properties`. Objekt bez `properties` sa skopíruje tak, ako je. Kľúčové slová pre objekty: `properties`, `required`, `minProperties`, `$ref`.\n\nExample: JSON\n```json\n{\n\t\"type\": \"object\",\n\t\"properties\": {\n\t\t\"street\": { \"type\": \"string\" },\n\t\t\"city\": { \"type\": \"string\" }\n\t},\n\t\"required\": [\"city\"]\n}\n```\n\n### { \"type\": \"array\", \"items\": {...} }\n\nType: `type`\n\nVlastnosť typu pole; každú položku validuje `items`.\n\nBez `items` sa pole skopíruje tak, ako je (s odstránenými duplicitami, ak je nastavené `uniqueItems`). Neplatné položky sa vynechajú a ich chyby sa nahlásia. Kľúčové slová pre polia: `items`, `minItems`, `uniqueItems`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\", \"subtype\": \"email\" }, \"minItems\": 1 }\n```\n\n### \"required\": [\"name\", ...]\n\nType: `property`\n\nZoznam povinných vlastností objektu.\n\nPovinná vlastnosť, ktorá chýba, je prázdna alebo neplatná, je chyba pomenovaná podľa vlastnosti. V inline syntaxi začni názov znakom `*` alebo `!`. Pri čiastočnej validácii sa chýbajúce vlastnosti preskakujú.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" } }, \"required\": [\"name\"] }\n```\n\n### \"properties\": { ... }\n\nType: `property`\n\nVlastnosti objektu a ich schémy.\n\nKaždý kľúč je názov vlastnosti a každá hodnota jej schéma. Vlastnosti, ktoré nie sú deklarované, sa z odpovede odstránia.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"number\" } } }\n```\n\n### \"subtype\": \"email\"\n\nType: `property`\n\nKľúčové slovo Total.js, ktoré k reťazcom a číslam pridáva kontrolu formátu alebo konverziu.\n\nPodtypy reťazcov: `email`, `phone`, `url`, `zip`, `guid`, `uid`, `json`, `base64`, `color` (`#RGB`, `#RRGGBB`, `#RRGGBBAA`), `icon` (triedy Font Awesome alebo Total.js Icons), `name`, `lower`, `lowercase`, `upper`, `uppercase`, `capitalize`, `capitalize2`. Podtypy čísel s kontrolou: `smallint`, `tinyint`. `String.toJSONSchema()` nastaví podtyp podľa názvu typu.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"subtype\": \"phone\" }\n```\n\n### \"maxLength\": 50\n\nType: `property`\n\nMaximálna dĺžka reťazca.\n\nDlhší reťazec je chyba. V inline syntaxi napíš `String(50)`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"maxLength\": 50 }\n```\n\n### \"minLength\": 3\n\nType: `property`\n\nMinimálna dĺžka neprázdneho reťazca.\n\nKratší reťazec je chyba. Prázdnu hodnotu kontroluje iba `required`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"minLength\": 3 }\n```\n\n### \"enum\": [\"a\", \"b\"]\n\nType: `property`\n\nPovolené hodnoty reťazca.\n\nHodnota, ktorá nie je v zozname, je chyba. Prázdna hodnota je povolená, pokiaľ vlastnosť nie je povinná. V inline syntaxi napíš `{a|b}`.\n\nExample: JSON\n```json\n{ \"type\": \"string\", \"enum\": [\"draft\", \"published\"] }\n```\n\n### \"minimum\": 1\n\nType: `property`\n\nNajmenšie povolené číslo.\n\nMenšie číslo je chyba.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"minimum\": 1 }\n```\n\n### \"maximum\": 100\n\nType: `property`\n\nNajväčšie povolené číslo.\n\nVäčšie číslo je chyba.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"maximum\": 100 }\n```\n\n### \"exclusiveMinimum\": 0.5\n\nType: `property`\n\nČíslo musí byť väčšie ako táto hodnota.\n\nČíslo menšie alebo rovné hodnote je chyba.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMinimum\": 0.5 }\n```\n\n### \"exclusiveMaximum\": 10\n\nType: `property`\n\nČíslo musí byť menšie ako táto hodnota.\n\nČíslo väčšie alebo rovné hodnote je chyba.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"exclusiveMaximum\": 10 }\n```\n\n### \"multipleOf\": 5\n\nType: `property`\n\nČíslo musí byť násobkom tejto hodnoty.\n\nČíslo so zvyškom je chyba.\n\nExample: JSON\n```json\n{ \"type\": \"number\", \"multipleOf\": 5 }\n```\n\n### \"items\": { ... }\n\nType: `property`\n\nSchéma položiek poľa.\n\nKaždá položka sa validuje touto schémou; neplatné položky sa vynechajú a nahlásia. Schéma môže byť jednoduchý typ, objekt s `properties` alebo `$ref`.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"number\" } }\n```\n\n### \"minItems\": 1\n\nType: `property`\n\nMinimálny počet platných položiek v poli.\n\nPočíta sa po odstránení neplatných položiek. Prázdne pole povinnej vlastnosti je vždy chyba.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"minItems\": 1 }\n```\n\n### \"uniqueItems\": true\n\nType: `property`\n\nOdstráni z poľa duplicitné položky.\n\nDuplicity sa odstránia potichu; nie sú chybou. Objekty sa porovnávajú podľa referencie, takže voľba je užitočná pre jednoduché hodnoty.\n\nExample: JSON\n```json\n{ \"type\": \"array\", \"items\": { \"type\": \"string\" }, \"uniqueItems\": true }\n```\n\n### \"minProperties\": 1\n\nType: `property`\n\nMinimálny počet platných vlastností v objekte.\n\nPočíta vlastnosti, ktoré skončia v odpovedi.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"a\": { \"type\": \"string\" }, \"b\": { \"type\": \"string\" } }, \"minProperties\": 1 }\n```\n\n### \"$ref\": \"name\"\n\nType: `property`\n\nPoužije pre vlastnosť inú registrovanú JSON schému.\n\nVlastnosť bez `type` a s `$ref` sa validuje schémou `F.jsonschemas[$ref]`: názvom súboru v `jsonschemas/`, názvom z `NEWJSONSCHEMA()` alebo `$id`. Ak schéma neexistuje, je to chyba. V inline syntaxi `@Name` namiesto toho vloží inú schému.\n\nExample: JSON\n```json\n{ \"type\": \"object\", \"properties\": { \"address\": { \"$ref\": \"address\" } } }\n```\n\n### schema.toJSONSchema()\n\nType: `method`\n\nPrevedie Total.js schému na objekt JSON schémy.\n\nReturns: `Object` Objekt JSON schémy\n\nPrevedie polia schémy (a polia zo `schema.jsonschema_define()`) na `properties` a povinné polia na `required`. `$id` je `CONF.url` (alebo `https://schemas.totaljs.com/`) + názov schémy + `.json`. Výsledok sa zaregistruje v `F.jsonschemas` pod názvom schémy a pod `$id`.\n\nExample: Export\n```js\nvar json = GETSCHEMA('Order').toJSONSchema();\nconsole.log(JSON.stringify(json, null, '\\t'));\n```\n\n### schema.jsonschema_define(name, type, [required], [invalid])\n\nType: `method` · Since: `0.0.42`\n\nDeklaruje pole, ktoré sa objaví iba v JSON schéme vytvorenej cez `schema.toJSONSchema()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String|Array` | yes |  | Názov alebo názvy poľa |\n| `type` | `String|Object` | yes |  | Typ poľa ako v `schema.define()` alebo `null` na odstránenie |\n| `required` | `Boolean` | no | `false` | Označí pole ako povinné |\n| `invalid` | `String` | no | `'@'` | Chybová správa |\n\nReturns: `Function` Funkcia, ktorá nastaví predvolenú hodnotu a vráti schému\n\nPole používa rovnaké typy ako `schema.define()`, ale nezúčastňuje sa bežnej validácie Total.js schémy. `type` nastavené na `null` pole odstráni. `name` môže byť pole názvov. Reťazec ako tretí argument je chybová správa a pole urobí povinným.\n\nExample: Pole navyše\n```js\nNEWSCHEMA('Order', function(schema) {\n\tschema.define('id', UID);\n\tschema.jsonschema_define('url', 'URL', true);\n});\n```\n\n### $MAKE(schema, model, [callback], [novalidate], [arg], [controller])\n\nType: `method`\n\nSynchrónne vytvorí a zvaliduje model Total.js schémy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Názov Total.js schémy |\n| `model` | `Object` | yes |  | Dáta |\n| `callback` | `Function` | no |  | `function(err, response, arg)` |\n| `novalidate` | `Boolean` | no | `false` | Preskočiť validáciu |\n| `arg` | `Object` | no |  | Hodnota odovzdaná do callbacku |\n| `controller` | `Controller|SchemaOptions` | no |  | Kontext požiadavky |\n\nReturns: `Object` Vytvorený model\n\nZavolá `schema.make()` a vráti vytvorený model. Chyby idú do `callback(err, response, arg)`. S `novalidate` sa model prevedie, ale nezvaliduje. Pre promise použi `MAKE()` (pozri [Schémy](../schemas/)). Ak schéma neexistuje, vráti `undefined`.\n\nExample: Vytvorenie\n```js\n$MAKE('Order', $.body, function(err, model) {\n\tif (err)\n\t\t$.invalid(err);\n\telse\n\t\t$.success(model.id);\n});\n```\n\n### $CREATE(schema)\n\nType: `method`\n\nVytvorí nový model Total.js schémy s predvolenými hodnotami.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `schema` | `String` | yes |  | Názov Total.js schémy |\n\nReturns: `Object|null` Nový model s predvolenými hodnotami\n\nVráti predvolený objekt schémy (`schema.default()`) alebo `null`, ak schéma neexistuje. Predvolené hodnoty pochádzajú z polí Total.js schémy.\n\nExample: Predvolené hodnoty\n```js\nvar order = $CREATE('Order');\n```\n","entries":[{"type":"method","name":"JSONSCHEMA()","signature":"JSONSCHEMA(schema, value, [callback], [error])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWJSONSCHEMA()","signature":"NEWJSONSCHEMA(name, [declaration])","since":"0.0.42","deprecated":false},{"type":"method","name":"String.toJSONSchema()","signature":"String.toJSONSchema([name], [url])","since":"0.0.42","deprecated":false},{"type":"method","name":"jsonschema.transform()","signature":"jsonschema.transform(value, [partial], [error])","since":"0.0.66","deprecated":false},{"type":"property","name":"F.jsonschemas","signature":"F.jsonschemas","since":"","deprecated":false},{"type":"config","name":"directory_jsonschemas","signature":"directory_jsonschemas : /jsonschemas/","since":"0.0.42","deprecated":false},{"type":"method","name":"PATH.jsonschemas()","signature":"PATH.jsonschemas([filename])","since":"","deprecated":false},{"type":"type","name":"jsonschemas/*.json","signature":"jsonschemas/{name}.json","since":"0.0.42","deprecated":false},{"type":"type","name":"jsonschemas/*.txt","signature":"jsonschemas/{name}.txt","since":"0.0.92","deprecated":false},{"type":"type","name":"type: string","signature":"{ \"type\": \"string\", \"subtype\": \"...\" }","since":"","deprecated":false},{"type":"type","name":"type: number","signature":"{ \"type\": \"number\" }","since":"","deprecated":false},{"type":"type","name":"type: boolean","signature":"{ \"type\": \"boolean\" }","since":"","deprecated":false},{"type":"type","name":"type: date","signature":"{ \"type\": \"date\" }","since":"","deprecated":false},{"type":"type","name":"type: object","signature":"{ \"type\": \"object\", \"properties\": {...} }","since":"","deprecated":false},{"type":"type","name":"type: array","signature":"{ \"type\": \"array\", \"items\": {...} }","since":"","deprecated":false},{"type":"property","name":"required","signature":"\"required\": [\"name\", ...]","since":"","deprecated":false},{"type":"property","name":"properties","signature":"\"properties\": { ... }","since":"","deprecated":false},{"type":"property","name":"subtype","signature":"\"subtype\": \"email\"","since":"","deprecated":false},{"type":"property","name":"maxLength","signature":"\"maxLength\": 50","since":"","deprecated":false},{"type":"property","name":"minLength","signature":"\"minLength\": 3","since":"","deprecated":false},{"type":"property","name":"enum","signature":"\"enum\": [\"a\", \"b\"]","since":"","deprecated":false},{"type":"property","name":"minimum","signature":"\"minimum\": 1","since":"","deprecated":false},{"type":"property","name":"maximum","signature":"\"maximum\": 100","since":"","deprecated":false},{"type":"property","name":"exclusiveMinimum","signature":"\"exclusiveMinimum\": 0.5","since":"","deprecated":false},{"type":"property","name":"exclusiveMaximum","signature":"\"exclusiveMaximum\": 10","since":"","deprecated":false},{"type":"property","name":"multipleOf","signature":"\"multipleOf\": 5","since":"","deprecated":false},{"type":"property","name":"items","signature":"\"items\": { ... }","since":"","deprecated":false},{"type":"property","name":"minItems","signature":"\"minItems\": 1","since":"","deprecated":false},{"type":"property","name":"uniqueItems","signature":"\"uniqueItems\": true","since":"","deprecated":false},{"type":"property","name":"minProperties","signature":"\"minProperties\": 1","since":"","deprecated":false},{"type":"property","name":"$ref","signature":"\"$ref\": \"name\"","since":"","deprecated":false},{"type":"method","name":"schema.toJSONSchema()","signature":"schema.toJSONSchema()","since":"","deprecated":false},{"type":"method","name":"schema.jsonschema_define()","signature":"schema.jsonschema_define(name, type, [required], [invalid])","since":"0.0.42","deprecated":false},{"type":"method","name":"$MAKE()","signature":"$MAKE(schema, model, [callback], [novalidate], [arg], [controller])","since":"","deprecated":false},{"type":"method","name":"$CREATE()","signature":"$CREATE(schema)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"Jabdvd6IR61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Workers, threads and cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() and the cluster API.","markdown":"---\ntitle: Workers, threads and cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Workers, threads and cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() and the cluster API.\n\nEvery function, property and start option for background workers, threads, shell commands and the cluster. The guide [Workers, threads and cluster](../../guides/workers-and-threads/) shows how they fit together.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nRuns a script from /workers/ as a worker_threads thread.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The file name in `/workers/` without `.js`, `@package` or `~/absolute/path.js`; leave it out inside a worker to get the helper |\n| `data` | `Object` | no |  | Data for the thread (`workerData`) |\n\nReturns: `Worker` The thread, or the worker helper when `name` is empty\n\nStarts `/workers/{name}.js` with `new Worker()` of the Node.js `worker_threads` module and returns the `Worker`. `data` reaches the thread as `workerData` (the helper's `worker.data`). The returned object gets `kill()` and `exit()`, which call `terminate()`.\n\nA `name` that starts with `@` points to a package file, one that starts with `~` is an absolute path. Without `name`, the function returns the worker-side helper (see `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Start a thread\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nRuns a script from /workers/ as a child process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | The file name in `/workers/` without `.js`, `@package` or `~/absolute/path.js`; leave it out inside a worker to get the helper |\n\nReturns: `ChildProcess` The child process, or the worker helper when `name` is empty\n\nStarts `/workers/{name}.js` with `child_process.fork()` in the app directory and returns the `ChildProcess`. The object gets `postMessage()` (alias of `send()`) and `terminate()` (sends `SIGTERM`), so it has the same methods as a thread from `NEWTHREAD()`.\n\nThe name rules are the same as in `NEWTHREAD()`. Without `name`, the function returns the worker-side helper.\n\nExample: Start a fork\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nStarts a fixed number of workers and lends them to jobs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `/workers/` without `.js` |\n| `count` | `Number` | yes |  | How many workers to start |\n| `isfork` | `Boolean` | no | `false` | Use child processes instead of threads |\n\nReturns: `Object` The pool with `exec()`, `workers` and `pending`\n\nStarts `count` workers of `/workers/{name}.js` with `NEWTHREAD()`, or with `NEWFORK()` when `isfork` is `true`, and returns a pool. Jobs run with `pool.exec()`. The pool is also stored in `F.workerspool[name]`.\n\nExample: A pool of four threads\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: A pool of child processes\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nRuns a job on the next free worker of a pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Only when `fn` is not given; resolves with the worker\n\nWhen a worker is free, the pool removes its `message` listeners and calls `fn(worker, release)`; inside `fn`, `this` is the worker too. Call `release()` when the job is done so the worker can take the next job. Jobs wait in `pool.pending` while all workers are busy.\n\nWithout `fn` the method returns a promise that resolves with the free worker. Call `worker.release()` when you are done.\n\nExample: With a callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: With await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nThe workers of a pool.\n\nReturns: `Array`\n\nAn array of the `Worker` or `ChildProcess` objects that the pool started. `pool.pending` is the array of jobs that wait for a free worker.\n\n### F.workerspool\n\nType: `property`\n\nThe pools created by NEWTHREADPOOL(), by name.\n\nReturns: `Object`\n\nAn object where each key is the `name` given to `NEWTHREADPOOL()` and each value is the pool. Use it to get a pool in another file.\n\nExample: Use a pool from another file\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nThe data that the parent passed to NEWTHREAD().\n\nReturns: `Object`\n\nInside a worker file, `NEWTHREAD()` or `NEWFORK()` without arguments returns the worker helper. `worker.data` is the `data` argument of `NEWTHREAD(name, data)`. In a child process it is an empty object; send data with a message instead.\n\nExample: In /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nReceives the messages that the parent sends to the worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | The message from the parent |\n\nAssign a function to the helper returned by `NEWTHREAD()` or `NEWFORK()` without arguments. It is called for each message from the parent, in a thread and in a child process.\n\nExample: Answer each message\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nSends a message from the worker to the parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | A serialisable value |\n\nUses `parentPort.postMessage()` in a thread and `process.send()` in a child process. `worker.postMessage()` is the same method. The parent receives the message in `on('message')` of the object that `NEWTHREAD()` or `NEWFORK()` returned.\n\nExample: Report progress\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nEnds the worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | The exit code |\n\nCalls `process.exit(code)`. `worker.kill()` and `worker.close()` are the same method.\n\nExample: Finish after the answer\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nEnds the worker after a time limit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milliseconds |\n\nStarts a timer that ends the worker with exit code `1` after `timeout` milliseconds. A new call replaces the previous timer, so you can call it again to extend the limit while the worker is busy.\n\nExample: Limit the worker to one minute\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nForks a script from /workers/ (the older API).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `/workers/`, without `.js` |\n| `timeout` | `Number` | no |  | Kills the process after this many milliseconds |\n| `args` | `Array` | no |  | Command-line arguments for the script |\n\nReturns: `ChildProcess`\n\nRuns `/workers/{name}.js` with `child_process.fork()` in the app directory and returns the `ChildProcess`. The arguments `args` and `--worker` are passed to the script. The process is stored in `F.workers` until it exits. When `timeout` (more than 10 ms) passes, the process is killed with `SIGKILL`.\n\n`timeout` can be left out: `WORKER(name, args)`. A name that starts with `@` points to a package file; a name that starts with `#` returns a running worker from `F.workers` by its id. `NEWFORK()` is the newer alternative.\n\nExample: Run a worker for at most 10 seconds\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nRuns a script from /workers/ and returns its standard output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name in `/workers/`, without `.js` |\n| `args` | `Array` | no |  | Command-line arguments; the script reads them from `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Kills the process after this many milliseconds |\n\nReturns: `ChildProcess`\n\nForks `/workers/{name}.js` silently (like `WORKER()`), collects everything it writes to the standard output and calls `callback(err, buffer)` when the process exits or fails. `args` can be an array or one value. The order of `callback` and `timeout` can be swapped.\n\nExample: Read the output of a script\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nThe running processes started by WORKER().\n\nReturns: `Object`\n\nAn object of the child processes that `WORKER()` and `WORKER2()` started, by their id (`{name}_{number}`). A process is removed when it exits. When the app stops, all of them are killed.\n\n### PATH.workers([filename])\n\nType: `method`\n\nReturns the path to a file in the /workers/ directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | A file name |\n\nReturns: `String`\n\nJoins `directory_workers` (default `/workers/`) with `filename` and returns the full path.\n\nExample: Check a worker file\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue when the framework runs through LOAD() without the HTTP server.\n\nReturns: `Boolean`\n\nThe global is `false` by default. `LOAD()` sets it to `true`, and `HTTP()` sets it back to `false`. Use it in shared code that must not do things that need a web server (for example start schedulers) when it runs in a worker.\n\nExample: Skip a timer in workers\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nLoads parts of the app without starting the HTTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | The parts to load or to skip |\n| `cwd` | `String` | no |  | The app directory |\n| `callback` | `Function` | no |  | Called when the app is loaded |\n\nReturns: `Promise` Only when `callback` is not given\n\nUse it in worker files and scripts. It reads the config and `.env`, loads the parts named in `types` and calls `callback` (or resolves the returned promise) when they are ready. It sets `isWORKER` to `true` and emits `load` and `ready`.\n\n`types` is an array or a string separated by commas or spaces, for example `'config,modules,schemas'`. Names with the `no` prefix (`'nobundles'`) exclude a part and load the rest. The default is `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Add `'debug'` to run in debug mode and `'service'` to run the `ON('service')` timer. Parts: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: A worker with schemas\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: With await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nRuns a shell command.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | The command line |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | The working directory |\n\nReturns: `Promise` Only when `callback` is not given; resolves with stdout\n\nRuns `command` with `child_process.exec()`. The working directory is `cwd` or the app directory; the shell is `default_shell` when it is set. The callback receives `(err, stdout, stderr)`. Without a callback the function returns a promise that resolves with the standard output. You can pass `cwd` as the second argument when you use the promise.\n\nNever put user input into `command` without escaping it.\n\nExample: With a callback\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: With await and a directory\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nThe shell that SHELL() uses.\n\nReturns: `String`\n\nThe path of the shell for `SHELL()` (the `shell` option of `child_process.exec()`). When it is not set, Node.js uses `/bin/sh` on Unix and `cmd.exe` on Windows.\n\nExample: In the config file\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nRuns the app as a cluster of several instances.\n\nReturns: `Number|String`\n\nA start-script option of `total4/release` and `total4/debug`. A number starts that many instances of the app; `'auto'` starts one and adds or removes instances by their response time (see `options.cluster_limit`). The master process restarts an instance that exits after one second. In debug mode the master restarts all instances when a file changes.\n\nWhen `options.threads` is set, the value applies to each thread instead of the main app.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nThe maximum number of instances in the auto cluster.\n\nReturns: `Number`\n\nWith `options.cluster = 'auto'`, the master pings the instances every five seconds. It adds an instance when the average response is over 70 ms, until the count reaches `cluster_limit`. Without it there is no limit. When an instance answers fast, the master removes the last instance (at most every 25 seconds) if it has fewer than two pending requests.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nThe time zone of a cluster.\n\nReturns: `String`\n\nIn cluster mode the master sets `process.env.TZ` for all instances to this value. When you do not set it, the cluster runs in `'utc'`, whatever the time zone of the server is.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nRuns every subdirectory of /threads/ as a separate app.\n\nReturns: `String|Boolean`\n\nFor each directory in `/threads/` the main app writes a start script `{script}_{name}.js` into the root and forks it. Requests under `{threads}/{name}/` are forwarded to that thread over a Unix socket, without the prefix. `true` means no prefix (`/{name}/`).\n\nEach thread loads the `.js` files of its directory with `exports.install`, its own config and `.env` files, `views/` and `public/`. It skips the root `/controllers/` and `/middleware/`.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nThe thread name of the process.\n\nReturns: `String`\n\nSets the global `THREAD` and loads the app as the thread `/threads/{name}/`. The scripts that `options.threads` writes set it for you. In cluster mode, the restart file is `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nWrites the output of each thread into its own log file.\n\nReturns: `String`\n\nWith `'isolated'`, the output of a thread goes to `/threads/{name}/logs/debug.log` instead of the console of the main app. The file is cleared when the thread starts (in debug mode only on the first start).\n\n### THREAD\n\nType: `property`\n\nThe name of the current thread.\n\nReturns: `String`\n\nAn empty string in a normal app. Inside a thread of `/threads/{name}/` it is the name of the thread. The framework adds it to the console banner and to audit logs.\n\nExample: Use the thread name\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nThe child processes of the threads, by name.\n\nReturns: `Object`\n\nIn the main app with `options.threads`, an object where each key is a thread name and each value is its `ChildProcess`. Otherwise `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue in an instance of a cluster.\n\nReturns: `Boolean`\n\n`true` when the process is an instance started by the cluster master.\n\nExample: Run a job in one instance only\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nThe id of the instance in a cluster.\n\nReturns: `String`\n\nThe index of the instance as a string (`'0'`, `'1'`, ...), or `null` outside a cluster. Temporary files of an instance get the prefix `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nRaises an event in every instance of the cluster.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name |\n| `a` | `Object` | no |  | Up to five arguments |\n\nReturns: `Framework`\n\nSends the event through the master to all instances, the sender included. Each instance calls its `ON(name)` listeners with up to five arguments. The arguments travel as IPC messages, so they must be serialisable. Outside a cluster it does nothing.\n\nExample: Clear a cache everywhere\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nSends an event from an instance to the master process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name |\n| `a` | `Object` | no |  | Up to five arguments |\n\nReturns: `Framework`\n\nThe master calls the listeners registered with `F.cluster.on(name)`. Outside a cluster it does nothing.\n\nExample: Report to the master\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nListens in the master process to events from F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The event name |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nRegister it in the start script: the master runs that script, and so does every instance. The callback receives the arguments of `F.cluster.master()`. Register only one listener per name.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nRestarts instances of the cluster from the master process.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | The index of the instance |\n\nRestarts the instance with `index`, or all instances two seconds apart when `index` is not given. It works only in the master process. From outside, create the `restart` file instead.\n\nExample: Restart all instances from the start script\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nStarts a cluster with an HTTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Number of instances or `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` or `'release'` |\n| `options` | `Object` | no |  | Start options |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nThis is what `options.cluster` calls in the start script. `count` is a number, `'auto'` or `null` (one instance per CPU core). `mode` is `'debug'` or `'release'`. `options` are the start options that the instances receive. In the master, `callback` is called with the array of instances when all of them have started. `F.cluster.https()` takes the same arguments and starts HTTPS servers.\n\nExample: Start a cluster directly\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nA file that restarts all instances of a running cluster.\n\nThe master checks every five seconds for a file named `restart` in the app directory (`restart_{thread}` when `options.thread` is set). When it finds it, it deletes the file and restarts all instances two seconds apart, at most once in 30 seconds. Use it after a deploy to load new code without stopping the app.\n\nThe master also writes its state (PID, versions, instance count, memory and statistics of every instance) into the start script name plus `.json`, for example `index.js.json`, about every 50 seconds.\n\nExample: Restart after a deploy\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSynchronizes the framework cache between cluster instances.\n\nReturns: `Boolean`\n\nWhen `true`, every `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` and `clear()` in an instance is repeated in the other instances. Sessions are synchronized in a cluster without this option.\n\nExample: In the config file\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdvd6IR61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Worker, Threads und Cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() und die Cluster-API.","markdown":"---\ntitle: Worker, Threads und Cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Worker, Threads und Cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() und die Cluster-API.\n\nJede Funktion, Eigenschaft und Startoption für Hintergrund-Worker, Threads, Shell-Befehle und den Cluster. Der Leitfaden [Worker, Threads und Cluster](../../guides/workers-and-threads/) zeigt, wie sie zusammenpassen.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nFührt ein Skript aus /workers/ als worker_threads-Thread aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Dateiname in `/workers/` ohne `.js`, `@package` oder `~/absolute/path.js`; lass ihn innerhalb eines Workers weg, um das Hilfsobjekt zu bekommen |\n| `data` | `Object` | no |  | Daten für den Thread (`workerData`) |\n\nReturns: `Worker` Der Thread oder das Worker-Hilfsobjekt, wenn `name` leer ist\n\nStartet `/workers/{name}.js` mit `new Worker()` aus dem Node.js-Modul `worker_threads` und gibt den `Worker` zurück. `data` erreicht den Thread als `workerData` (im Hilfsobjekt `worker.data`). Das zurückgegebene Objekt bekommt `kill()` und `exit()`, die `terminate()` aufrufen.\n\nEin `name`, der mit `@` beginnt, verweist auf eine Paketdatei, einer, der mit `~` beginnt, ist ein absoluter Pfad. Ohne `name` gibt die Funktion das Hilfsobjekt der Worker-Seite zurück (siehe `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Einen Thread starten\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nFührt ein Skript aus /workers/ als Kindprozess aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Der Dateiname in `/workers/` ohne `.js`, `@package` oder `~/absolute/path.js`; lass ihn innerhalb eines Workers weg, um das Hilfsobjekt zu bekommen |\n\nReturns: `ChildProcess` Der Kindprozess oder das Worker-Hilfsobjekt, wenn `name` leer ist\n\nStartet `/workers/{name}.js` mit `child_process.fork()` im App-Verzeichnis und gibt den `ChildProcess` zurück. Das Objekt bekommt `postMessage()` (Alias von `send()`) und `terminate()` (sendet `SIGTERM`), sodass es dieselben Methoden hat wie ein Thread aus `NEWTHREAD()`.\n\nDie Regeln für den Namen sind dieselben wie bei `NEWTHREAD()`. Ohne `name` gibt die Funktion das Hilfsobjekt der Worker-Seite zurück.\n\nExample: Einen Fork starten\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nStartet eine feste Anzahl von Workern und leiht sie an Jobs aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `/workers/` ohne `.js` |\n| `count` | `Number` | yes |  | Wie viele Worker gestartet werden |\n| `isfork` | `Boolean` | no | `false` | Kindprozesse statt Threads verwenden |\n\nReturns: `Object` Der Pool mit `exec()`, `workers` und `pending`\n\nStartet `count` Worker von `/workers/{name}.js` mit `NEWTHREAD()` oder mit `NEWFORK()`, wenn `isfork` gleich `true` ist, und gibt einen Pool zurück. Jobs laufen mit `pool.exec()`. Der Pool wird außerdem in `F.workerspool[name]` gespeichert.\n\nExample: Ein Pool aus vier Threads\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: Ein Pool aus Kindprozessen\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nFührt einen Job auf dem nächsten freien Worker eines Pools aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Nur wenn `fn` nicht angegeben ist; wird mit dem Worker aufgelöst\n\nWenn ein Worker frei ist, entfernt der Pool dessen `message`-Listener und ruft `fn(worker, release)` auf; innerhalb von `fn` ist auch `this` der Worker. Rufe `release()` auf, wenn der Job fertig ist, damit der Worker den nächsten Job übernehmen kann. Jobs warten in `pool.pending`, solange alle Worker belegt sind.\n\nOhne `fn` gibt die Methode ein Promise zurück, das mit dem freien Worker aufgelöst wird. Rufe `worker.release()` auf, wenn du fertig bist.\n\nExample: Mit einem Callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: Mit await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nDie Worker eines Pools.\n\nReturns: `Array`\n\nEin Array der `Worker`- oder `ChildProcess`-Objekte, die der Pool gestartet hat. `pool.pending` ist das Array der Jobs, die auf einen freien Worker warten.\n\n### F.workerspool\n\nType: `property`\n\nDie von NEWTHREADPOOL() erzeugten Pools, nach Namen.\n\nReturns: `Object`\n\nEin Objekt, in dem jeder Schlüssel der an `NEWTHREADPOOL()` übergebene `name` ist und jeder Wert der Pool. Verwende es, um in einer anderen Datei an einen Pool zu kommen.\n\nExample: Einen Pool aus einer anderen Datei verwenden\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nDie Daten, die der Elternprozess an NEWTHREAD() übergeben hat.\n\nReturns: `Object`\n\nIn einer Worker-Datei gibt `NEWTHREAD()` oder `NEWFORK()` ohne Argumente das Worker-Hilfsobjekt zurück. `worker.data` ist das Argument `data` von `NEWTHREAD(name, data)`. In einem Kindprozess ist es ein leeres Objekt; sende Daten stattdessen mit einer Nachricht.\n\nExample: In /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nEmpfängt die Nachrichten, die der Elternprozess an den Worker sendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Die Nachricht des Elternprozesses |\n\nWeise dem Hilfsobjekt, das `NEWTHREAD()` oder `NEWFORK()` ohne Argumente zurückgibt, eine Funktion zu. Sie wird für jede Nachricht des Elternprozesses aufgerufen, in einem Thread und in einem Kindprozess.\n\nExample: Jede Nachricht beantworten\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nSendet eine Nachricht vom Worker an den Elternprozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Ein serialisierbarer Wert |\n\nVerwendet `parentPort.postMessage()` in einem Thread und `process.send()` in einem Kindprozess. `worker.postMessage()` ist dieselbe Methode. Der Elternprozess empfängt die Nachricht in `on('message')` des Objekts, das `NEWTHREAD()` oder `NEWFORK()` zurückgegeben hat.\n\nExample: Fortschritt melden\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nBeendet den Worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | Der Exit-Code |\n\nRuft `process.exit(code)` auf. `worker.kill()` und `worker.close()` sind dieselbe Methode.\n\nExample: Nach der Antwort beenden\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nBeendet den Worker nach einem Zeitlimit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisekunden |\n\nStartet einen Timer, der den Worker nach `timeout` Millisekunden mit dem Exit-Code `1` beendet. Ein neuer Aufruf ersetzt den vorherigen Timer, sodass du ihn erneut aufrufen kannst, um das Limit zu verlängern, während der Worker beschäftigt ist.\n\nExample: Den Worker auf eine Minute begrenzen\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nForkt ein Skript aus /workers/ (die ältere API).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `/workers/`, ohne `.js` |\n| `timeout` | `Number` | no |  | Beendet den Prozess nach so vielen Millisekunden |\n| `args` | `Array` | no |  | Kommandozeilenargumente für das Skript |\n\nReturns: `ChildProcess`\n\nFührt `/workers/{name}.js` mit `child_process.fork()` im App-Verzeichnis aus und gibt den `ChildProcess` zurück. Die Argumente `args` und `--worker` werden an das Skript übergeben. Der Prozess wird in `F.workers` gespeichert, bis er sich beendet. Wenn `timeout` (mehr als 10 ms) abläuft, wird der Prozess mit `SIGKILL` beendet.\n\n`timeout` kann weggelassen werden: `WORKER(name, args)`. Ein Name, der mit `@` beginnt, verweist auf eine Paketdatei; ein Name, der mit `#` beginnt, gibt einen laufenden Worker aus `F.workers` anhand seiner ID zurück. `NEWFORK()` ist die neuere Alternative.\n\nExample: Einen Worker höchstens 10 Sekunden laufen lassen\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nFührt ein Skript aus /workers/ aus und gibt seine Standardausgabe zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname in `/workers/`, ohne `.js` |\n| `args` | `Array` | no |  | Kommandozeilenargumente; das Skript liest sie aus `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Beendet den Prozess nach so vielen Millisekunden |\n\nReturns: `ChildProcess`\n\nForkt `/workers/{name}.js` still (wie `WORKER()`), sammelt alles, was es in die Standardausgabe schreibt, und ruft `callback(err, buffer)` auf, wenn der Prozess endet oder fehlschlägt. `args` kann ein Array oder ein einzelner Wert sein. Die Reihenfolge von `callback` und `timeout` kann vertauscht werden.\n\nExample: Die Ausgabe eines Skripts lesen\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nDie laufenden Prozesse, die WORKER() gestartet hat.\n\nReturns: `Object`\n\nEin Objekt der Kindprozesse, die `WORKER()` und `WORKER2()` gestartet haben, nach ihrer ID (`{name}_{number}`). Ein Prozess wird entfernt, wenn er sich beendet. Wenn die App anhält, werden alle beendet.\n\n### PATH.workers([filename])\n\nType: `method`\n\nGibt den Pfad zu einer Datei im Verzeichnis /workers/ zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Ein Dateiname |\n\nReturns: `String`\n\nVerbindet `directory_workers` (Standard `/workers/`) mit `filename` und gibt den vollständigen Pfad zurück.\n\nExample: Eine Worker-Datei prüfen\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue, wenn das Framework über LOAD() ohne HTTP-Server läuft.\n\nReturns: `Boolean`\n\nDie globale Variable ist standardmäßig `false`. `LOAD()` setzt sie auf `true`, und `HTTP()` setzt sie wieder auf `false`. Verwende sie in gemeinsamem Code, der in einem Worker keine Dinge tun darf, die einen Webserver brauchen (zum Beispiel Scheduler starten).\n\nExample: Einen Timer in Workern überspringen\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nLädt Teile der App, ohne den HTTP-Server zu starten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | Die Teile, die geladen oder übersprungen werden |\n| `cwd` | `String` | no |  | Das App-Verzeichnis |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn die App geladen ist |\n\nReturns: `Promise` Nur wenn `callback` nicht angegeben ist\n\nVerwende es in Worker-Dateien und Skripten. Es liest die Konfiguration und `.env`, lädt die in `types` genannten Teile und ruft `callback` auf (oder löst das zurückgegebene Promise auf), wenn sie bereit sind. Es setzt `isWORKER` auf `true` und löst `load` und `ready` aus.\n\n`types` ist ein Array oder ein durch Kommas oder Leerzeichen getrennter String, zum Beispiel `'config,modules,schemas'`. Namen mit dem Präfix `no` (`'nobundles'`) schließen einen Teil aus und laden den Rest. Der Standard ist `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Füge `'debug'` hinzu, um im Debug-Modus zu laufen, und `'service'`, um den Timer `ON('service')` auszuführen. Teile: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: Ein Worker mit Schemas\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: Mit await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nFührt einen Shell-Befehl aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | Die Befehlszeile |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | Das Arbeitsverzeichnis |\n\nReturns: `Promise` Nur wenn `callback` nicht angegeben ist; wird mit stdout aufgelöst\n\nFührt `command` mit `child_process.exec()` aus. Das Arbeitsverzeichnis ist `cwd` oder das App-Verzeichnis; die Shell ist `default_shell`, wenn es gesetzt ist. Der Callback erhält `(err, stdout, stderr)`. Ohne Callback gibt die Funktion ein Promise zurück, das mit der Standardausgabe aufgelöst wird. Du kannst `cwd` als zweites Argument übergeben, wenn du das Promise verwendest.\n\nSetze niemals Benutzereingaben ohne Escaping in `command` ein.\n\nExample: Mit einem Callback\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: Mit await und einem Verzeichnis\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nDie Shell, die SHELL() verwendet.\n\nReturns: `String`\n\nDer Pfad der Shell für `SHELL()` (die Option `shell` von `child_process.exec()`). Wenn er nicht gesetzt ist, verwendet Node.js `/bin/sh` unter Unix und `cmd.exe` unter Windows.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nBetreibt die App als Cluster aus mehreren Instanzen.\n\nReturns: `Number|String`\n\nEine Startskript-Option von `total4/release` und `total4/debug`. Eine Zahl startet so viele Instanzen der App; `'auto'` startet eine und fügt Instanzen je nach Antwortzeit hinzu oder entfernt sie (siehe `options.cluster_limit`). Der Master-Prozess startet eine Instanz, die sich beendet, nach einer Sekunde neu. Im Debug-Modus startet der Master alle Instanzen neu, wenn sich eine Datei ändert.\n\nWenn `options.threads` gesetzt ist, gilt der Wert für jeden Thread statt für die Haupt-App.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nDie maximale Anzahl von Instanzen im Auto-Cluster.\n\nReturns: `Number`\n\nMit `options.cluster = 'auto'` pingt der Master die Instanzen alle fünf Sekunden an. Er fügt eine Instanz hinzu, wenn die durchschnittliche Antwort über 70 ms liegt, bis die Anzahl `cluster_limit` erreicht. Ohne diesen Wert gibt es kein Limit. Wenn eine Instanz schnell antwortet, entfernt der Master die letzte Instanz (höchstens alle 25 Sekunden), sofern sie weniger als zwei ausstehende Requests hat.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nDie Zeitzone eines Clusters.\n\nReturns: `String`\n\nIm Cluster-Modus setzt der Master `process.env.TZ` für alle Instanzen auf diesen Wert. Wenn du ihn nicht setzt, läuft der Cluster in `'utc'`, unabhängig von der Zeitzone des Servers.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nBetreibt jedes Unterverzeichnis von /threads/ als getrennte App.\n\nReturns: `String|Boolean`\n\nFür jedes Verzeichnis in `/threads/` schreibt die Haupt-App ein Startskript `{script}_{name}.js` ins Wurzelverzeichnis und forkt es. Requests unter `{threads}/{name}/` werden über einen Unix-Socket ohne das Präfix an diesen Thread weitergeleitet. `true` bedeutet kein Präfix (`/{name}/`).\n\nJeder Thread lädt die `.js`-Dateien seines Verzeichnisses mit `exports.install`, seine eigenen Konfigurations- und `.env`-Dateien, `views/` und `public/`. Er überspringt die Wurzelverzeichnisse `/controllers/` und `/middleware/`.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nDer Thread-Name des Prozesses.\n\nReturns: `String`\n\nSetzt die globale Variable `THREAD` und lädt die App als Thread `/threads/{name}/`. Die Skripte, die `options.threads` schreibt, setzen das für dich. Im Cluster-Modus ist die Neustart-Datei `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nSchreibt die Ausgabe jedes Threads in eine eigene Logdatei.\n\nReturns: `String`\n\nMit `'isolated'` geht die Ausgabe eines Threads nach `/threads/{name}/logs/debug.log` statt in die Konsole der Haupt-App. Die Datei wird geleert, wenn der Thread startet (im Debug-Modus nur beim ersten Start).\n\n### THREAD\n\nType: `property`\n\nDer Name des aktuellen Threads.\n\nReturns: `String`\n\nIn einer normalen App ein leerer String. Innerhalb eines Threads von `/threads/{name}/` ist es der Name des Threads. Das Framework fügt ihn dem Konsolenbanner und den Audit-Logs hinzu.\n\nExample: Den Thread-Namen verwenden\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nDie Kindprozesse der Threads, nach Namen.\n\nReturns: `Object`\n\nIn der Haupt-App mit `options.threads` ein Objekt, in dem jeder Schlüssel ein Thread-Name und jeder Wert dessen `ChildProcess` ist. Sonst `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue in einer Instanz eines Clusters.\n\nReturns: `Boolean`\n\n`true`, wenn der Prozess eine vom Cluster-Master gestartete Instanz ist.\n\nExample: Einen Job nur in einer Instanz ausführen\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nDie ID der Instanz in einem Cluster.\n\nReturns: `String`\n\nDer Index der Instanz als String (`'0'`, `'1'`, ...) oder `null` außerhalb eines Clusters. Temporäre Dateien einer Instanz bekommen das Präfix `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nLöst ein Event in jeder Instanz des Clusters aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events |\n| `a` | `Object` | no |  | Bis zu fünf Argumente |\n\nReturns: `Framework`\n\nSendet das Event über den Master an alle Instanzen, auch an den Absender. Jede Instanz ruft ihre `ON(name)`-Listener mit bis zu fünf Argumenten auf. Die Argumente reisen als IPC-Nachrichten, sie müssen also serialisierbar sein. Außerhalb eines Clusters tut es nichts.\n\nExample: Einen Cache überall leeren\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nSendet ein Event von einer Instanz an den Master-Prozess.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events |\n| `a` | `Object` | no |  | Bis zu fünf Argumente |\n\nReturns: `Framework`\n\nDer Master ruft die mit `F.cluster.on(name)` registrierten Listener auf. Außerhalb eines Clusters tut es nichts.\n\nExample: An den Master melden\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nHört im Master-Prozess auf Events von F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Events |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nRegistriere es im Startskript: Der Master führt dieses Skript aus, und jede Instanz ebenfalls. Der Callback erhält die Argumente von `F.cluster.master()`. Registriere nur einen Listener pro Name.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nStartet Instanzen des Clusters vom Master-Prozess aus neu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | Der Index der Instanz |\n\nStartet die Instanz mit `index` neu, oder alle Instanzen im Abstand von zwei Sekunden, wenn `index` nicht angegeben ist. Es funktioniert nur im Master-Prozess. Von außen erstellst du stattdessen die Datei `restart`.\n\nExample: Alle Instanzen aus dem Startskript neu starten\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nStartet einen Cluster mit einem HTTP-Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Anzahl der Instanzen oder `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` oder `'release'` |\n| `options` | `Object` | no |  | Startoptionen |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nDas ist es, was `options.cluster` im Startskript aufruft. `count` ist eine Zahl, `'auto'` oder `null` (eine Instanz pro CPU-Kern). `mode` ist `'debug'` oder `'release'`. `options` sind die Startoptionen, die die Instanzen erhalten. Im Master wird `callback` mit dem Array der Instanzen aufgerufen, wenn alle gestartet sind. `F.cluster.https()` nimmt dieselben Argumente und startet HTTPS-Server.\n\nExample: Einen Cluster direkt starten\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nEine Datei, die alle Instanzen eines laufenden Clusters neu startet.\n\nDer Master prüft alle fünf Sekunden, ob es im App-Verzeichnis eine Datei namens `restart` gibt (`restart_{thread}`, wenn `options.thread` gesetzt ist). Findet er sie, löscht er die Datei und startet alle Instanzen im Abstand von zwei Sekunden neu, höchstens einmal in 30 Sekunden. Verwende sie nach einem Deployment, um neuen Code zu laden, ohne die App anzuhalten.\n\nDer Master schreibt außerdem etwa alle 50 Sekunden seinen Zustand (PID, Versionen, Anzahl der Instanzen, Speicher und Statistiken jeder Instanz) in den Namen des Startskripts plus `.json`, zum Beispiel `index.js.json`.\n\nExample: Nach einem Deployment neu starten\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSynchronisiert den Framework-Cache zwischen den Cluster-Instanzen.\n\nReturns: `Boolean`\n\nBei `true` wird jedes `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` und `clear()` in einer Instanz in den anderen Instanzen wiederholt. Sessions werden in einem Cluster auch ohne diese Option synchronisiert.\n\nExample: In der Konfigurationsdatei\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdvd6IR61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Workers, hilos y clúster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() y la API del clúster.","markdown":"---\ntitle: \"Workers, hilos y clúster\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Workers, hilos y clúster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() y la API del clúster.\n\nTodas las funciones, propiedades y opciones de inicio para workers en segundo plano, hilos, comandos de shell y el clúster. La guía [Workers, hilos y clúster](../../guides/workers-and-threads/) muestra cómo encajan entre sí.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nEjecuta un script de /workers/ como hilo worker_threads.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre del archivo en `/workers/` sin `.js`, `@package` o `~/absolute/path.js`; omítelo dentro de un worker para obtener el objeto auxiliar |\n| `data` | `Object` | no |  | Datos para el hilo (`workerData`) |\n\nReturns: `Worker` El hilo, o el objeto auxiliar del worker cuando `name` está vacío\n\nInicia `/workers/{name}.js` con `new Worker()` del módulo `worker_threads` de Node.js y devuelve el `Worker`. `data` llega al hilo como `workerData` (el `worker.data` del objeto auxiliar). El objeto devuelto recibe `kill()` y `exit()`, que llaman a `terminate()`.\n\nUn `name` que empieza por `@` apunta a un archivo de un paquete; uno que empieza por `~` es una ruta absoluta. Sin `name`, la función devuelve el objeto auxiliar del lado del worker (consulta `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Iniciar un hilo\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nEjecuta un script de /workers/ como proceso hijo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | El nombre del archivo en `/workers/` sin `.js`, `@package` o `~/absolute/path.js`; omítelo dentro de un worker para obtener el objeto auxiliar |\n\nReturns: `ChildProcess` El proceso hijo, o el objeto auxiliar del worker cuando `name` está vacío\n\nInicia `/workers/{name}.js` con `child_process.fork()` en el directorio de la app y devuelve el `ChildProcess`. El objeto recibe `postMessage()` (alias de `send()`) y `terminate()` (envía `SIGTERM`), así que tiene los mismos métodos que un hilo de `NEWTHREAD()`.\n\nLas reglas del nombre son las mismas que en `NEWTHREAD()`. Sin `name`, la función devuelve el objeto auxiliar del lado del worker.\n\nExample: Iniciar un fork\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nInicia un número fijo de workers y los presta a los trabajos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `/workers/` sin `.js` |\n| `count` | `Number` | yes |  | Cuántos workers iniciar |\n| `isfork` | `Boolean` | no | `false` | Usa procesos hijo en lugar de hilos |\n\nReturns: `Object` El pool con `exec()`, `workers` y `pending`\n\nInicia `count` workers de `/workers/{name}.js` con `NEWTHREAD()`, o con `NEWFORK()` cuando `isfork` es `true`, y devuelve un pool. Los trabajos se ejecutan con `pool.exec()`. El pool también se guarda en `F.workerspool[name]`.\n\nExample: Un pool de cuatro hilos\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: Un pool de procesos hijo\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nEjecuta un trabajo en el siguiente worker libre de un pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Solo cuando no se pasa `fn`; se resuelve con el worker\n\nCuando hay un worker libre, el pool elimina sus listeners de `message` y llama a `fn(worker, release)`; dentro de `fn`, `this` también es el worker. Llama a `release()` cuando el trabajo termine para que el worker pueda tomar el siguiente. Los trabajos esperan en `pool.pending` mientras todos los workers están ocupados.\n\nSin `fn` el método devuelve una promesa que se resuelve con el worker libre. Llama a `worker.release()` cuando termines.\n\nExample: Con un callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: Con await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nLos workers de un pool.\n\nReturns: `Array`\n\nUn array de los objetos `Worker` o `ChildProcess` que inició el pool. `pool.pending` es el array de trabajos que esperan un worker libre.\n\n### F.workerspool\n\nType: `property`\n\nLos pools creados por NEWTHREADPOOL(), por nombre.\n\nReturns: `Object`\n\nUn objeto donde cada clave es el `name` dado a `NEWTHREADPOOL()` y cada valor es el pool. Úsalo para obtener un pool en otro archivo.\n\nExample: Usar un pool desde otro archivo\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nLos datos que el padre pasó a NEWTHREAD().\n\nReturns: `Object`\n\nDentro de un archivo de worker, `NEWTHREAD()` o `NEWFORK()` sin argumentos devuelve el objeto auxiliar del worker. `worker.data` es el argumento `data` de `NEWTHREAD(name, data)`. En un proceso hijo es un objeto vacío; en ese caso envía los datos con un mensaje.\n\nExample: En /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nRecibe los mensajes que el padre envía al worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | El mensaje del padre |\n\nAsigna una función al objeto auxiliar que devuelve `NEWTHREAD()` o `NEWFORK()` sin argumentos. Se llama con cada mensaje del padre, en un hilo y en un proceso hijo.\n\nExample: Responder a cada mensaje\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nEnvía un mensaje del worker al padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Un valor serializable |\n\nUsa `parentPort.postMessage()` en un hilo y `process.send()` en un proceso hijo. `worker.postMessage()` es el mismo método. El padre recibe el mensaje en `on('message')` del objeto que devolvió `NEWTHREAD()` o `NEWFORK()`.\n\nExample: Informar del progreso\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nTermina el worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | El código de salida |\n\nLlama a `process.exit(code)`. `worker.kill()` y `worker.close()` son el mismo método.\n\nExample: Terminar después de la respuesta\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nTermina el worker tras un límite de tiempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milisegundos |\n\nInicia un temporizador que termina el worker con el código de salida `1` tras `timeout` milisegundos. Una nueva llamada sustituye al temporizador anterior, así que puedes volver a llamarlo para ampliar el límite mientras el worker está ocupado.\n\nExample: Limitar el worker a un minuto\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nHace fork de un script de /workers/ (la API antigua).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `/workers/`, sin `.js` |\n| `timeout` | `Number` | no |  | Mata el proceso tras estos milisegundos |\n| `args` | `Array` | no |  | Argumentos de línea de comandos para el script |\n\nReturns: `ChildProcess`\n\nEjecuta `/workers/{name}.js` con `child_process.fork()` en el directorio de la app y devuelve el `ChildProcess`. Los argumentos `args` y `--worker` se pasan al script. El proceso se guarda en `F.workers` hasta que termina. Cuando pasa `timeout` (más de 10 ms), el proceso se mata con `SIGKILL`.\n\n`timeout` se puede omitir: `WORKER(name, args)`. Un nombre que empieza por `@` apunta a un archivo de un paquete; un nombre que empieza por `#` devuelve un worker en ejecución de `F.workers` por su id. `NEWFORK()` es la alternativa más nueva.\n\nExample: Ejecutar un worker durante 10 segundos como máximo\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nEjecuta un script de /workers/ y devuelve su salida estándar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo en `/workers/`, sin `.js` |\n| `args` | `Array` | no |  | Argumentos de línea de comandos; el script los lee de `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Mata el proceso tras estos milisegundos |\n\nReturns: `ChildProcess`\n\nHace fork de `/workers/{name}.js` en silencio (como `WORKER()`), recoge todo lo que escribe en la salida estándar y llama a `callback(err, buffer)` cuando el proceso termina o falla. `args` puede ser un array o un solo valor. El orden de `callback` y `timeout` se puede intercambiar.\n\nExample: Leer la salida de un script\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nLos procesos en ejecución iniciados por WORKER().\n\nReturns: `Object`\n\nUn objeto con los procesos hijo que iniciaron `WORKER()` y `WORKER2()`, por su id (`{name}_{number}`). Un proceso se elimina cuando termina. Cuando la app se detiene, se matan todos.\n\n### PATH.workers([filename])\n\nType: `method`\n\nDevuelve la ruta a un archivo del directorio /workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nombre de archivo |\n\nReturns: `String`\n\nUne `directory_workers` (por defecto `/workers/`) con `filename` y devuelve la ruta completa.\n\nExample: Comprobar un archivo de worker\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue cuando el framework se ejecuta mediante LOAD() sin el servidor HTTP.\n\nReturns: `Boolean`\n\nLa variable global es `false` por defecto. `LOAD()` la pone a `true` y `HTTP()` la vuelve a poner a `false`. Úsala en código compartido que no debe hacer cosas que necesitan un servidor web (por ejemplo, iniciar planificadores) cuando se ejecuta en un worker.\n\nExample: Omitir un temporizador en los workers\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nCarga partes de la app sin iniciar el servidor HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | Las partes que cargar u omitir |\n| `cwd` | `String` | no |  | El directorio de la app |\n| `callback` | `Function` | no |  | Se llama cuando la app está cargada |\n\nReturns: `Promise` Solo cuando no se pasa `callback`\n\nÚsalo en archivos de worker y en scripts. Lee la configuración y `.env`, carga las partes indicadas en `types` y llama a `callback` (o resuelve la promesa devuelta) cuando están listas. Pone `isWORKER` a `true` y emite `load` y `ready`.\n\n`types` es un array o una cadena separada por comas o espacios, por ejemplo `'config,modules,schemas'`. Los nombres con el prefijo `no` (`'nobundles'`) excluyen una parte y cargan el resto. El valor por defecto es `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Añade `'debug'` para ejecutar en modo debug y `'service'` para ejecutar el temporizador `ON('service')`. Partes: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: Un worker con esquemas\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: Con await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nEjecuta un comando de shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | La línea de comandos |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | El directorio de trabajo |\n\nReturns: `Promise` Solo cuando no se pasa `callback`; se resuelve con stdout\n\nEjecuta `command` con `child_process.exec()`. El directorio de trabajo es `cwd` o el directorio de la app; la shell es `default_shell` cuando está definida. El callback recibe `(err, stdout, stderr)`. Sin callback la función devuelve una promesa que se resuelve con la salida estándar. Puedes pasar `cwd` como segundo argumento cuando usas la promesa.\n\nNunca pongas datos del usuario en `command` sin escaparlos.\n\nExample: Con un callback\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: Con await y un directorio\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nLa shell que usa SHELL().\n\nReturns: `String`\n\nLa ruta de la shell para `SHELL()` (la opción `shell` de `child_process.exec()`). Si no está definida, Node.js usa `/bin/sh` en Unix y `cmd.exe` en Windows.\n\nExample: En el archivo de configuración\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nEjecuta la app como un clúster de varias instancias.\n\nReturns: `Number|String`\n\nUna opción del script de inicio de `total4/release` y `total4/debug`. Un número inicia ese número de instancias de la app; `'auto'` inicia una y añade o elimina instancias según su tiempo de respuesta (consulta `options.cluster_limit`). El proceso master reinicia tras un segundo una instancia que termina. En modo debug el master reinicia todas las instancias cuando cambia un archivo.\n\nCuando `options.threads` está definido, el valor se aplica a cada hilo en lugar de a la app principal.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nEl número máximo de instancias en el clúster automático.\n\nReturns: `Number`\n\nCon `options.cluster = 'auto'`, el master hace ping a las instancias cada cinco segundos. Añade una instancia cuando la respuesta media supera 70 ms, hasta que el número llega a `cluster_limit`. Sin esta opción no hay límite. Cuando una instancia responde rápido, el master elimina la última instancia (como mucho cada 25 segundos) si tiene menos de dos peticiones pendientes.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nLa zona horaria de un clúster.\n\nReturns: `String`\n\nEn modo clúster el master establece `process.env.TZ` de todas las instancias a este valor. Si no lo defines, el clúster se ejecuta en `'utc'`, sea cual sea la zona horaria del servidor.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nEjecuta cada subdirectorio de /threads/ como una app separada.\n\nReturns: `String|Boolean`\n\nPara cada directorio de `/threads/` la app principal escribe un script de inicio `{script}_{name}.js` en la raíz y hace fork de él. Las peticiones bajo `{threads}/{name}/` se reenvían a ese hilo a través de un socket Unix, sin el prefijo. `true` significa sin prefijo (`/{name}/`).\n\nCada hilo carga los archivos `.js` de su directorio con `exports.install`, sus propios archivos de configuración y `.env`, `views/` y `public/`. Omite los directorios raíz `/controllers/` y `/middleware/`.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nEl nombre del hilo del proceso.\n\nReturns: `String`\n\nDefine la variable global `THREAD` y carga la app como el hilo `/threads/{name}/`. Los scripts que escribe `options.threads` la definen por ti. En modo clúster, el archivo de reinicio es `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nEscribe la salida de cada hilo en su propio archivo de log.\n\nReturns: `String`\n\nCon `'isolated'`, la salida de un hilo va a `/threads/{name}/logs/debug.log` en lugar de a la consola de la app principal. El archivo se vacía cuando el hilo se inicia (en modo debug solo en el primer inicio).\n\n### THREAD\n\nType: `property`\n\nEl nombre del hilo actual.\n\nReturns: `String`\n\nUna cadena vacía en una app normal. Dentro de un hilo de `/threads/{name}/` es el nombre del hilo. El framework lo añade al banner de la consola y a los logs de auditoría.\n\nExample: Usar el nombre del hilo\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nLos procesos hijo de los hilos, por nombre.\n\nReturns: `Object`\n\nEn la app principal con `options.threads`, un objeto donde cada clave es el nombre de un hilo y cada valor es su `ChildProcess`. En otro caso, `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue en una instancia de un clúster.\n\nReturns: `Boolean`\n\n`true` cuando el proceso es una instancia iniciada por el master del clúster.\n\nExample: Ejecutar un trabajo solo en una instancia\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nEl id de la instancia en un clúster.\n\nReturns: `String`\n\nEl índice de la instancia como cadena (`'0'`, `'1'`, ...), o `null` fuera de un clúster. Los archivos temporales de una instancia reciben el prefijo `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nLanza un evento en todas las instancias del clúster.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento |\n| `a` | `Object` | no |  | Hasta cinco argumentos |\n\nReturns: `Framework`\n\nEnvía el evento a través del master a todas las instancias, incluida la que lo envía. Cada instancia llama a sus listeners `ON(name)` con hasta cinco argumentos. Los argumentos viajan como mensajes IPC, así que deben ser serializables. Fuera de un clúster no hace nada.\n\nExample: Vaciar una caché en todas partes\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nEnvía un evento desde una instancia al proceso master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento |\n| `a` | `Object` | no |  | Hasta cinco argumentos |\n\nReturns: `Framework`\n\nEl master llama a los listeners registrados con `F.cluster.on(name)`. Fuera de un clúster no hace nada.\n\nExample: Informar al master\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nEscucha en el proceso master los eventos de F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del evento |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nRegístralo en el script de inicio: el master ejecuta ese script, y también cada instancia. El callback recibe los argumentos de `F.cluster.master()`. Registra un solo listener por nombre.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nReinicia instancias del clúster desde el proceso master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | El índice de la instancia |\n\nReinicia la instancia con `index`, o todas las instancias con dos segundos de diferencia cuando no se pasa `index`. Solo funciona en el proceso master. Desde fuera, crea en su lugar el archivo `restart`.\n\nExample: Reiniciar todas las instancias desde el script de inicio\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nInicia un clúster con un servidor HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Número de instancias o `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` o `'release'` |\n| `options` | `Object` | no |  | Opciones de inicio |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nEsto es lo que llama `options.cluster` en el script de inicio. `count` es un número, `'auto'` o `null` (una instancia por núcleo de CPU). `mode` es `'debug'` o `'release'`. `options` son las opciones de inicio que reciben las instancias. En el master, `callback` se llama con el array de instancias cuando todas se han iniciado. `F.cluster.https()` recibe los mismos argumentos e inicia servidores HTTPS.\n\nExample: Iniciar un clúster directamente\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nUn archivo que reinicia todas las instancias de un clúster en ejecución.\n\nEl master comprueba cada cinco segundos si hay un archivo llamado `restart` en el directorio de la app (`restart_{thread}` cuando `options.thread` está definido). Cuando lo encuentra, borra el archivo y reinicia todas las instancias con dos segundos de diferencia, como mucho una vez cada 30 segundos. Úsalo después de un despliegue para cargar código nuevo sin detener la app.\n\nEl master también escribe su estado (PID, versiones, número de instancias, memoria y estadísticas de cada instancia) en el nombre del script de inicio más `.json`, por ejemplo `index.js.json`, aproximadamente cada 50 segundos.\n\nExample: Reiniciar después de un despliegue\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSincroniza la caché del framework entre las instancias del clúster.\n\nReturns: `Boolean`\n\nCuando es `true`, cada `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` y `clear()` de una instancia se repite en las demás instancias. Las sesiones se sincronizan en un clúster sin esta opción.\n\nExample: En el archivo de configuración\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdvd6IR61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Workers, threads et cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() et l'API du cluster.","markdown":"---\ntitle: Workers, threads et cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Workers, threads et cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() et l'API du cluster.\n\nChaque fonction, propriété et option de démarrage pour les workers en arrière-plan, les threads, les commandes shell et le cluster. Le guide [Workers, threads et cluster](../../guides/workers-and-threads/) montre comment ils s'articulent.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nExécute un script de /workers/ comme thread worker_threads.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom du fichier dans `/workers/` sans `.js`, `@package` ou `~/absolute/path.js` ; omets-le dans un worker pour obtenir l'utilitaire |\n| `data` | `Object` | no |  | Données pour le thread (`workerData`) |\n\nReturns: `Worker` Le thread, ou l'utilitaire du worker lorsque `name` est vide\n\nDémarre `/workers/{name}.js` avec `new Worker()` du module `worker_threads` de Node.js et renvoie le `Worker`. `data` arrive dans le thread sous forme de `workerData` (le `worker.data` de l'utilitaire). L'objet renvoyé reçoit `kill()` et `exit()`, qui appellent `terminate()`.\n\nUn `name` qui commence par `@` désigne un fichier de paquet, un nom qui commence par `~` est un chemin absolu. Sans `name`, la fonction renvoie l'utilitaire côté worker (voir `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Démarrer un thread\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nExécute un script de /workers/ comme processus enfant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Le nom du fichier dans `/workers/` sans `.js`, `@package` ou `~/absolute/path.js` ; omets-le dans un worker pour obtenir l'utilitaire |\n\nReturns: `ChildProcess` Le processus enfant, ou l'utilitaire du worker lorsque `name` est vide\n\nDémarre `/workers/{name}.js` avec `child_process.fork()` dans le répertoire de l'application et renvoie le `ChildProcess`. L'objet reçoit `postMessage()` (alias de `send()`) et `terminate()` (envoie `SIGTERM`), il a donc les mêmes méthodes qu'un thread de `NEWTHREAD()`.\n\nLes règles de nommage sont les mêmes que pour `NEWTHREAD()`. Sans `name`, la fonction renvoie l'utilitaire côté worker.\n\nExample: Démarrer un fork\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nDémarre un nombre fixe de workers et les prête aux tâches.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `/workers/` sans `.js` |\n| `count` | `Number` | yes |  | Combien de workers démarrer |\n| `isfork` | `Boolean` | no | `false` | Utiliser des processus enfants au lieu de threads |\n\nReturns: `Object` Le pool avec `exec()`, `workers` et `pending`\n\nDémarre `count` workers de `/workers/{name}.js` avec `NEWTHREAD()`, ou avec `NEWFORK()` lorsque `isfork` vaut `true`, et renvoie un pool. Les tâches s'exécutent avec `pool.exec()`. Le pool est aussi stocké dans `F.workerspool[name]`.\n\nExample: Un pool de quatre threads\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: Un pool de processus enfants\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nExécute une tâche sur le prochain worker libre d'un pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Uniquement si `fn` n'est pas fourni ; résolue avec le worker\n\nLorsqu'un worker est libre, le pool supprime ses écouteurs `message` et appelle `fn(worker, release)` ; dans `fn`, `this` est aussi le worker. Appelle `release()` quand la tâche est terminée pour que le worker puisse prendre la suivante. Les tâches attendent dans `pool.pending` tant que tous les workers sont occupés.\n\nSans `fn`, la méthode renvoie une promesse résolue avec le worker libre. Appelle `worker.release()` quand tu as terminé.\n\nExample: Avec un callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: Avec await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nLes workers d'un pool.\n\nReturns: `Array`\n\nUn tableau des objets `Worker` ou `ChildProcess` que le pool a démarrés. `pool.pending` est le tableau des tâches qui attendent un worker libre.\n\n### F.workerspool\n\nType: `property`\n\nLes pools créés par NEWTHREADPOOL(), par nom.\n\nReturns: `Object`\n\nUn objet dont chaque clé est le `name` passé à `NEWTHREADPOOL()` et chaque valeur est le pool. Utilise-le pour obtenir un pool dans un autre fichier.\n\nExample: Utiliser un pool depuis un autre fichier\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nLes données que le parent a passées à NEWTHREAD().\n\nReturns: `Object`\n\nDans un fichier worker, `NEWTHREAD()` ou `NEWFORK()` sans arguments renvoie l'utilitaire du worker. `worker.data` est l'argument `data` de `NEWTHREAD(name, data)`. Dans un processus enfant, c'est un objet vide ; envoie plutôt les données par un message.\n\nExample: Dans /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nReçoit les messages que le parent envoie au worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Le message du parent |\n\nAssigne une fonction à l'utilitaire renvoyé par `NEWTHREAD()` ou `NEWFORK()` sans arguments. Elle est appelée pour chaque message du parent, dans un thread comme dans un processus enfant.\n\nExample: Répondre à chaque message\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nEnvoie un message du worker au parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Une valeur sérialisable |\n\nUtilise `parentPort.postMessage()` dans un thread et `process.send()` dans un processus enfant. `worker.postMessage()` est la même méthode. Le parent reçoit le message dans `on('message')` de l'objet renvoyé par `NEWTHREAD()` ou `NEWFORK()`.\n\nExample: Signaler la progression\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nTermine le worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | Le code de sortie |\n\nAppelle `process.exit(code)`. `worker.kill()` et `worker.close()` sont la même méthode.\n\nExample: Terminer après la réponse\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nTermine le worker après un délai.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisecondes |\n\nDémarre un minuteur qui termine le worker avec le code de sortie `1` après `timeout` millisecondes. Un nouvel appel remplace le minuteur précédent, tu peux donc l'appeler à nouveau pour prolonger le délai pendant que le worker est occupé.\n\nExample: Limiter le worker à une minute\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nForke un script de /workers/ (l'ancienne API).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `/workers/`, sans `.js` |\n| `timeout` | `Number` | no |  | Tue le processus après ce nombre de millisecondes |\n| `args` | `Array` | no |  | Arguments de ligne de commande pour le script |\n\nReturns: `ChildProcess`\n\nExécute `/workers/{name}.js` avec `child_process.fork()` dans le répertoire de l'application et renvoie le `ChildProcess`. Les arguments `args` et `--worker` sont passés au script. Le processus est stocké dans `F.workers` jusqu'à sa fin. Lorsque `timeout` (plus de 10 ms) est écoulé, le processus est tué avec `SIGKILL`.\n\n`timeout` peut être omis : `WORKER(name, args)`. Un nom qui commence par `@` désigne un fichier de paquet ; un nom qui commence par `#` renvoie un worker en cours d'exécution de `F.workers` par son id. `NEWFORK()` est l'alternative plus récente.\n\nExample: Exécuter un worker pendant 10 secondes au maximum\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nExécute un script de /workers/ et renvoie sa sortie standard.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier dans `/workers/`, sans `.js` |\n| `args` | `Array` | no |  | Arguments de ligne de commande ; le script les lit depuis `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Tue le processus après ce nombre de millisecondes |\n\nReturns: `ChildProcess`\n\nForke `/workers/{name}.js` silencieusement (comme `WORKER()`), collecte tout ce qu'il écrit sur la sortie standard et appelle `callback(err, buffer)` lorsque le processus se termine ou échoue. `args` peut être un tableau ou une seule valeur. L'ordre de `callback` et `timeout` peut être inversé.\n\nExample: Lire la sortie d'un script\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nLes processus en cours démarrés par WORKER().\n\nReturns: `Object`\n\nUn objet des processus enfants que `WORKER()` et `WORKER2()` ont démarrés, par leur id (`{name}_{number}`). Un processus est retiré lorsqu'il se termine. Lorsque l'application s'arrête, ils sont tous tués.\n\n### PATH.workers([filename])\n\nType: `method`\n\nRenvoie le chemin d'un fichier du répertoire /workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nom de fichier |\n\nReturns: `String`\n\nJoint `directory_workers` (par défaut `/workers/`) à `filename` et renvoie le chemin complet.\n\nExample: Vérifier un fichier worker\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue lorsque le framework s'exécute via LOAD() sans le serveur HTTP.\n\nReturns: `Boolean`\n\nCette variable globale vaut `false` par défaut. `LOAD()` la met à `true`, et `HTTP()` la remet à `false`. Utilise-la dans du code partagé qui ne doit pas faire de choses nécessitant un serveur web (par exemple démarrer des planificateurs) lorsqu'il s'exécute dans un worker.\n\nExample: Ignorer un minuteur dans les workers\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nCharge des parties de l'application sans démarrer le serveur HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | Les parties à charger ou à ignorer |\n| `cwd` | `String` | no |  | Le répertoire de l'application |\n| `callback` | `Function` | no |  | Appelé lorsque l'application est chargée |\n\nReturns: `Promise` Uniquement si `callback` n'est pas fourni\n\nUtilise-la dans les fichiers workers et les scripts. Elle lit la configuration et `.env`, charge les parties nommées dans `types` et appelle `callback` (ou résout la promesse renvoyée) lorsqu'elles sont prêtes. Elle met `isWORKER` à `true` et émet `load` et `ready`.\n\n`types` est un tableau ou une chaîne séparée par des virgules ou des espaces, par exemple `'config,modules,schemas'`. Les noms avec le préfixe `no` (`'nobundles'`) excluent une partie et chargent le reste. La valeur par défaut est `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Ajoute `'debug'` pour exécuter en mode debug et `'service'` pour exécuter le minuteur `ON('service')`. Parties : `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: Un worker avec des schémas\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: Avec await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nExécute une commande shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | La ligne de commande |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | Le répertoire de travail |\n\nReturns: `Promise` Uniquement si `callback` n'est pas fourni ; résolue avec stdout\n\nExécute `command` avec `child_process.exec()`. Le répertoire de travail est `cwd` ou le répertoire de l'application ; le shell est `default_shell` lorsqu'il est défini. Le callback reçoit `(err, stdout, stderr)`. Sans callback, la fonction renvoie une promesse résolue avec la sortie standard. Tu peux passer `cwd` comme deuxième argument lorsque tu utilises la promesse.\n\nNe mets jamais une saisie utilisateur dans `command` sans l'échapper.\n\nExample: Avec un callback\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: Avec await et un répertoire\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nLe shell qu'utilise SHELL().\n\nReturns: `String`\n\nLe chemin du shell pour `SHELL()` (l'option `shell` de `child_process.exec()`). Lorsqu'il n'est pas défini, Node.js utilise `/bin/sh` sous Unix et `cmd.exe` sous Windows.\n\nExample: Dans le fichier de configuration\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nExécute l'application comme un cluster de plusieurs instances.\n\nReturns: `Number|String`\n\nUne option du script de démarrage de `total4/release` et `total4/debug`. Un nombre démarre autant d'instances de l'application ; `'auto'` en démarre une et ajoute ou retire des instances selon leur temps de réponse (voir `options.cluster_limit`). Le processus master redémarre une instance qui se termine après une seconde. En mode debug, le master redémarre toutes les instances lorsqu'un fichier change.\n\nLorsque `options.threads` est défini, la valeur s'applique à chaque thread au lieu de l'application principale.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nLe nombre maximal d'instances du cluster automatique.\n\nReturns: `Number`\n\nAvec `options.cluster = 'auto'`, le master interroge les instances toutes les cinq secondes. Il ajoute une instance lorsque la réponse moyenne dépasse 70 ms, jusqu'à ce que le nombre atteigne `cluster_limit`. Sans cette option, il n'y a pas de limite. Lorsqu'une instance répond rapidement, le master retire la dernière instance (au plus toutes les 25 secondes) si elle a moins de deux requêtes en attente.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nLe fuseau horaire d'un cluster.\n\nReturns: `String`\n\nEn mode cluster, le master règle `process.env.TZ` de toutes les instances sur cette valeur. Si tu ne la définis pas, le cluster s'exécute en `'utc'`, quel que soit le fuseau horaire du serveur.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nExécute chaque sous-répertoire de /threads/ comme une application séparée.\n\nReturns: `String|Boolean`\n\nPour chaque répertoire de `/threads/`, l'application principale écrit un script de démarrage `{script}_{name}.js` à la racine et le forke. Les requêtes sous `{threads}/{name}/` sont transmises à ce thread via un socket Unix, sans le préfixe. `true` signifie aucun préfixe (`/{name}/`).\n\nChaque thread charge les fichiers `.js` de son répertoire avec `exports.install`, ses propres fichiers de configuration et `.env`, `views/` et `public/`. Il ignore les répertoires racine `/controllers/` et `/middleware/`.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nLe nom de thread du processus.\n\nReturns: `String`\n\nDéfinit la variable globale `THREAD` et charge l'application comme le thread `/threads/{name}/`. Les scripts écrits par `options.threads` la définissent pour toi. En mode cluster, le fichier de redémarrage est `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nÉcrit la sortie de chaque thread dans son propre fichier de log.\n\nReturns: `String`\n\nAvec `'isolated'`, la sortie d'un thread va dans `/threads/{name}/logs/debug.log` au lieu de la console de l'application principale. Le fichier est vidé au démarrage du thread (en mode debug, uniquement au premier démarrage).\n\n### THREAD\n\nType: `property`\n\nLe nom du thread courant.\n\nReturns: `String`\n\nUne chaîne vide dans une application normale. Dans un thread de `/threads/{name}/`, c'est le nom du thread. Le framework l'ajoute à la bannière de la console et aux logs d'audit.\n\nExample: Utiliser le nom du thread\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nLes processus enfants des threads, par nom.\n\nReturns: `Object`\n\nDans l'application principale avec `options.threads`, un objet dont chaque clé est un nom de thread et chaque valeur son `ChildProcess`. Sinon `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue dans une instance d'un cluster.\n\nReturns: `Boolean`\n\n`true` lorsque le processus est une instance démarrée par le master du cluster.\n\nExample: Exécuter une tâche dans une seule instance\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nL'id de l'instance dans un cluster.\n\nReturns: `String`\n\nL'index de l'instance sous forme de chaîne (`'0'`, `'1'`, ...), ou `null` hors d'un cluster. Les fichiers temporaires d'une instance reçoivent le préfixe `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nDéclenche un événement dans chaque instance du cluster.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement |\n| `a` | `Object` | no |  | Jusqu'à cinq arguments |\n\nReturns: `Framework`\n\nEnvoie l'événement via le master à toutes les instances, y compris l'émettrice. Chaque instance appelle ses écouteurs `ON(name)` avec jusqu'à cinq arguments. Les arguments transitent sous forme de messages IPC, ils doivent donc être sérialisables. Hors d'un cluster, elle ne fait rien.\n\nExample: Vider un cache partout\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nEnvoie un événement d'une instance au processus master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement |\n| `a` | `Object` | no |  | Jusqu'à cinq arguments |\n\nReturns: `Framework`\n\nLe master appelle les écouteurs enregistrés avec `F.cluster.on(name)`. Hors d'un cluster, elle ne fait rien.\n\nExample: Informer le master\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nÉcoute dans le processus master les événements de F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'événement |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nEnregistre-le dans le script de démarrage : le master exécute ce script, et chaque instance aussi. Le callback reçoit les arguments de `F.cluster.master()`. N'enregistre qu'un seul écouteur par nom.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nRedémarre des instances du cluster depuis le processus master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | L'index de l'instance |\n\nRedémarre l'instance d'index `index`, ou toutes les instances à deux secondes d'intervalle lorsque `index` n'est pas fourni. Cela ne fonctionne que dans le processus master. Depuis l'extérieur, crée plutôt le fichier `restart`.\n\nExample: Redémarrer toutes les instances depuis le script de démarrage\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nDémarre un cluster avec un serveur HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Nombre d'instances ou `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` ou `'release'` |\n| `options` | `Object` | no |  | Options de démarrage |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nC'est ce qu'appelle `options.cluster` dans le script de démarrage. `count` est un nombre, `'auto'` ou `null` (une instance par cœur CPU). `mode` vaut `'debug'` ou `'release'`. `options` sont les options de démarrage que reçoivent les instances. Dans le master, `callback` est appelé avec le tableau des instances une fois qu'elles ont toutes démarré. `F.cluster.https()` prend les mêmes arguments et démarre des serveurs HTTPS.\n\nExample: Démarrer un cluster directement\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nUn fichier qui redémarre toutes les instances d'un cluster en cours d'exécution.\n\nLe master vérifie toutes les cinq secondes la présence d'un fichier nommé `restart` dans le répertoire de l'application (`restart_{thread}` lorsque `options.thread` est défini). Lorsqu'il le trouve, il supprime le fichier et redémarre toutes les instances à deux secondes d'intervalle, au plus une fois toutes les 30 secondes. Utilise-le après un déploiement pour charger le nouveau code sans arrêter l'application.\n\nLe master écrit aussi son état (PID, versions, nombre d'instances, mémoire et statistiques de chaque instance) dans le nom du script de démarrage suivi de `.json`, par exemple `index.js.json`, environ toutes les 50 secondes.\n\nExample: Redémarrer après un déploiement\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSynchronise le cache du framework entre les instances du cluster.\n\nReturns: `Boolean`\n\nLorsque `true`, chaque `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` et `clear()` dans une instance est répété dans les autres instances. Les sessions sont synchronisées dans un cluster sans cette option.\n\nExample: Dans le fichier de configuration\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdvd6IR61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Worker, thread e cluster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() e l'API del cluster.","markdown":"---\ntitle: Worker, thread e cluster\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Worker, thread e cluster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() e l'API del cluster.\n\nTutte le funzioni, le proprietà e le opzioni di avvio per worker in background, thread, comandi shell e cluster. La guida [Worker, thread e cluster](../../guides/workers-and-threads/) mostra come si combinano tra loro.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nEsegue uno script da /workers/ come thread worker_threads.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome del file in `/workers/` senza `.js`, `@package` o `~/absolute/path.js`; omettilo all'interno di un worker per ottenere l'helper |\n| `data` | `Object` | no |  | Dati per il thread (`workerData`) |\n\nReturns: `Worker` Il thread, oppure l'helper del worker quando `name` è vuoto\n\nAvvia `/workers/{name}.js` con `new Worker()` del modulo `worker_threads` di Node.js e restituisce il `Worker`. `data` arriva al thread come `workerData` (il `worker.data` dell'helper). L'oggetto restituito ha `kill()` ed `exit()`, che chiamano `terminate()`.\n\nUn `name` che inizia con `@` punta a un file di un pacchetto, uno che inizia con `~` è un percorso assoluto. Senza `name`, la funzione restituisce l'helper lato worker (vedi `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Avviare un thread\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nEsegue uno script da /workers/ come processo figlio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Il nome del file in `/workers/` senza `.js`, `@package` o `~/absolute/path.js`; omettilo all'interno di un worker per ottenere l'helper |\n\nReturns: `ChildProcess` Il processo figlio, oppure l'helper del worker quando `name` è vuoto\n\nAvvia `/workers/{name}.js` con `child_process.fork()` nella directory dell'app e restituisce il `ChildProcess`. L'oggetto ha `postMessage()` (alias di `send()`) e `terminate()` (invia `SIGTERM`), quindi ha gli stessi metodi di un thread di `NEWTHREAD()`.\n\nLe regole per il nome sono le stesse di `NEWTHREAD()`. Senza `name`, la funzione restituisce l'helper lato worker.\n\nExample: Avviare un fork\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nAvvia un numero fisso di worker e li presta ai job.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `/workers/` senza `.js` |\n| `count` | `Number` | yes |  | Quanti worker avviare |\n| `isfork` | `Boolean` | no | `false` | Usa processi figli invece dei thread |\n\nReturns: `Object` Il pool con `exec()`, `workers` e `pending`\n\nAvvia `count` worker di `/workers/{name}.js` con `NEWTHREAD()`, oppure con `NEWFORK()` quando `isfork` è `true`, e restituisce un pool. I job si eseguono con `pool.exec()`. Il pool viene anche memorizzato in `F.workerspool[name]`.\n\nExample: Un pool di quattro thread\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: Un pool di processi figli\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nEsegue un job sul prossimo worker libero di un pool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Solo quando `fn` non è indicato; si risolve con il worker\n\nQuando un worker è libero, il pool rimuove i suoi listener `message` e chiama `fn(worker, release)`; all'interno di `fn`, anche `this` è il worker. Chiama `release()` quando il job è terminato, così il worker può prendere il job successivo. I job attendono in `pool.pending` mentre tutti i worker sono occupati.\n\nSenza `fn` il metodo restituisce una promise che si risolve con il worker libero. Chiama `worker.release()` quando hai finito.\n\nExample: Con una callback\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: Con await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nI worker di un pool.\n\nReturns: `Array`\n\nUn array degli oggetti `Worker` o `ChildProcess` avviati dal pool. `pool.pending` è l'array dei job che attendono un worker libero.\n\n### F.workerspool\n\nType: `property`\n\nI pool creati da NEWTHREADPOOL(), per nome.\n\nReturns: `Object`\n\nUn oggetto in cui ogni chiave è il `name` passato a `NEWTHREADPOOL()` e ogni valore è il pool. Usalo per ottenere un pool in un altro file.\n\nExample: Usare un pool da un altro file\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nI dati che il processo padre ha passato a NEWTHREAD().\n\nReturns: `Object`\n\nIn un file worker, `NEWTHREAD()` o `NEWFORK()` senza argomenti restituisce l'helper del worker. `worker.data` è l'argomento `data` di `NEWTHREAD(name, data)`. In un processo figlio è un oggetto vuoto; invia invece i dati con un messaggio.\n\nExample: In /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nRiceve i messaggi che il processo padre invia al worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Il messaggio del processo padre |\n\nAssegna una funzione all'helper restituito da `NEWTHREAD()` o `NEWFORK()` senza argomenti. Viene chiamata per ogni messaggio del processo padre, sia in un thread sia in un processo figlio.\n\nExample: Rispondere a ogni messaggio\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nInvia un messaggio dal worker al processo padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Un valore serializzabile |\n\nUsa `parentPort.postMessage()` in un thread e `process.send()` in un processo figlio. `worker.postMessage()` è lo stesso metodo. Il processo padre riceve il messaggio in `on('message')` dell'oggetto restituito da `NEWTHREAD()` o `NEWFORK()`.\n\nExample: Comunicare l'avanzamento\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nTermina il worker.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | Il codice di uscita |\n\nChiama `process.exit(code)`. `worker.kill()` e `worker.close()` sono lo stesso metodo.\n\nExample: Terminare dopo la risposta\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nTermina il worker dopo un limite di tempo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Millisecondi |\n\nAvvia un timer che termina il worker con codice di uscita `1` dopo `timeout` millisecondi. Una nuova chiamata sostituisce il timer precedente, quindi puoi richiamarlo per estendere il limite mentre il worker è occupato.\n\nExample: Limitare il worker a un minuto\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nEsegue il fork di uno script da /workers/ (la vecchia API).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `/workers/`, senza `.js` |\n| `timeout` | `Number` | no |  | Termina il processo dopo questo numero di millisecondi |\n| `args` | `Array` | no |  | Argomenti da riga di comando per lo script |\n\nReturns: `ChildProcess`\n\nEsegue `/workers/{name}.js` con `child_process.fork()` nella directory dell'app e restituisce il `ChildProcess`. Gli argomenti `args` e `--worker` vengono passati allo script. Il processo è memorizzato in `F.workers` finché non termina. Quando scade `timeout` (più di 10 ms), il processo viene terminato con `SIGKILL`.\n\n`timeout` può essere omesso: `WORKER(name, args)`. Un nome che inizia con `@` punta a un file di un pacchetto; un nome che inizia con `#` restituisce un worker in esecuzione da `F.workers` tramite il suo id. `NEWFORK()` è l'alternativa più recente.\n\nExample: Eseguire un worker per al massimo 10 secondi\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nEsegue uno script da /workers/ e restituisce il suo standard output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file in `/workers/`, senza `.js` |\n| `args` | `Array` | no |  | Argomenti da riga di comando; lo script li legge da `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Termina il processo dopo questo numero di millisecondi |\n\nReturns: `ChildProcess`\n\nEsegue il fork di `/workers/{name}.js` in modo silenzioso (come `WORKER()`), raccoglie tutto ciò che scrive sullo standard output e chiama `callback(err, buffer)` quando il processo termina o fallisce. `args` può essere un array o un singolo valore. L'ordine di `callback` e `timeout` può essere invertito.\n\nExample: Leggere l'output di uno script\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nI processi in esecuzione avviati da WORKER().\n\nReturns: `Object`\n\nUn oggetto dei processi figli avviati da `WORKER()` e `WORKER2()`, indicizzati per id (`{name}_{number}`). Un processo viene rimosso quando termina. Quando l'app si ferma, vengono terminati tutti.\n\n### PATH.workers([filename])\n\nType: `method`\n\nRestituisce il percorso di un file nella directory /workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Un nome di file |\n\nReturns: `String`\n\nUnisce `directory_workers` (predefinito `/workers/`) con `filename` e restituisce il percorso completo.\n\nExample: Verificare un file worker\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue quando il framework gira tramite LOAD() senza il server HTTP.\n\nReturns: `Boolean`\n\nLa variabile globale è `false` per impostazione predefinita. `LOAD()` la imposta a `true` e `HTTP()` la riporta a `false`. Usala nel codice condiviso che, quando gira in un worker, non deve fare cose che richiedono un server web (per esempio avviare scheduler).\n\nExample: Saltare un timer nei worker\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nCarica parti dell'app senza avviare il server HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | Le parti da caricare o da saltare |\n| `cwd` | `String` | no |  | La directory dell'app |\n| `callback` | `Function` | no |  | Chiamata quando l'app è caricata |\n\nReturns: `Promise` Solo quando `callback` non è indicata\n\nUsala nei file worker e negli script. Legge la configurazione e `.env`, carica le parti indicate in `types` e chiama `callback` (o risolve la promise restituita) quando sono pronte. Imposta `isWORKER` a `true` ed emette `load` e `ready`.\n\n`types` è un array o una stringa separata da virgole o spazi, per esempio `'config,modules,schemas'`. I nomi con il prefisso `no` (`'nobundles'`) escludono una parte e caricano il resto. Il valore predefinito è `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Aggiungi `'debug'` per girare in modalità debug e `'service'` per eseguire il timer `ON('service')`. Parti: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: Un worker con schemi\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: Con await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nEsegue un comando shell.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | La riga di comando |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | La directory di lavoro |\n\nReturns: `Promise` Solo quando `callback` non è indicata; si risolve con stdout\n\nEsegue `command` con `child_process.exec()`. La directory di lavoro è `cwd` o la directory dell'app; la shell è `default_shell` quando è impostata. La callback riceve `(err, stdout, stderr)`. Senza callback la funzione restituisce una promise che si risolve con lo standard output. Quando usi la promise puoi passare `cwd` come secondo argomento.\n\nNon inserire mai input dell'utente in `command` senza farne l'escape.\n\nExample: Con una callback\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: Con await e una directory\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nLa shell usata da SHELL().\n\nReturns: `String`\n\nIl percorso della shell per `SHELL()` (l'opzione `shell` di `child_process.exec()`). Quando non è impostata, Node.js usa `/bin/sh` su Unix e `cmd.exe` su Windows.\n\nExample: Nel file di configurazione\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nEsegue l'app come cluster di più istanze.\n\nReturns: `Number|String`\n\nUn'opzione dello script di avvio di `total4/release` e `total4/debug`. Un numero avvia altrettante istanze dell'app; `'auto'` ne avvia una e aggiunge o rimuove istanze in base al loro tempo di risposta (vedi `options.cluster_limit`). Il processo master riavvia dopo un secondo un'istanza che termina. In modalità debug il master riavvia tutte le istanze quando un file cambia.\n\nQuando `options.threads` è impostato, il valore si applica a ogni thread invece che all'app principale.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nIl numero massimo di istanze nel cluster automatico.\n\nReturns: `Number`\n\nCon `options.cluster = 'auto'`, il master interroga le istanze ogni cinque secondi. Aggiunge un'istanza quando la risposta media supera i 70 ms, finché il numero non raggiunge `cluster_limit`. Senza questa opzione non c'è limite. Quando un'istanza risponde velocemente, il master rimuove l'ultima istanza (al massimo ogni 25 secondi) se ha meno di due richieste in sospeso.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nIl fuso orario di un cluster.\n\nReturns: `String`\n\nIn modalità cluster il master imposta `process.env.TZ` di tutte le istanze su questo valore. Se non lo imposti, il cluster gira in `'utc'`, qualunque sia il fuso orario del server.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nEsegue ogni sottodirectory di /threads/ come app separata.\n\nReturns: `String|Boolean`\n\nPer ogni directory in `/threads/` l'app principale scrive uno script di avvio `{script}_{name}.js` nella radice e ne esegue il fork. Le richieste sotto `{threads}/{name}/` vengono inoltrate a quel thread tramite un socket Unix, senza il prefisso. `true` significa nessun prefisso (`/{name}/`).\n\nOgni thread carica i file `.js` della sua directory con `exports.install`, i propri file di configurazione e `.env`, `views/` e `public/`. Salta le directory `/controllers/` e `/middleware/` della radice.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nIl nome del thread del processo.\n\nReturns: `String`\n\nImposta la variabile globale `THREAD` e carica l'app come thread `/threads/{name}/`. Gli script scritti da `options.threads` la impostano per te. In modalità cluster, il file di riavvio è `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nScrive l'output di ogni thread nel proprio file di log.\n\nReturns: `String`\n\nCon `'isolated'`, l'output di un thread va in `/threads/{name}/logs/debug.log` invece che nella console dell'app principale. Il file viene svuotato all'avvio del thread (in modalità debug solo al primo avvio).\n\n### THREAD\n\nType: `property`\n\nIl nome del thread corrente.\n\nReturns: `String`\n\nUna stringa vuota in un'app normale. All'interno di un thread di `/threads/{name}/` è il nome del thread. Il framework lo aggiunge al banner della console e ai log di audit.\n\nExample: Usare il nome del thread\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nI processi figli dei thread, per nome.\n\nReturns: `Object`\n\nNell'app principale con `options.threads`, un oggetto in cui ogni chiave è il nome di un thread e ogni valore è il suo `ChildProcess`. Altrimenti `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue in un'istanza di un cluster.\n\nReturns: `Boolean`\n\n`true` quando il processo è un'istanza avviata dal master del cluster.\n\nExample: Eseguire un job in una sola istanza\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nL'id dell'istanza in un cluster.\n\nReturns: `String`\n\nL'indice dell'istanza come stringa (`'0'`, `'1'`, ...), oppure `null` fuori da un cluster. I file temporanei di un'istanza ricevono il prefisso `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nGenera un evento in ogni istanza del cluster.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento |\n| `a` | `Object` | no |  | Fino a cinque argomenti |\n\nReturns: `Framework`\n\nInvia l'evento tramite il master a tutte le istanze, incluso il mittente. Ogni istanza chiama i suoi listener `ON(name)` con un massimo di cinque argomenti. Gli argomenti viaggiano come messaggi IPC, quindi devono essere serializzabili. Fuori da un cluster non fa nulla.\n\nExample: Svuotare una cache ovunque\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nInvia un evento da un'istanza al processo master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento |\n| `a` | `Object` | no |  | Fino a cinque argomenti |\n\nReturns: `Framework`\n\nIl master chiama i listener registrati con `F.cluster.on(name)`. Fuori da un cluster non fa nulla.\n\nExample: Comunicare al master\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nAscolta nel processo master gli eventi di F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'evento |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nRegistralo nello script di avvio: il master esegue quello script, e lo stesso fa ogni istanza. La callback riceve gli argomenti di `F.cluster.master()`. Registra un solo listener per nome.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nRiavvia le istanze del cluster dal processo master.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | L'indice dell'istanza |\n\nRiavvia l'istanza con `index`, oppure tutte le istanze a due secondi di distanza quando `index` non è indicato. Funziona solo nel processo master. Dall'esterno, crea invece il file `restart`.\n\nExample: Riavviare tutte le istanze dallo script di avvio\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nAvvia un cluster con un server HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Numero di istanze o `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` o `'release'` |\n| `options` | `Object` | no |  | Opzioni di avvio |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nÈ ciò che `options.cluster` chiama nello script di avvio. `count` è un numero, `'auto'` o `null` (un'istanza per core della CPU). `mode` è `'debug'` o `'release'`. `options` sono le opzioni di avvio che ricevono le istanze. Nel master, `callback` viene chiamata con l'array delle istanze quando sono state avviate tutte. `F.cluster.https()` accetta gli stessi argomenti e avvia server HTTPS.\n\nExample: Avviare direttamente un cluster\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nUn file che riavvia tutte le istanze di un cluster in esecuzione.\n\nIl master controlla ogni cinque secondi se esiste un file chiamato `restart` nella directory dell'app (`restart_{thread}` quando `options.thread` è impostato). Quando lo trova, elimina il file e riavvia tutte le istanze a due secondi di distanza, al massimo una volta ogni 30 secondi. Usalo dopo un deploy per caricare il nuovo codice senza fermare l'app.\n\nIl master scrive anche il suo stato (PID, versioni, numero di istanze, memoria e statistiche di ogni istanza) in un file con il nome dello script di avvio più `.json`, per esempio `index.js.json`, circa ogni 50 secondi.\n\nExample: Riavviare dopo un deploy\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSincronizza la cache del framework tra le istanze del cluster.\n\nReturns: `Boolean`\n\nQuando è `true`, ogni `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` e `clear()` in un'istanza viene ripetuto nelle altre istanze. In un cluster le sessioni sono sincronizzate anche senza questa opzione.\n\nExample: Nel file di configurazione\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabdvd6IR61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/workers-and-threads/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Workery, vlákna a klaster","summary":"NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() a API klastra.","markdown":"---\ntitle: \"Workery, vlákna a klaster\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/workers-and-threads/\nupdated: 2026-11-16T15:41:05.817Z\n---\n\n# Workery, vlákna a klaster\n\n> NEWTHREAD(), NEWFORK(), NEWTHREADPOOL(), WORKER(), SHELL(), LOAD() a API klastra.\n\nKaždá funkcia, vlastnosť a štartovacia možnosť pre workery na pozadí, vlákna, príkazy shellu a klaster. Príručka [Workery, vlákna a klaster](../../guides/workers-and-threads/) ukazuje, ako do seba zapadajú.\n\n## API\n\n### NEWTHREAD(name, [data])\n\nType: `method`\n\nSpustí skript z /workers/ ako vlákno worker_threads.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov súboru v `/workers/` bez `.js`, `@package` alebo `~/absolute/path.js`; vo workeri ho vynechaj, aby si dostal pomocný objekt |\n| `data` | `Object` | no |  | Dáta pre vlákno (`workerData`) |\n\nReturns: `Worker` Vlákno alebo pomocný objekt workera, keď je `name` prázdny\n\nSpustí `/workers/{name}.js` cez `new Worker()` z modulu Node.js `worker_threads` a vráti `Worker`. `data` sa do vlákna dostanú ako `workerData` (v pomocnom objekte `worker.data`). Vrátený objekt dostane `kill()` a `exit()`, ktoré volajú `terminate()`.\n\n`name`, ktorý začína `@`, odkazuje na súbor balíka, ten, ktorý začína `~`, je absolútna cesta. Bez `name` funkcia vráti pomocný objekt na strane workera (pozri `worker.data`, `worker.message`, `worker.send()`).\n\nExample: Spustenie vlákna\n```js\nvar worker = NEWTHREAD('hash', { rounds: 10 });\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n\tworker.kill();\n});\nworker.postMessage('secret');\n```\n\n### NEWFORK(name)\n\nType: `method`\n\nSpustí skript z /workers/ ako podproces.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Názov súboru v `/workers/` bez `.js`, `@package` alebo `~/absolute/path.js`; vo workeri ho vynechaj, aby si dostal pomocný objekt |\n\nReturns: `ChildProcess` Podproces alebo pomocný objekt workera, keď je `name` prázdny\n\nSpustí `/workers/{name}.js` cez `child_process.fork()` v adresári aplikácie a vráti `ChildProcess`. Objekt dostane `postMessage()` (alias `send()`) a `terminate()` (pošle `SIGTERM`), takže má rovnaké metódy ako vlákno z `NEWTHREAD()`.\n\nPravidlá pre názov sú rovnaké ako pri `NEWTHREAD()`. Bez `name` funkcia vráti pomocný objekt na strane workera.\n\nExample: Spustenie forku\n```js\nvar fork = NEWFORK('import');\nfork.on('message', function(msg) {\n\tconsole.log('Imported', msg.count);\n\tfork.terminate();\n});\nfork.postMessage({ filename: PATH.databases('import.csv') });\n```\n\n### NEWTHREADPOOL(name, count, [isfork])\n\nType: `method`\n\nSpustí pevný počet workerov a požičiava ich úlohám.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru v `/workers/` bez `.js` |\n| `count` | `Number` | yes |  | Koľko workerov sa má spustiť |\n| `isfork` | `Boolean` | no | `false` | Použiť podprocesy namiesto vlákien |\n\nReturns: `Object` Pool s `exec()`, `workers` a `pending`\n\nSpustí `count` workerov z `/workers/{name}.js` cez `NEWTHREAD()` alebo cez `NEWFORK()`, keď je `isfork` `true`, a vráti pool. Úlohy sa spúšťajú cez `pool.exec()`. Pool sa uloží aj do `F.workerspool[name]`.\n\nExample: Pool štyroch vlákien\n```js\nvar pool = NEWTHREADPOOL('resize', 4);\n```\n\nExample: Pool podprocesov\n```js\nvar pool = NEWTHREADPOOL('pdf', 2, true);\n```\n\n### pool.exec([fn])\n\nType: `method`\n\nSpustí úlohu na ďalšom voľnom workeri poolu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | no |  | `function(worker, release)` |\n\nReturns: `Promise` Len keď `fn` nie je zadané; vyrieši sa workerom\n\nKeď je worker voľný, pool odstráni jeho poslucháčov `message` a zavolá `fn(worker, release)`; vo vnútri `fn` je `this` tiež worker. Keď je úloha hotová, zavolaj `release()`, aby worker mohol prevziať ďalšiu úlohu. Kým sú všetci workeri obsadení, úlohy čakajú v `pool.pending`.\n\nBez `fn` metóda vráti promise, ktorý sa vyrieši voľným workerom. Keď skončíš, zavolaj `worker.release()`.\n\nExample: S callbackom\n```js\npool.exec(function(worker, release) {\n\tworker.on('message', function(msg) {\n\t\trelease();\n\t\tconsole.log(msg);\n\t});\n\tworker.postMessage({ id: 1 });\n});\n```\n\nExample: S await\n```js\nvar worker = await pool.exec();\nworker.on('message', function(msg) {\n\tworker.release();\n\tconsole.log(msg);\n});\nworker.postMessage({ id: 2 });\n```\n\n### pool.workers\n\nType: `property`\n\nWorkeri poolu.\n\nReturns: `Array`\n\nPole objektov `Worker` alebo `ChildProcess`, ktoré pool spustil. `pool.pending` je pole úloh, ktoré čakajú na voľného workera.\n\n### F.workerspool\n\nType: `property`\n\nPooly vytvorené cez NEWTHREADPOOL(), podľa názvu.\n\nReturns: `Object`\n\nObjekt, v ktorom je každý kľúč `name` zadaný do `NEWTHREADPOOL()` a každá hodnota je pool. Použi ho na získanie poolu v inom súbore.\n\nExample: Použitie poolu z iného súboru\n```js\nF.workerspool.resize.exec(function(worker, release) {\n\t// ...\n\trelease();\n});\n```\n\n### worker.data\n\nType: `property`\n\nDáta, ktoré rodič odovzdal do NEWTHREAD().\n\nReturns: `Object`\n\nV súbore workera vráti `NEWTHREAD()` alebo `NEWFORK()` bez argumentov pomocný objekt workera. `worker.data` je argument `data` z `NEWTHREAD(name, data)`. V podprocese je to prázdny objekt; dáta namiesto toho pošli správou.\n\nExample: V /workers/hash.js\n```js\nrequire('total4');\nvar worker = NEWTHREAD();\nconsole.log(worker.data.rounds);\n```\n\n### worker.message = function(msg) {}\n\nType: `delegate`\n\nPrijíma správy, ktoré rodič posiela workerovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `msg` | `Object` | yes |  | Správa od rodiča |\n\nPriraď funkciu pomocnému objektu, ktorý vráti `NEWTHREAD()` alebo `NEWFORK()` bez argumentov. Volá sa pre každú správu od rodiča, vo vlákne aj v podprocese.\n\nExample: Odpoveď na každú správu\n```js\nrequire('total4');\nvar worker = NEWFORK();\nworker.message = function(msg) {\n\tworker.send({ id: msg.id, length: msg.text.length });\n};\n```\n\n### worker.send(message)\n\nType: `method`\n\nPošle správu z workera rodičovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `message` | `Object` | yes |  | Serializovateľná hodnota |\n\nVo vlákne používa `parentPort.postMessage()` a v podprocese `process.send()`. `worker.postMessage()` je tá istá metóda. Rodič prijme správu v `on('message')` objektu, ktorý vrátil `NEWTHREAD()` alebo `NEWFORK()`.\n\nExample: Hlásenie priebehu\n```js\nworker.send({ progress: 50 });\n```\n\n### worker.exit([code])\n\nType: `method`\n\nUkončí workera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `Number` | no | `0` | Návratový kód |\n\nVolá `process.exit(code)`. `worker.kill()` a `worker.close()` sú tá istá metóda.\n\nExample: Ukončenie po odpovedi\n```js\nworker.message = function(msg) {\n\tworker.send(msg);\n\tworker.exit();\n};\n```\n\n### worker.setTimeout(timeout)\n\nType: `method`\n\nUkončí workera po časovom limite.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `timeout` | `Number` | yes |  | Milisekundy |\n\nSpustí časovač, ktorý ukončí workera s návratovým kódom `1` po `timeout` milisekundách. Nové volanie nahradí predchádzajúci časovač, takže ho môžeš zavolať znova a predĺžiť limit, kým je worker zaneprázdnený.\n\nExample: Obmedzenie workera na jednu minútu\n```js\nvar worker = NEWTHREAD();\nworker.setTimeout(60000);\n```\n\n### WORKER(name, [timeout], [args])\n\nType: `method`\n\nForkne skript z /workers/ (staršie API).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru v `/workers/`, bez `.js` |\n| `timeout` | `Number` | no |  | Zabije proces po tomto počte milisekúnd |\n| `args` | `Array` | no |  | Argumenty príkazového riadku pre skript |\n\nReturns: `ChildProcess`\n\nSpustí `/workers/{name}.js` cez `child_process.fork()` v adresári aplikácie a vráti `ChildProcess`. Argumenty `args` a `--worker` sa odovzdajú skriptu. Proces sa uchováva v `F.workers`, kým neskončí. Keď uplynie `timeout` (viac ako 10 ms), proces sa zabije signálom `SIGKILL`.\n\n`timeout` môžeš vynechať: `WORKER(name, args)`. Názov, ktorý začína `@`, odkazuje na súbor balíka; názov, ktorý začína `#`, vráti bežiaceho workera z `F.workers` podľa jeho id. Novšou alternatívou je `NEWFORK()`.\n\nExample: Spustenie workera najviac na 10 sekúnd\n```js\nvar worker = WORKER('stats', 10000);\nworker.on('message', function(msg) {\n\tconsole.log(msg);\n});\nworker.send({ year: 2024 });\n```\n\nExample: /workers/stats.js\n```js\nrequire('total4');\nprocess.on('message', function(msg) {\n\tprocess.send({ year: msg.year, count: 0 });\n\tprocess.exit(0);\n});\n```\n\n### WORKER2(name, [args], callback, [timeout])\n\nType: `method`\n\nSpustí skript z /workers/ a vráti jeho štandardný výstup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru v `/workers/`, bez `.js` |\n| `args` | `Array` | no |  | Argumenty príkazového riadku; skript ich číta z `process.argv` |\n| `callback` | `Function` | yes |  | `function(err, buffer)` |\n| `timeout` | `Number` | no |  | Zabije proces po tomto počte milisekúnd |\n\nReturns: `ChildProcess`\n\nPotichu forkne `/workers/{name}.js` (ako `WORKER()`), zozbiera všetko, čo zapíše na štandardný výstup, a zavolá `callback(err, buffer)`, keď proces skončí alebo zlyhá. `args` môže byť pole alebo jedna hodnota. Poradie `callback` a `timeout` sa dá vymeniť.\n\nExample: Čítanie výstupu skriptu\n```js\nWORKER2('report', ['2024'], function(err, buffer) {\n\tvar report = buffer.toString('utf8').parseJSON();\n\tconsole.log(report);\n}, 30000);\n```\n\nExample: /workers/report.js\n```js\nvar year = process.argv[2];\nconsole.log(JSON.stringify({ year: year, total: 100 }));\n```\n\n### F.workers\n\nType: `property`\n\nBežiace procesy spustené cez WORKER().\n\nReturns: `Object`\n\nObjekt podprocesov, ktoré spustili `WORKER()` a `WORKER2()`, podľa ich id (`{name}_{number}`). Proces sa odstráni, keď skončí. Keď sa aplikácia zastaví, všetky sa zabijú.\n\n### PATH.workers([filename])\n\nType: `method`\n\nVráti cestu k súboru v adresári /workers/.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no |  | Názov súboru |\n\nReturns: `String`\n\nSpojí `directory_workers` (predvolene `/workers/`) s `filename` a vráti úplnú cestu.\n\nExample: Kontrola súboru workera\n```js\nvar exists = require('fs').existsSync(PATH.workers('resize.js'));\n```\n\n### isWORKER\n\nType: `property`\n\ntrue, keď framework beží cez LOAD() bez HTTP servera.\n\nReturns: `Boolean`\n\nGlobálna premenná je predvolene `false`. `LOAD()` ju nastaví na `true` a `HTTP()` ju vráti späť na `false`. Použi ju v zdieľanom kóde, ktorý nesmie robiť veci vyžadujúce webový server (napríklad spúšťať plánovače), keď beží vo workeri.\n\nExample: Vynechanie časovača vo workeroch\n```js\nif (!isWORKER)\n\tsetInterval(cleanup, 60000);\n```\n\n### LOAD([types], [cwd], [callback])\n\nType: `method`\n\nNačíta časti aplikácie bez spustenia HTTP servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|Array` | no |  | Časti, ktoré sa majú načítať alebo preskočiť |\n| `cwd` | `String` | no |  | Adresár aplikácie |\n| `callback` | `Function` | no |  | Volá sa, keď je aplikácia načítaná |\n\nReturns: `Promise` Len keď `callback` nie je zadaný\n\nPouži ju v súboroch workerov a skriptoch. Načíta konfiguráciu a `.env`, načíta časti uvedené v `types` a zavolá `callback` (alebo vyrieši vrátený promise), keď sú pripravené. Nastaví `isWORKER` na `true` a emituje `load` a `ready`.\n\n`types` je pole alebo reťazec oddelený čiarkami alebo medzerami, napríklad `'config,modules,schemas'`. Názvy s prefixom `no` (`'nobundles'`) vylúčia časť a načítajú zvyšok. Predvolená hodnota je `['nobundles', 'nopackages', 'nocomponents', 'nothemes']`. Pridaj `'debug'` pre beh v režime debug a `'service'` pre spustenie časovača `ON('service')`. Časti: `actions`, `builds`, `bundles`, `components`, `controllers`, `definitions`, `extensions`, `flowstreams`, `jsonschemas`, `middleware`, `models`, `modules`, `operations`, `packages`, `plugins`, `preferences`, `schemas`, `sitemap`, `tasks`, `themes`, `versions`.\n\nExample: Worker so schémami\n```js\nrequire('total4');\nLOAD('config,schemas,modules', function() {\n\tconsole.log(isWORKER); // true\n});\n```\n\nExample: S await\n```js\nrequire('total4');\n(async function() {\n\tawait LOAD('nobundles,nopackages');\n\tconsole.log(CONF.name);\n})();\n```\n\n### SHELL(command, [callback], [cwd])\n\nType: `method`\n\nSpustí príkaz shellu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `command` | `String` | yes |  | Príkazový riadok |\n| `callback` | `Function` | no |  | `function(err, stdout, stderr)` |\n| `cwd` | `String` | no | `the app directory` | Pracovný adresár |\n\nReturns: `Promise` Len keď `callback` nie je zadaný; vyrieši sa hodnotou stdout\n\nSpustí `command` cez `child_process.exec()`. Pracovný adresár je `cwd` alebo adresár aplikácie; shell je `default_shell`, keď je nastavený. Callback dostane `(err, stdout, stderr)`. Bez callbacku funkcia vráti promise, ktorý sa vyrieši štandardným výstupom. Keď používaš promise, môžeš odovzdať `cwd` ako druhý argument.\n\nNikdy nevkladaj vstup používateľa do `command` bez escapovania.\n\nExample: S callbackom\n```js\nSHELL('df -h', function(err, stdout) {\n\tconsole.log(stdout);\n});\n```\n\nExample: S await a adresárom\n```js\nvar commit = await SHELL('git rev-parse HEAD', '/www/app/');\n```\n\n### default_shell : <value>\n\nType: `config`\n\nShell, ktorý používa SHELL().\n\nReturns: `String`\n\nCesta k shellu pre `SHELL()` (možnosť `shell` z `child_process.exec()`). Keď nie je nastavená, Node.js použije `/bin/sh` na Unixe a `cmd.exe` na Windows.\n\nExample: V konfiguračnom súbore\n```text\ndefault_shell : /bin/bash\n```\n\n### options.cluster = 4\n\nType: `config`\n\nSpustí aplikáciu ako klaster niekoľkých inštancií.\n\nReturns: `Number|String`\n\nMožnosť štartovacieho skriptu `total4/release` a `total4/debug`. Číslo spustí toľko inštancií aplikácie; `'auto'` spustí jednu a pridáva alebo odoberá inštancie podľa ich času odozvy (pozri `options.cluster_limit`). Hlavný proces reštartuje inštanciu, ktorá skončí, po jednej sekunde. V režime debug master reštartuje všetky inštancie, keď sa zmení súbor.\n\nKeď je nastavené `options.threads`, hodnota platí pre každé vlákno namiesto hlavnej aplikácie.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n```\n\n### options.cluster_limit = 10\n\nType: `config`\n\nMaximálny počet inštancií v automatickom klastri.\n\nReturns: `Number`\n\nPri `options.cluster = 'auto'` master každých päť sekúnd pinguje inštancie. Pridá inštanciu, keď je priemerná odozva nad 70 ms, kým počet nedosiahne `cluster_limit`. Bez neho nie je žiadny limit. Keď inštancia odpovedá rýchlo, master odstráni poslednú inštanciu (najviac raz za 25 sekúnd), ak má menej ako dve čakajúce požiadavky.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 'auto';\noptions.cluster_limit = 8;\nrequire('total4/release')(options);\n```\n\n### options.tz = 'utc'\n\nType: `config`\n\nČasové pásmo klastra.\n\nReturns: `String`\n\nV režime klastra master nastaví `process.env.TZ` pre všetky inštancie na túto hodnotu. Keď ju nenastavíš, klaster beží v `'utc'` bez ohľadu na časové pásmo servera.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 2;\noptions.tz = 'Europe/Bratislava';\nrequire('total4/release')(options);\n```\n\n### options.threads = '/api/'\n\nType: `config`\n\nSpustí každý podadresár /threads/ ako samostatnú aplikáciu.\n\nReturns: `String|Boolean`\n\nPre každý adresár v `/threads/` hlavná aplikácia zapíše do koreňa štartovací skript `{script}_{name}.js` a forkne ho. Požiadavky pod `{threads}/{name}/` sa prepošlú tomuto vláknu cez Unix socket, bez prefixu. `true` znamená žiadny prefix (`/{name}/`).\n\nKaždé vlákno načíta súbory `.js` svojho adresára cez `exports.install`, vlastnú konfiguráciu a súbory `.env`, `views/` a `public/`. Preskočí koreňové `/controllers/` a `/middleware/`.\n\nExample: index.js\n```js\nconst options = {};\noptions.threads = '/api/';\nrequire('total4/release')(options);\n```\n\nExample: /threads/users/index.js\n```js\nexports.install = function() {\n\t// Serves GET /api/users/\n\tROUTE('GET /', function() {\n\t\tthis.json({ thread: THREAD });\n\t});\n};\n```\n\n### options.thread = 'name'\n\nType: `config`\n\nNázov vlákna procesu.\n\nReturns: `String`\n\nNastaví globálnu premennú `THREAD` a načíta aplikáciu ako vlákno `/threads/{name}/`. Skripty, ktoré zapisuje `options.threads`, ho nastavia za teba. V režime klastra je súbor na reštart `restart_{name}`.\n\n### options.logs = 'isolated'\n\nType: `config`\n\nZapisuje výstup každého vlákna do vlastného log súboru.\n\nReturns: `String`\n\nPri `'isolated'` ide výstup vlákna do `/threads/{name}/logs/debug.log` namiesto konzoly hlavnej aplikácie. Súbor sa vyprázdni, keď sa vlákno spustí (v režime debug len pri prvom spustení).\n\n### THREAD\n\nType: `property`\n\nNázov aktuálneho vlákna.\n\nReturns: `String`\n\nV bežnej aplikácii prázdny reťazec. Vo vlákne z `/threads/{name}/` je to názov vlákna. Framework ho pridáva do úvodného výpisu v konzole a do audit logov.\n\nExample: Použitie názvu vlákna\n```js\nvar key = THREAD ? ('cache_' + THREAD) : 'cache';\n```\n\n### F.threads\n\nType: `property`\n\nPodprocesy vlákien, podľa názvu.\n\nReturns: `Object`\n\nV hlavnej aplikácii s `options.threads` objekt, v ktorom je každý kľúč názov vlákna a každá hodnota jeho `ChildProcess`. Inak `undefined`.\n\n### F.isCluster\n\nType: `property`\n\ntrue v inštancii klastra.\n\nReturns: `Boolean`\n\n`true`, keď je proces inštancia spustená hlavným procesom klastra.\n\nExample: Spustenie úlohy len v jednej inštancii\n```js\nif (!F.isCluster || F.id === '0')\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### F.id\n\nType: `property`\n\nId inštancie v klastri.\n\nReturns: `String`\n\nIndex inštancie ako reťazec (`'0'`, `'1'`, ...) alebo `null` mimo klastra. Dočasné súbory inštancie dostanú prefix `cluster_{id}_`.\n\n### F.cluster.emit(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nVyvolá udalosť v každej inštancii klastra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti |\n| `a` | `Object` | no |  | Najviac päť argumentov |\n\nReturns: `Framework`\n\nPošle udalosť cez hlavný proces všetkým inštanciám vrátane odosielateľa. Každá inštancia zavolá svojich poslucháčov `ON(name)` s najviac piatimi argumentmi. Argumenty sa prenášajú ako IPC správy, preto musia byť serializovateľné. Mimo klastra nerobí nič.\n\nExample: Vymazanie cache všade\n```js\nON('settings_changed', function() {\n\tCACHE('settings', null);\n});\n\nF.cluster.emit('settings_changed');\n```\n\n### F.cluster.master(name, [a], [b], [c], [d], [e])\n\nType: `method`\n\nPošle udalosť z inštancie hlavnému procesu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti |\n| `a` | `Object` | no |  | Najviac päť argumentov |\n\nReturns: `Framework`\n\nHlavný proces zavolá poslucháčov zaregistrovaných cez `F.cluster.on(name)`. Mimo klastra nerobí nič.\n\nExample: Hlásenie hlavnému procesu\n```js\nF.cluster.master('visit', F.id);\n```\n\n### F.cluster.on(name, callback)\n\nType: `method`\n\nV hlavnom procese počúva udalosti z F.cluster.master().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov udalosti |\n| `callback` | `Function` | yes |  | `function(a, b, c, d, e)` |\n\nReturns: `Framework`\n\nZaregistruj ho v štartovacom skripte: tento skript spúšťa hlavný proces aj každá inštancia. Callback dostane argumenty z `F.cluster.master()`. Pre každý názov zaregistruj len jedného poslucháča.\n\nExample: index.js\n```js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\nvar visits = 0;\nF.cluster.on('visit', function(id) {\n\tvisits++;\n});\n```\n\n### F.cluster.restart([index])\n\nType: `method`\n\nReštartuje inštancie klastra z hlavného procesu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `index` | `Number` | no |  | Index inštancie |\n\nReštartuje inštanciu s `index` alebo všetky inštancie s odstupom dvoch sekúnd, keď `index` nie je zadaný. Funguje len v hlavnom procese. Zvonku namiesto toho vytvor súbor `restart`.\n\nExample: Reštart všetkých inštancií zo štartovacieho skriptu\n```js\n// index.js\nconst options = {};\noptions.cluster = 4;\nrequire('total4/release')(options);\n\n// The start script also runs in every instance, so check the master\nif (require('cluster').isMaster)\n\tsetInterval(() => F.cluster.restart(), 24 * 60 * 60 * 1000);\n```\n\n### F.cluster.http(count, mode, [options], [callback])\n\nType: `method`\n\nSpustí klaster s HTTP serverom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `count` | `Number|String` | yes |  | Počet inštancií alebo `'auto'` |\n| `mode` | `String` | yes |  | `'debug'` alebo `'release'` |\n| `options` | `Object` | no |  | Štartovacie možnosti |\n| `callback` | `Function` | no |  | `function(forks)` |\n\nToto volá `options.cluster` v štartovacom skripte. `count` je číslo, `'auto'` alebo `null` (jedna inštancia na jadro CPU). `mode` je `'debug'` alebo `'release'`. `options` sú štartovacie možnosti, ktoré dostanú inštancie. V hlavnom procese sa `callback` zavolá s poľom inštancií, keď sa všetky spustili. `F.cluster.https()` berie rovnaké argumenty a spúšťa HTTPS servery.\n\nExample: Priame spustenie klastra\n```js\nrequire('total4').cluster.http(4, 'release', { port: 8000 });\n```\n\n### restart\n\nType: `command`\n\nSúbor, ktorý reštartuje všetky inštancie bežiaceho klastra.\n\nHlavný proces každých päť sekúnd hľadá v adresári aplikácie súbor s názvom `restart` (`restart_{thread}`, keď je nastavené `options.thread`). Keď ho nájde, súbor zmaže a reštartuje všetky inštancie s odstupom dvoch sekúnd, najviac raz za 30 sekúnd. Použi ho po nasadení, aby sa načítal nový kód bez zastavenia aplikácie.\n\nHlavný proces tiež približne každých 50 sekúnd zapisuje svoj stav (PID, verzie, počet inštancií, pamäť a štatistiky každej inštancie) do súboru s názvom štartovacieho skriptu plus `.json`, napríklad `index.js.json`.\n\nExample: Reštart po nasadení\n```bash\ntouch /www/app/restart\n```\n\n### allow_cache_cluster : false\n\nType: `config`\n\nSynchronizuje cache frameworku medzi inštanciami klastra.\n\nReturns: `Boolean`\n\nKeď je `true`, každé `CACHE()` / `F.cache.set()`, `remove()`, `removeAll()` a `clear()` v inštancii sa zopakuje v ostatných inštanciách. Relácie sa v klastri synchronizujú aj bez tejto možnosti.\n\nExample: V konfiguračnom súbore\n```text\nallow_cache_cluster : true\n```\n","entries":[{"type":"method","name":"NEWTHREAD()","signature":"NEWTHREAD(name, [data])","since":"","deprecated":false},{"type":"method","name":"NEWFORK()","signature":"NEWFORK(name)","since":"","deprecated":false},{"type":"method","name":"NEWTHREADPOOL()","signature":"NEWTHREADPOOL(name, count, [isfork])","since":"","deprecated":false},{"type":"method","name":"pool.exec()","signature":"pool.exec([fn])","since":"","deprecated":false},{"type":"property","name":"pool.workers","signature":"pool.workers","since":"","deprecated":false},{"type":"property","name":"F.workerspool","signature":"F.workerspool","since":"","deprecated":false},{"type":"property","name":"worker.data","signature":"worker.data","since":"","deprecated":false},{"type":"delegate","name":"worker.message","signature":"worker.message = function(msg) {}","since":"","deprecated":false},{"type":"method","name":"worker.send()","signature":"worker.send(message)","since":"","deprecated":false},{"type":"method","name":"worker.exit()","signature":"worker.exit([code])","since":"","deprecated":false},{"type":"method","name":"worker.setTimeout()","signature":"worker.setTimeout(timeout)","since":"","deprecated":false},{"type":"method","name":"WORKER()","signature":"WORKER(name, [timeout], [args])","since":"","deprecated":false},{"type":"method","name":"WORKER2()","signature":"WORKER2(name, [args], callback, [timeout])","since":"","deprecated":false},{"type":"property","name":"F.workers","signature":"F.workers","since":"","deprecated":false},{"type":"method","name":"PATH.workers()","signature":"PATH.workers([filename])","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [cwd], [callback])","since":"","deprecated":false},{"type":"method","name":"SHELL()","signature":"SHELL(command, [callback], [cwd])","since":"","deprecated":false},{"type":"config","name":"default_shell","signature":"default_shell : <value>","since":"","deprecated":false},{"type":"config","name":"options.cluster","signature":"options.cluster = 4","since":"","deprecated":false},{"type":"config","name":"options.cluster_limit","signature":"options.cluster_limit = 10","since":"","deprecated":false},{"type":"config","name":"options.tz","signature":"options.tz = 'utc'","since":"","deprecated":false},{"type":"config","name":"options.threads","signature":"options.threads = '/api/'","since":"","deprecated":false},{"type":"config","name":"options.thread","signature":"options.thread = 'name'","since":"","deprecated":false},{"type":"config","name":"options.logs","signature":"options.logs = 'isolated'","since":"","deprecated":false},{"type":"property","name":"THREAD","signature":"THREAD","since":"","deprecated":false},{"type":"property","name":"F.threads","signature":"F.threads","since":"","deprecated":false},{"type":"property","name":"F.isCluster","signature":"F.isCluster","since":"","deprecated":false},{"type":"property","name":"F.id","signature":"F.id","since":"","deprecated":false},{"type":"method","name":"F.cluster.emit()","signature":"F.cluster.emit(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.master()","signature":"F.cluster.master(name, [a], [b], [c], [d], [e])","since":"","deprecated":false},{"type":"method","name":"F.cluster.on()","signature":"F.cluster.on(name, callback)","since":"","deprecated":false},{"type":"method","name":"F.cluster.restart()","signature":"F.cluster.restart([index])","since":"","deprecated":false},{"type":"method","name":"F.cluster.http()","signature":"F.cluster.http(count, mode, [options], [callback])","since":"","deprecated":false},{"type":"command","name":"restart","signature":"restart","since":"","deprecated":false},{"type":"config","name":"allow_cache_cluster","signature":"allow_cache_cluster : false","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:05.817Z"}
{"id":"Jabm3e3Zr60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Message Service and APIs","summary":"TMS functions, the TMS client, API(), NEWAPI(), TotalAPI() and API routes.","markdown":"---\ntitle: Message Service and APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service and APIs\n\n> TMS functions, the TMS client, API(), NEWAPI(), TotalAPI() and API routes.\n\nTMS channels are declared with `NEWPUBLISH()`, `NEWSUBSCRIBE()` and `NEWCALL()`, and another app connects with `TMSCLIENT()`. `API()` calls providers registered with `NEWAPI()`. The guide [Message Service and APIs](../../guides/message-service-and-apis/) explains how the parts work together; this page is the exact reference.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDeclares a TMS channel that your app publishes to.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the channel |\n| `schema` | `String|Object` | no |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel |\n\nReturns: `undefined`\n\nThe channel and its JSON schema are sent to every TMS client in the `meta` message. A schema name that does not exist throws an error. Without `schema` (or with `null`), the channel is removed. Redeclaring an existing channel keeps its first schema.\n\nExample: Declare a channel\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Remove a channel\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nSends a message to TMS clients subscribed to the channel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of a channel declared with `NEWPUBLISH()` |\n| `data` | `Object` | yes |  | The message |\n\nReturns: `undefined`\n\nOnly clients that announced a subscription to `name` receive the message. It does nothing when no TMS client is connected or when `name` was not declared with `NEWPUBLISH()`. The data is not validated on the server; `TMSCLIENT()` converts it with the channel schema.\n\nExample: Publish after an insert\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDeclares a TMS channel that clients publish to and your app receives.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the channel |\n| `schema` | `String|Object` | no |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema. Leave it out to remove the channel |\n| `callback` | `Function` | no |  | A handler `function(data, client)` |\n\nReturns: `undefined`\n\nIncoming messages of the channel are validated with `schema`; invalid messages are dropped and valid ones go to the handlers added with `SUBSCRIBE()`. `callback` is a shortcut for `SUBSCRIBE(name, callback)`. Without `schema`, the channel is removed (its handlers stay).\n\nExample: Declare a channel with a handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nAdds a handler for messages of a TMS subscribe channel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the channel |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nThe handler receives the validated data and the WebSocket client that sent it. A channel can have many handlers. Messages arrive only for channels declared with `NEWSUBSCRIBE()`. The app announces its subscriptions to the clients in the next `meta` message.\n\nExample: Add a handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nRemoves one handler or all handlers of a TMS channel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the channel |\n| `callback` | `Function` | no |  | The handler to remove |\n\nReturns: `Boolean` `true` when something was removed\n\nWith `callback`, only that handler is removed (pass the same function you gave to `SUBSCRIBE()`). Without it, all handlers of the channel are removed.\n\nExample: Remove a handler\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nRegisters a TMS remote call that clients can run.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the call |\n| `schema` | `String|Object` | yes |  | An inline declaration (`id:UID, name:String`), a JSON schema object with `$id`, or the name of a JSON schema or a Total.js schema, or `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` or an operation name |\n\nReturns: `undefined`\n\nThe data of a call is validated with `schema`; a validation error goes back to the client. `callback(data, next, client)` answers with `next(err, response)`. Instead of a function, `callback` can be the name of an operation. With no callback and a schema like `*Orders --> create`, the call runs that schema action. `NEWCALL(name, null)` removes the call. A call that does not exist answers with error `404`.\n\nExample: A call with a function\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: A call that runs a schema action\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nThe JSON messages exchanged on the TMS endpoint.\n\nReturns: `Object`\n\nEvery message is a JSON object with `type`:\n\n- `meta` (server to client): `name`, `publish`, `subscribe` and `call` (arrays of `{ id, schema }`) and `subscribers` (channels the app subscribes to). Sent after connecting and one second after any change.\n- `publish` (server to client): `{ id, data }`, sent by `PUBLISH()`.\n- `subscribe` (client to server): `{ id, data }`, a message for a `NEWSUBSCRIBE()` channel.\n- `subscribers` (client to server): `{ subscribers: [names] }`, the channels the client wants to receive.\n- `call` (both ways): `{ id, data, callbackid }`; the answer adds `success: true` or `error: true`.\n- `ping`: answered with `pong`.\n\nYou need this only to write a TMS client without `TMSCLIENT()`. A new client starts with an empty list of subscriptions and receives `publish` messages only for the channels it lists in `subscribers`.\n\nExample: A client subscribes and calls\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nThe token that TMS clients must send.\n\nReturns: `String`\n\nClients send it in the `x-token` header. A wrong token closes the connection with code `4001`; more than five failed attempts from one IP address block it until the daily reset. Changing the token closes the TMS connections. The value can also be a number. Default: empty, every client is accepted.\n\nExample: Protect TMS\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nMaximum size of a TMS message in kB.\n\nReturns: `Number`\n\nApplied to the WebSocket route of the TMS endpoint (`default_tms_url`). Default: `1024` (1 MB).\n\nExample: Allow bigger messages\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nOption of schema.action() and NEWACTION() that declares a TMS publish channel.\n\nReturns: `Boolean|String`\n\nThe channel is named after the action: `Schema.action` for `schema.action()`, the action name for `NEWACTION()`. `true` uses the `input` (or `output`) of the action as the channel schema. A string is its own inline schema; a string that starts with `+` adds its fields to the input. Send messages with `$.publish()`.\n\nExample: Publish from an action\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nPublishes a message to the TMS channel of the current action.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The message |\n\nReturns: `SchemaOptions` The same `$`, for chaining\n\nWorks in actions declared with the `publish` option; the channel name is the action ID. Like `PUBLISH()`, it does nothing without a connected TMS client. The fields of `value` are copied to a new object.\n\nExample: Publish and answer\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nConnects to the TMS endpoint of another Total.js app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL of the TMS endpoint, for example `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | The server `secret_tms` |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` The TMS client\n\nReturns a WebSocket client (see [WebSockets](../../guides/websockets/)) with the extra methods `subscribe()`, `publish()` and `call()`. An `http` URL is changed to `ws` and the client reconnects when the server goes down. `token` is sent in the `x-token` header. `callback(err, client, meta)` runs once, after the first `meta` message.\n\nExample: Connect\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nReceives messages of a publish channel of the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of a channel declared with `NEWPUBLISH()` on the server |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nThe data is converted with the channel schema from `meta`, and handlers run only for channels the server publishes. The client sends its list of subscriptions to the server shortly after each call and again after reconnecting.\n\nExample: Subscribe\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nSends a message to a subscribe channel of the server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of a channel declared with `NEWSUBSCRIBE()` on the server |\n| `data` | `Object` | yes |  | The message |\n\nReturns: `undefined`\n\nThe server validates it with the schema of its `NEWSUBSCRIBE()` channel. Nothing is sent while the client is not connected.\n\nExample: Publish\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nRuns a remote call registered on the server with NEWCALL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the call |\n| `data` | `Object` | yes |  | Data of the call |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Timeout in milliseconds |\n\nReturns: `Promise|undefined` A promise when there is no callback\n\n`callback(err, response)` receives the response; errors from the server arrive as an `ErrorBuilder`. Without a callback it returns a promise. Before the connection is ready, it fails with `TMS is offline`; without an answer in time, with `408: Timeout`.\n\nExample: Call with a callback\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Call with await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true` when the client is connected and has received the meta.\n\nReturns: `Boolean`\n\nIt becomes `false` when the connection closes and `true` again after the next `meta`.\n\nExample: Check the state\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nThe last meta message received from the server.\n\nReturns: `Object`\n\nIt contains the server `name` and the `publish`, `subscribe` and `call` lists with JSON schemas. See TMS messages.\n\nExample: List the remote calls\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nEmitted each time the server sends its meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | The meta message |\n\nThe server sends the meta after connecting, after reconnecting and after any change of its channels or calls.\n\nExample: Watch changes\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nEmitted after each meta message, when the client is ready.\n\nUse it to run code after every reconnection; the `TMSCLIENT()` callback runs only the first time.\n\nExample: After every connection\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nRegisters an API provider used by API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the provider, several separated by commas, or `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Leave it out to remove the provider |\n\nReturns: `undefined`\n\n`callback(opt, next)` runs for each `API()` call with this name, with the call object as `this`. `opt` has `name`, `schema`, `data`, `controller`, and `files` and `output` when set. Answer with `next(err, response)`. `name` is not case-sensitive, can list several names separated by commas, and `*` registers a fallback for unknown names. A name without `callback` removes the provider. The provider `TotalAPI` (alias `TAPI`) is registered by default.\n\nExample: A custom provider\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nSends a request to a registered API provider.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name of the provider, for example `TotalAPI` |\n| `schema` | `String` | yes |  | The endpoint or operation of the provider |\n| `data` | `Object` | no |  | Data of the request |\n| `$` | `Object` | no |  | A controller or `$`, passed to the provider as `opt.controller` |\n\nReturns: `APICall` The call object\n\nReturns a call object. The request starts on the next tick, so chain the options and the callback right away. Without a provider for `name` (and no `*` provider), the call fails with `API is not initialized`.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Inside an action\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nSets the callback of the API call.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)`, or `$` |\n\nReturns: `APICall` The call, for chaining\n\n`fn(err, response)`. Pass `$` (or an object with `callback`) to answer an action with the result.\n\nExample: With $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nReturns a promise with the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | An object with `invalid()`, such as `$` |\n\nReturns: `Promise` The response\n\nWith `$`, an error is sent with `$.invalid()` and the promise never resolves; without it the promise is rejected with an error named `API(name --> schema)`.\n\nExample: Await the response\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nSets the output format of the response.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The output format |\n\nReturns: `APICall` The call, for chaining\n\nThe provider reads it as `opt.output`. The `TotalAPI` provider supports `json` (default), `html`, `text`, `plain`, `base64`, `buffer` or `binary`, `stream`, and `#name id filename` to save the response to a FileStorage.\n\nExample: Save the response to FileStorage\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nAdds a file to the request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Name of the file |\n| `path` | `String` | yes |  | Path to the file on disk |\n| `name` | `String` | no | `'file' + index` | Name of the form field |\n\nReturns: `APICall` The call, for chaining\n\nAdds `{ name, filename, path }` to `opt.files`. The `TotalAPI` provider then sends the data and files as a multipart request.\n\nExample: Send a file\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nTurns an empty response into an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | The error |\n| `reverse` | `Boolean` | no | `false` | Fail when the response is not empty |\n\nReturns: `APICall` The call, for chaining\n\nAn empty response (or an empty array) becomes `err`. With `reverse`, a non-empty response becomes the error instead. Alias: `api.err()`.\n\nExample: Require a response\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nRuns a function when the call fails.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` The call, for chaining\n\n`fn(err)` runs in addition to the callback.\n\nExample: Log errors\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nRuns a function with the response when the call succeeds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` The call, for chaining\n\n`fn(response)` runs in addition to the callback, only without an error.\n\nExample: Use the response\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nWrites an audit log entry when the call succeeds.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | The `$` of an action or operation |\n| `message` | `String` | no |  | The audit message |\n| `type` | `String` | no |  | Type of the entry |\n\nReturns: `APICall` The call, for chaining\n\nCalls `$.audit(message, type)`. Variables in the message are filled from the data of the call with `$.variables()`.\n\nExample: Audit a payment\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nPasses a controller to the provider.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | A controller or `$` |\n\nReturns: `APICall` The call, for chaining\n\nSets `opt.controller` to `$.controller` (or `$` itself).\n\nExample: Pass the controller\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nLogs the result of the call to the console.\n\nReturns: `APICall` The call, for chaining\n\nPrints the provider name, the schema, the error and the response.\n\nExample: Debug a call\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nSends one request to Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Total API token |\n| `type` | `String` | yes |  | The Total API service |\n| `data` | `Object` | yes |  | Data of the request |\n| `callback` | `Function|Controller` | no |  | `function(err, response)`, or a controller to stream a file |\n| `filename` | `String` | no |  | File name of a streamed file |\n\nReturns: `Promise|undefined` A promise when there is no callback\n\nPosts `data` to `https://{default_tapi}.api.totaljs.com/{type}/`. The token defaults to `totalapi` (or `secret_totalapi`). A non-object `data` is sent as `{ value: data }`. Without a callback it returns a promise. A binary response goes to the callback as a stream, or, when `callback` is a controller, is sent to the client with `filename`. With `allow_totalapi: false`, only `check` works; other calls fail with `totalapi_inactive`.\n\nExample: Check the token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nThe Total API token.\n\nReturns: `String`\n\nUsed by `TotalAPI()`, the `TotalAPI` provider of `API()` and the audit logger. `secret_totalapi` is read when `totalapi` is empty.\n\nExample: Set the token\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nThe Total API server region.\n\nReturns: `String`\n\nRequests go to `https://{default_tapi}.api.totaljs.com/`. Default: `eu`.\n\nExample: Region\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nSends audit logs to Total API.\n\nReturns: `Boolean`\n\nWhen `true` and a Total API token is set, audit entries are sent to the Total API `logger` service instead of `DEF.onAudit()`. Default: `false`.\n\nExample: Enable\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDeclares an API route: one POST URL that runs actions by name.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The route declaration |\n| `fn` | `Function` | no |  | A custom handler with the controller as `this` |\n| `flags` | `Array` | no |  | Route flags |\n\nReturns: `Object` The route\n\nThe client posts `{ \"schema\": \"name/param?query\", \"data\": {} }` to the URL. The sign before the name sets how the data is handled: `+` validates it like `POST`, `#` like `PATCH` (partial), `-` sends none like `GET`. URL parameters can have a type after `:` (`uid`, `number`, `guid`, `date`); the first becomes `$.id`. Without `*Schema --> action`, the route runs the action with the same name (`--> name`). `+API` requires a signed-in user and `-API` an anonymous one. Unknown names answer `404`, invalid parameters `400`.\n\nExample: API routes\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: A request\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nAn API route action handled by your own function.\n\nInstead of `*Schema --> action`, pass a function. It runs with the controller as `this`; `this.params` holds the URL parameters, `this.body` the posted `{ schema, data }` and `this.id` the first parameter. Answer with any controller method.\n\nExample: A custom action\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm3e3Zr60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Message Service und APIs","summary":"TMS-Funktionen, der TMS-Client, API(), NEWAPI(), TotalAPI() und API-Routen.","markdown":"---\ntitle: Message Service und APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service und APIs\n\n> TMS-Funktionen, der TMS-Client, API(), NEWAPI(), TotalAPI() und API-Routen.\n\nTMS-Kanäle werden mit `NEWPUBLISH()`, `NEWSUBSCRIBE()` und `NEWCALL()` deklariert, und eine andere App verbindet sich mit `TMSCLIENT()`. `API()` ruft Provider auf, die mit `NEWAPI()` registriert wurden. Die Anleitung [Message Service und APIs](../../guides/message-service-and-apis/) erklärt, wie die Teile zusammenarbeiten; diese Seite ist die genaue Referenz.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDeklariert einen TMS-Kanal, in den deine App veröffentlicht.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Kanals |\n| `schema` | `String|Object` | no |  | Eine Inline-Deklaration (`id:UID, name:String`), ein JSON-Schema-Objekt mit `$id` oder der Name eines JSON-Schemas oder eines Total.js-Schemas. Lass es weg, um den Kanal zu entfernen |\n\nReturns: `undefined`\n\nDer Kanal und sein JSON-Schema werden in der `meta`-Nachricht an jeden TMS-Client gesendet. Ein nicht existierender Schemaname löst einen Fehler aus. Ohne `schema` (oder mit `null`) wird der Kanal entfernt. Wird ein bestehender Kanal erneut deklariert, behält er sein erstes Schema.\n\nExample: Einen Kanal deklarieren\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Einen Kanal entfernen\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nSendet eine Nachricht an TMS-Clients, die den Kanal abonniert haben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name eines mit `NEWPUBLISH()` deklarierten Kanals |\n| `data` | `Object` | yes |  | Die Nachricht |\n\nReturns: `undefined`\n\nNur Clients, die ein Abonnement für `name` angemeldet haben, erhalten die Nachricht. Es passiert nichts, wenn kein TMS-Client verbunden ist oder `name` nicht mit `NEWPUBLISH()` deklariert wurde. Die Daten werden auf dem Server nicht validiert; `TMSCLIENT()` konvertiert sie mit dem Schema des Kanals.\n\nExample: Nach einem Insert veröffentlichen\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDeklariert einen TMS-Kanal, in den Clients veröffentlichen und den deine App empfängt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Kanals |\n| `schema` | `String|Object` | no |  | Eine Inline-Deklaration (`id:UID, name:String`), ein JSON-Schema-Objekt mit `$id` oder der Name eines JSON-Schemas oder eines Total.js-Schemas. Lass es weg, um den Kanal zu entfernen |\n| `callback` | `Function` | no |  | Ein Handler `function(data, client)` |\n\nReturns: `undefined`\n\nEingehende Nachrichten des Kanals werden mit `schema` validiert; ungültige Nachrichten werden verworfen, gültige gehen an die mit `SUBSCRIBE()` hinzugefügten Handler. `callback` ist eine Kurzform für `SUBSCRIBE(name, callback)`. Ohne `schema` wird der Kanal entfernt (seine Handler bleiben).\n\nExample: Einen Kanal mit einem Handler deklarieren\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nFügt einen Handler für Nachrichten eines TMS-Subscribe-Kanals hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Kanals |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nDer Handler erhält die validierten Daten und den WebSocket-Client, der sie gesendet hat. Ein Kanal kann viele Handler haben. Nachrichten kommen nur für Kanäle an, die mit `NEWSUBSCRIBE()` deklariert wurden. Die App meldet ihre Abonnements den Clients in der nächsten `meta`-Nachricht.\n\nExample: Einen Handler hinzufügen\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nEntfernt einen Handler oder alle Handler eines TMS-Kanals.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Kanals |\n| `callback` | `Function` | no |  | Der zu entfernende Handler |\n\nReturns: `Boolean` `true`, wenn etwas entfernt wurde\n\nMit `callback` wird nur dieser Handler entfernt (übergib dieselbe Funktion, die du an `SUBSCRIBE()` übergeben hast). Ohne ihn werden alle Handler des Kanals entfernt.\n\nExample: Einen Handler entfernen\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nRegistriert einen TMS-Remote-Aufruf, den Clients ausführen können.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Aufrufs |\n| `schema` | `String|Object` | yes |  | Eine Inline-Deklaration (`id:UID, name:String`), ein JSON-Schema-Objekt mit `$id`, der Name eines JSON-Schemas oder eines Total.js-Schemas oder `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` oder der Name einer Operation |\n\nReturns: `undefined`\n\nDie Daten eines Aufrufs werden mit `schema` validiert; ein Validierungsfehler geht an den Client zurück. `callback(data, next, client)` antwortet mit `next(err, response)`. Statt einer Funktion kann `callback` der Name einer Operation sein. Ohne Callback und mit einem Schema wie `*Orders --> create` führt der Aufruf diese Schema-Aktion aus. `NEWCALL(name, null)` entfernt den Aufruf. Ein nicht existierender Aufruf antwortet mit dem Fehler `404`.\n\nExample: Ein Aufruf mit einer Funktion\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: Ein Aufruf, der eine Schema-Aktion ausführt\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nDie JSON-Nachrichten, die am TMS-Endpunkt ausgetauscht werden.\n\nReturns: `Object`\n\nJede Nachricht ist ein JSON-Objekt mit `type`:\n\n- `meta` (Server zum Client): `name`, `publish`, `subscribe` und `call` (Arrays aus `{ id, schema }`) sowie `subscribers` (Kanäle, die die App abonniert). Wird nach dem Verbinden und eine Sekunde nach jeder Änderung gesendet.\n- `publish` (Server zum Client): `{ id, data }`, gesendet von `PUBLISH()`.\n- `subscribe` (Client zum Server): `{ id, data }`, eine Nachricht für einen `NEWSUBSCRIBE()`-Kanal.\n- `subscribers` (Client zum Server): `{ subscribers: [names] }`, die Kanäle, die der Client empfangen will.\n- `call` (in beide Richtungen): `{ id, data, callbackid }`; die Antwort fügt `success: true` oder `error: true` hinzu.\n- `ping`: wird mit `pong` beantwortet.\n\nDu brauchst das nur, um einen TMS-Client ohne `TMSCLIENT()` zu schreiben. Ein neuer Client startet mit einer leeren Liste von Abonnements und empfängt `publish`-Nachrichten nur für die Kanäle, die er in `subscribers` aufführt.\n\nExample: Ein Client abonniert und ruft auf\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nDas Token, das TMS-Clients senden müssen.\n\nReturns: `String`\n\nClients senden es im Header `x-token`. Ein falsches Token schließt die Verbindung mit dem Code `4001`; mehr als fünf fehlgeschlagene Versuche von einer IP-Adresse sperren diese bis zum täglichen Zurücksetzen. Eine Änderung des Tokens schließt die TMS-Verbindungen. Der Wert kann auch eine Zahl sein. Standard: leer, jeder Client wird akzeptiert.\n\nExample: TMS schützen\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nMaximale Größe einer TMS-Nachricht in kB.\n\nReturns: `Number`\n\nGilt für die WebSocket-Route des TMS-Endpunkts (`default_tms_url`). Standard: `1024` (1 MB).\n\nExample: Größere Nachrichten erlauben\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nOption von schema.action() und NEWACTION(), die einen TMS-Publish-Kanal deklariert.\n\nReturns: `Boolean|String`\n\nDer Kanal ist nach der Aktion benannt: `Schema.action` bei `schema.action()`, der Name der Aktion bei `NEWACTION()`. `true` verwendet `input` (oder `output`) der Aktion als Schema des Kanals. Ein String ist ein eigenes Inline-Schema; ein String, der mit `+` beginnt, fügt seine Felder dem Input hinzu. Sende Nachrichten mit `$.publish()`.\n\nExample: Aus einer Aktion veröffentlichen\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nVeröffentlicht eine Nachricht im TMS-Kanal der aktuellen Aktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Die Nachricht |\n\nReturns: `SchemaOptions` Dasselbe `$`, zum Verketten\n\nFunktioniert in Aktionen, die mit der Option `publish` deklariert wurden; der Kanalname ist die ID der Aktion. Wie `PUBLISH()` passiert ohne verbundenen TMS-Client nichts. Die Felder von `value` werden in ein neues Objekt kopiert.\n\nExample: Veröffentlichen und antworten\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nVerbindet sich mit dem TMS-Endpunkt einer anderen Total.js-App.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL des TMS-Endpunkts, zum Beispiel `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | Das `secret_tms` des Servers |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` Der TMS-Client\n\nGibt einen WebSocket-Client zurück (siehe [WebSockets](../../guides/websockets/)) mit den zusätzlichen Methoden `subscribe()`, `publish()` und `call()`. Eine `http`-URL wird in `ws` geändert, und der Client verbindet sich erneut, wenn der Server ausfällt. `token` wird im Header `x-token` gesendet. `callback(err, client, meta)` läuft einmal, nach der ersten `meta`-Nachricht.\n\nExample: Verbinden\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nEmpfängt Nachrichten eines Publish-Kanals des Servers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name eines auf dem Server mit `NEWPUBLISH()` deklarierten Kanals |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nDie Daten werden mit dem Schema des Kanals aus `meta` konvertiert, und Handler laufen nur für Kanäle, die der Server veröffentlicht. Der Client sendet seine Liste der Abonnements kurz nach jedem Aufruf und erneut nach dem Wiederverbinden an den Server.\n\nExample: Abonnieren\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nSendet eine Nachricht an einen Subscribe-Kanal des Servers.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name eines auf dem Server mit `NEWSUBSCRIBE()` deklarierten Kanals |\n| `data` | `Object` | yes |  | Die Nachricht |\n\nReturns: `undefined`\n\nDer Server validiert sie mit dem Schema seines `NEWSUBSCRIBE()`-Kanals. Solange der Client nicht verbunden ist, wird nichts gesendet.\n\nExample: Veröffentlichen\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nFührt einen auf dem Server mit NEWCALL() registrierten Remote-Aufruf aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Aufrufs |\n| `data` | `Object` | yes |  | Daten des Aufrufs |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Timeout in Millisekunden |\n\nReturns: `Promise|undefined` Eine Promise, wenn kein Callback angegeben ist\n\n`callback(err, response)` erhält die Antwort; Fehler vom Server kommen als `ErrorBuilder` an. Ohne Callback gibt die Methode eine Promise zurück. Bevor die Verbindung bereit ist, schlägt sie mit `TMS is offline` fehl; ohne rechtzeitige Antwort mit `408: Timeout`.\n\nExample: Aufruf mit einem Callback\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Aufruf mit await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true`, wenn der Client verbunden ist und die Meta-Nachricht empfangen hat.\n\nReturns: `Boolean`\n\nDer Wert wird `false`, wenn die Verbindung geschlossen wird, und nach der nächsten `meta` wieder `true`.\n\nExample: Den Zustand prüfen\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nDie letzte vom Server empfangene Meta-Nachricht.\n\nReturns: `Object`\n\nSie enthält den `name` des Servers und die Listen `publish`, `subscribe` und `call` mit JSON-Schemas. Siehe TMS-Nachrichten.\n\nExample: Die Remote-Aufrufe auflisten\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nWird jedes Mal gesendet, wenn der Server seine Meta-Nachricht sendet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Die Meta-Nachricht |\n\nDer Server sendet die Meta-Nachricht nach dem Verbinden, nach dem Wiederverbinden und nach jeder Änderung seiner Kanäle oder Aufrufe.\n\nExample: Änderungen beobachten\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nWird nach jeder Meta-Nachricht gesendet, wenn der Client bereit ist.\n\nVerwende es, um nach jedem Wiederverbinden Code auszuführen; der Callback von `TMSCLIENT()` läuft nur beim ersten Mal.\n\nExample: Nach jeder Verbindung\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nRegistriert einen API-Provider, der von API() verwendet wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Providers, mehrere durch Kommas getrennt, oder `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Lass ihn weg, um den Provider zu entfernen |\n\nReturns: `undefined`\n\n`callback(opt, next)` läuft für jeden `API()`-Aufruf mit diesem Namen, mit dem Aufrufobjekt als `this`. `opt` hat `name`, `schema`, `data`, `controller` sowie `files` und `output`, wenn gesetzt. Antworte mit `next(err, response)`. Bei `name` wird die Groß- und Kleinschreibung nicht beachtet, es kann mehrere durch Kommas getrennte Namen enthalten, und `*` registriert einen Fallback für unbekannte Namen. Ein Name ohne `callback` entfernt den Provider. Der Provider `TotalAPI` (Alias `TAPI`) ist standardmäßig registriert.\n\nExample: Ein eigener Provider\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nSendet eine Anfrage an einen registrierten API-Provider.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Name des Providers, zum Beispiel `TotalAPI` |\n| `schema` | `String` | yes |  | Der Endpunkt oder die Operation des Providers |\n| `data` | `Object` | no |  | Daten der Anfrage |\n| `$` | `Object` | no |  | Ein Controller oder `$`, an den Provider als `opt.controller` übergeben |\n\nReturns: `APICall` Das Aufrufobjekt\n\nGibt ein Aufrufobjekt zurück. Die Anfrage startet im nächsten Tick, verkette die Optionen und den Callback also sofort. Ohne Provider für `name` (und ohne `*`-Provider) schlägt der Aufruf mit `API is not initialized` fehl.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Innerhalb einer Aktion\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nSetzt den Callback des API-Aufrufs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)` oder `$` |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\n`fn(err, response)`. Übergib `$` (oder ein Objekt mit `callback`), um eine Aktion mit dem Ergebnis zu beantworten.\n\nExample: Mit $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nGibt eine Promise mit der Response zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Ein Objekt mit `invalid()`, zum Beispiel `$` |\n\nReturns: `Promise` Die Antwort\n\nMit `$` wird ein Fehler mit `$.invalid()` gesendet, und die Promise wird nie aufgelöst; ohne `$` wird die Promise mit einem Fehler namens `API(name --> schema)` abgelehnt.\n\nExample: Auf die Antwort warten\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nSetzt das Ausgabeformat der Antwort.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Das Ausgabeformat |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nDer Provider liest es als `opt.output`. Der Provider `TotalAPI` unterstützt `json` (Standard), `html`, `text`, `plain`, `base64`, `buffer` oder `binary`, `stream` und `#name id filename`, um die Antwort in einem FileStorage zu speichern.\n\nExample: Die Antwort im FileStorage speichern\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nFügt der Anfrage eine Datei hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Name der Datei |\n| `path` | `String` | yes |  | Pfad zur Datei auf der Festplatte |\n| `name` | `String` | no | `'file' + index` | Name des Formularfelds |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nFügt `{ name, filename, path }` zu `opt.files` hinzu. Der Provider `TotalAPI` sendet dann die Daten und Dateien als Multipart-Anfrage.\n\nExample: Eine Datei senden\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nMacht aus einer leeren Antwort einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | Der Fehler |\n| `reverse` | `Boolean` | no | `false` | Fehlschlagen, wenn die Antwort nicht leer ist |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nEine leere Antwort (oder ein leeres Array) wird zu `err`. Mit `reverse` wird stattdessen eine nicht leere Antwort zum Fehler. Alias: `api.err()`.\n\nExample: Eine Antwort verlangen\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nFührt eine Funktion aus, wenn der Aufruf fehlschlägt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\n`fn(err)` läuft zusätzlich zum Callback.\n\nExample: Fehler protokollieren\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nFührt eine Funktion mit der Antwort aus, wenn der Aufruf erfolgreich ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\n`fn(response)` läuft zusätzlich zum Callback, nur ohne Fehler.\n\nExample: Die Antwort verwenden\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nSchreibt einen Audit-Log-Eintrag, wenn der Aufruf erfolgreich ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Das `$` einer Aktion oder Operation |\n| `message` | `String` | no |  | Die Audit-Nachricht |\n| `type` | `String` | no |  | Typ des Eintrags |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nRuft `$.audit(message, type)` auf. Variablen in der Nachricht werden mit `$.variables()` aus den Daten des Aufrufs gefüllt.\n\nExample: Eine Zahlung auditieren\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nÜbergibt einen Controller an den Provider.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Ein Controller oder `$` |\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nSetzt `opt.controller` auf `$.controller` (oder auf `$` selbst).\n\nExample: Den Controller übergeben\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nGibt das Ergebnis des Aufrufs in der Konsole aus.\n\nReturns: `APICall` Der Aufruf, zum Verketten\n\nGibt den Namen des Providers, das Schema, den Fehler und die Antwort aus.\n\nExample: Einen Aufruf debuggen\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nSendet eine einzelne Anfrage an Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Total-API-Token |\n| `type` | `String` | yes |  | Der Total-API-Dienst |\n| `data` | `Object` | yes |  | Daten der Anfrage |\n| `callback` | `Function|Controller` | no |  | `function(err, response)` oder ein Controller, um eine Datei zu streamen |\n| `filename` | `String` | no |  | Dateiname einer gestreamten Datei |\n\nReturns: `Promise|undefined` Eine Promise, wenn kein Callback angegeben ist\n\nSendet `data` per POST an `https://{default_tapi}.api.totaljs.com/{type}/`. Das Token ist standardmäßig `totalapi` (oder `secret_totalapi`). Ein `data`, das kein Objekt ist, wird als `{ value: data }` gesendet. Ohne Callback gibt die Funktion eine Promise zurück. Eine binäre Antwort geht als Stream an den Callback oder wird, wenn `callback` ein Controller ist, mit `filename` an den Client gesendet. Mit `allow_totalapi: false` funktioniert nur `check`; andere Aufrufe schlagen mit `totalapi_inactive` fehl.\n\nExample: Das Token prüfen\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nDas Total-API-Token.\n\nReturns: `String`\n\nWird von `TotalAPI()`, dem Provider `TotalAPI` von `API()` und dem Audit-Logger verwendet. `secret_totalapi` wird gelesen, wenn `totalapi` leer ist.\n\nExample: Das Token setzen\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nDie Serverregion von Total API.\n\nReturns: `String`\n\nAnfragen gehen an `https://{default_tapi}.api.totaljs.com/`. Standard: `eu`.\n\nExample: Region\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nSendet Audit-Logs an Total API.\n\nReturns: `Boolean`\n\nWenn `true` und ein Total-API-Token gesetzt ist, werden Audit-Einträge an den Total-API-Dienst `logger` gesendet statt an `DEF.onAudit()`. Standard: `false`.\n\nExample: Aktivieren\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDeklariert eine API-Route: eine einzige POST-URL, die Aktionen nach Namen ausführt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Deklaration der Route |\n| `fn` | `Function` | no |  | Ein eigener Handler mit dem Controller als `this` |\n| `flags` | `Array` | no |  | Flags der Route |\n\nReturns: `Object` Die Route\n\nDer Client sendet `{ \"schema\": \"name/param?query\", \"data\": {} }` per POST an die URL. Das Zeichen vor dem Namen legt fest, wie die Daten behandelt werden: `+` validiert sie wie `POST`, `#` wie `PATCH` (teilweise), `-` sendet keine wie `GET`. URL-Parameter können nach `:` einen Typ haben (`uid`, `number`, `guid`, `date`); der erste wird zu `$.id`. Ohne `*Schema --> action` führt die Route die Aktion mit demselben Namen aus (`--> name`). `+API` erfordert einen angemeldeten Benutzer und `-API` einen anonymen. Unbekannte Namen antworten mit `404`, ungültige Parameter mit `400`.\n\nExample: API-Routen\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: Eine Anfrage\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nEine Aktion einer API-Route, die von deiner eigenen Funktion verarbeitet wird.\n\nÜbergib statt `*Schema --> action` eine Funktion. Sie läuft mit dem Controller als `this`; `this.params` enthält die URL-Parameter, `this.body` das gesendete `{ schema, data }` und `this.id` den ersten Parameter. Antworte mit einer beliebigen Controller-Methode.\n\nExample: Eine eigene Aktion\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm3e3Zr60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Message Service y APIs","summary":"Funciones de TMS, el cliente TMS, API(), NEWAPI(), TotalAPI() y las rutas API.","markdown":"---\ntitle: Message Service y APIs\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service y APIs\n\n> Funciones de TMS, el cliente TMS, API(), NEWAPI(), TotalAPI() y las rutas API.\n\nLos canales TMS se declaran con `NEWPUBLISH()`, `NEWSUBSCRIBE()` y `NEWCALL()`, y otra app se conecta con `TMSCLIENT()`. `API()` llama a los proveedores registrados con `NEWAPI()`. La guía [Message Service y APIs](../../guides/message-service-and-apis/) explica cómo funcionan juntas las piezas; esta página es la referencia exacta.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDeclara un canal TMS en el que publica tu app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del canal |\n| `schema` | `String|Object` | no |  | Una declaración inline (`id:UID, name:String`), un objeto JSON schema con `$id`, o el nombre de un JSON schema o de un esquema de Total.js. Omítelo para eliminar el canal |\n\nReturns: `undefined`\n\nEl canal y su JSON schema se envían a todos los clientes TMS en el mensaje `meta`. Un nombre de esquema que no existe lanza un error. Sin `schema` (o con `null`), el canal se elimina. Volver a declarar un canal existente conserva su primer esquema.\n\nExample: Declarar un canal\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Eliminar un canal\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nEnvía un mensaje a los clientes TMS suscritos al canal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de un canal declarado con `NEWPUBLISH()` |\n| `data` | `Object` | yes |  | El mensaje |\n\nReturns: `undefined`\n\nSolo los clientes que anunciaron una suscripción a `name` reciben el mensaje. No hace nada cuando no hay ningún cliente TMS conectado o cuando `name` no se declaró con `NEWPUBLISH()`. Los datos no se validan en el servidor; `TMSCLIENT()` los convierte con el esquema del canal.\n\nExample: Publicar después de una inserción\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDeclara un canal TMS en el que publican los clientes y que recibe tu app.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del canal |\n| `schema` | `String|Object` | no |  | Una declaración inline (`id:UID, name:String`), un objeto JSON schema con `$id`, o el nombre de un JSON schema o de un esquema de Total.js. Omítelo para eliminar el canal |\n| `callback` | `Function` | no |  | Un handler `function(data, client)` |\n\nReturns: `undefined`\n\nLos mensajes entrantes del canal se validan con `schema`; los no válidos se descartan y los válidos van a los handlers añadidos con `SUBSCRIBE()`. `callback` es un atajo de `SUBSCRIBE(name, callback)`. Sin `schema`, el canal se elimina (sus handlers se mantienen).\n\nExample: Declarar un canal con un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nAñade un handler para los mensajes de un canal de suscripción TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del canal |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nEl handler recibe los datos validados y el cliente WebSocket que los envió. Un canal puede tener muchos handlers. Los mensajes solo llegan para los canales declarados con `NEWSUBSCRIBE()`. La app anuncia sus suscripciones a los clientes en el siguiente mensaje `meta`.\n\nExample: Añadir un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nElimina un handler o todos los handlers de un canal TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del canal |\n| `callback` | `Function` | no |  | El handler que se elimina |\n\nReturns: `Boolean` `true` cuando se eliminó algo\n\nCon `callback`, solo se elimina ese handler (pasa la misma función que diste a `SUBSCRIBE()`). Sin él, se eliminan todos los handlers del canal.\n\nExample: Eliminar un handler\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nRegistra una llamada remota TMS que los clientes pueden ejecutar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la llamada |\n| `schema` | `String|Object` | yes |  | Una declaración inline (`id:UID, name:String`), un objeto JSON schema con `$id`, el nombre de un JSON schema o de un esquema de Total.js, o `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` o un nombre de operación |\n\nReturns: `undefined`\n\nLos datos de una llamada se validan con `schema`; un error de validación vuelve al cliente. `callback(data, next, client)` responde con `next(err, response)`. En lugar de una función, `callback` puede ser el nombre de una operación. Sin callback y con un esquema como `*Orders --> create`, la llamada ejecuta esa acción del esquema. `NEWCALL(name, null)` elimina la llamada. Una llamada que no existe responde con el error `404`.\n\nExample: Una llamada con una función\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: Una llamada que ejecuta una acción de esquema\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nLos mensajes JSON que se intercambian en el endpoint TMS.\n\nReturns: `Object`\n\nCada mensaje es un objeto JSON con `type`:\n\n- `meta` (del servidor al cliente): `name`, `publish`, `subscribe` y `call` (arrays de `{ id, schema }`) y `subscribers` (canales a los que se suscribe la aplicación). Se envía tras conectar y un segundo después de cualquier cambio.\n- `publish` (del servidor al cliente): `{ id, data }`, enviado por `PUBLISH()`.\n- `subscribe` (del cliente al servidor): `{ id, data }`, un mensaje para un canal de `NEWSUBSCRIBE()`.\n- `subscribers` (del cliente al servidor): `{ subscribers: [names] }`, los canales que el cliente quiere recibir.\n- `call` (en ambos sentidos): `{ id, data, callbackid }`; la respuesta añade `success: true` o `error: true`.\n- `ping`: se responde con `pong`.\n\nSolo lo necesitas para escribir un cliente TMS sin `TMSCLIENT()`. Un cliente nuevo empieza con una lista de suscripciones vacía y recibe mensajes `publish` solo para los canales que enumera en `subscribers`.\n\nExample: Un cliente se suscribe y hace llamadas\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nEl token que deben enviar los clientes TMS.\n\nReturns: `String`\n\nLos clientes lo envían en la cabecera `x-token`. Un token incorrecto cierra la conexión con el código `4001`; más de cinco intentos fallidos desde una dirección IP la bloquean hasta el reinicio diario. Cambiar el token cierra las conexiones TMS. El valor también puede ser un número. Por defecto: vacío, se acepta a todos los clientes.\n\nExample: Proteger TMS\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nTamaño máximo de un mensaje TMS en kB.\n\nReturns: `Number`\n\nSe aplica a la ruta WebSocket del endpoint TMS (`default_tms_url`). Por defecto: `1024` (1 MB).\n\nExample: Permitir mensajes más grandes\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nOpción de schema.action() y NEWACTION() que declara un canal de publicación TMS.\n\nReturns: `Boolean|String`\n\nEl canal recibe el nombre de la acción: `Schema.action` para `schema.action()`, el nombre de la acción para `NEWACTION()`. `true` usa el `input` (o el `output`) de la acción como esquema del canal. Una cadena es su propio esquema inline; una cadena que empieza por `+` añade sus campos al input. Envía mensajes con `$.publish()`.\n\nExample: Publicar desde una acción\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nPublica un mensaje en el canal TMS de la acción actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El mensaje |\n\nReturns: `SchemaOptions` El mismo `$`, para encadenar\n\nFunciona en acciones declaradas con la opción `publish`; el nombre del canal es el ID de la acción. Como `PUBLISH()`, no hace nada sin un cliente TMS conectado. Los campos de `value` se copian a un objeto nuevo.\n\nExample: Publicar y responder\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nSe conecta al endpoint TMS de otra app Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL del endpoint TMS, por ejemplo `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | El `secret_tms` del servidor |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` El cliente TMS\n\nDevuelve un cliente WebSocket (consulta [WebSockets](../../guides/websockets/)) con los métodos adicionales `subscribe()`, `publish()` y `call()`. Una URL `http` se cambia a `ws` y el cliente se reconecta cuando el servidor cae. `token` se envía en la cabecera `x-token`. `callback(err, client, meta)` se ejecuta una vez, después del primer mensaje `meta`.\n\nExample: Conectar\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nRecibe los mensajes de un canal de publicación del servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de un canal declarado con `NEWPUBLISH()` en el servidor |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nLos datos se convierten con el esquema del canal que viene en `meta`, y los handlers solo se ejecutan para los canales que publica el servidor. El cliente envía su lista de suscripciones al servidor poco después de cada llamada y de nuevo después de reconectarse.\n\nExample: Suscribirse\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nEnvía un mensaje a un canal de suscripción del servidor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de un canal declarado con `NEWSUBSCRIBE()` en el servidor |\n| `data` | `Object` | yes |  | El mensaje |\n\nReturns: `undefined`\n\nEl servidor lo valida con el esquema de su canal `NEWSUBSCRIBE()`. No se envía nada mientras el cliente no está conectado.\n\nExample: Publicar\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nEjecuta una llamada remota registrada en el servidor con NEWCALL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre de la llamada |\n| `data` | `Object` | yes |  | Datos de la llamada |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Timeout en milisegundos |\n\nReturns: `Promise|undefined` Una promesa cuando no hay callback\n\n`callback(err, response)` recibe la respuesta; los errores del servidor llegan como un `ErrorBuilder`. Sin callback devuelve una promesa. Antes de que la conexión esté lista, falla con `TMS is offline`; si no hay respuesta a tiempo, con `408: Timeout`.\n\nExample: Llamar con un callback\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Llamar con await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true` cuando el cliente está conectado y ha recibido el meta.\n\nReturns: `Boolean`\n\nPasa a `false` cuando la conexión se cierra y vuelve a `true` después del siguiente `meta`.\n\nExample: Comprobar el estado\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nEl último mensaje meta recibido del servidor.\n\nReturns: `Object`\n\nContiene el `name` del servidor y las listas `publish`, `subscribe` y `call` con JSON schemas. Consulta los mensajes TMS.\n\nExample: Listar las llamadas remotas\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nSe emite cada vez que el servidor envía su meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | El mensaje meta |\n\nEl servidor envía el meta después de conectar, después de reconectar y después de cualquier cambio en sus canales o llamadas.\n\nExample: Vigilar los cambios\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nSe emite después de cada mensaje meta, cuando el cliente está listo.\n\nÚsalo para ejecutar código después de cada reconexión; el callback de `TMSCLIENT()` solo se ejecuta la primera vez.\n\nExample: Después de cada conexión\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nRegistra un proveedor de API que usa API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del proveedor, varios separados por comas, o `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Omítelo para eliminar el proveedor |\n\nReturns: `undefined`\n\n`callback(opt, next)` se ejecuta para cada llamada `API()` con este nombre, con el objeto de llamada como `this`. `opt` tiene `name`, `schema`, `data`, `controller`, y `files` y `output` cuando están establecidos. Responde con `next(err, response)`. `name` no distingue mayúsculas de minúsculas, puede enumerar varios nombres separados por comas, y `*` registra un proveedor de reserva para los nombres desconocidos. Un nombre sin `callback` elimina el proveedor. El proveedor `TotalAPI` (alias `TAPI`) está registrado por defecto.\n\nExample: Un proveedor personalizado\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nEnvía una petición a un proveedor de API registrado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nombre del proveedor, por ejemplo `TotalAPI` |\n| `schema` | `String` | yes |  | El endpoint u operación del proveedor |\n| `data` | `Object` | no |  | Datos de la petición |\n| `$` | `Object` | no |  | Un controlador o `$`, que se pasa al proveedor como `opt.controller` |\n\nReturns: `APICall` El objeto de llamada\n\nDevuelve un objeto de llamada. La petición empieza en el siguiente tick, así que encadena las opciones y el callback de inmediato. Sin un proveedor para `name` (y sin proveedor `*`), la llamada falla con `API is not initialized`.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Dentro de una acción\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nEstablece el callback de la llamada a la API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)`, o `$` |\n\nReturns: `APICall` La llamada, para encadenar.\n\n`fn(err, response)`. Pasa `$` (o un objeto con `callback`) para responder a una acción con el resultado.\n\nExample: Con $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nDevuelve una promesa con la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Un objeto con `invalid()`, como `$` |\n\nReturns: `Promise` La respuesta\n\nCon `$`, un error se envía con `$.invalid()` y la promesa nunca se resuelve; sin él, la promesa se rechaza con un error llamado `API(name --> schema)`.\n\nExample: Esperar la respuesta con await\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nEstablece el formato de salida de la respuesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El formato de salida |\n\nReturns: `APICall` La llamada, para encadenar.\n\nEl proveedor lo lee como `opt.output`. El proveedor `TotalAPI` admite `json` (por defecto), `html`, `text`, `plain`, `base64`, `buffer` o `binary`, `stream`, y `#name id filename` para guardar la respuesta en un FileStorage.\n\nExample: Guardar la respuesta en FileStorage\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nAñade un archivo a la petición.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Nombre del archivo |\n| `path` | `String` | yes |  | Ruta del archivo en disco |\n| `name` | `String` | no | `'file' + index` | Nombre del campo del formulario |\n\nReturns: `APICall` La llamada, para encadenar.\n\nAñade `{ name, filename, path }` a `opt.files`. El proveedor `TotalAPI` envía entonces los datos y los archivos como una petición multipart.\n\nExample: Enviar un archivo\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nConvierte una respuesta vacía en un error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | El error |\n| `reverse` | `Boolean` | no | `false` | Falla cuando la respuesta no está vacía |\n\nReturns: `APICall` La llamada, para encadenar.\n\nUna respuesta vacía (o un array vacío) se convierte en `err`. Con `reverse`, es una respuesta no vacía la que se convierte en el error. Alias: `api.err()`.\n\nExample: Exigir una respuesta\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nEjecuta una función cuando la llamada falla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` La llamada, para encadenar.\n\n`fn(err)` se ejecuta además del callback.\n\nExample: Registrar errores\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nEjecuta una función con la respuesta cuando la llamada tiene éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` La llamada, para encadenar.\n\n`fn(response)` se ejecuta además del callback, solo si no hay error.\n\nExample: Usar la respuesta\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nEscribe una entrada en el registro de auditoría cuando la llamada tiene éxito.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | El `$` de una acción u operación |\n| `message` | `String` | no |  | El mensaje de auditoría |\n| `type` | `String` | no |  | Tipo de la entrada |\n\nReturns: `APICall` La llamada, para encadenar.\n\nLlama a `$.audit(message, type)`. Las variables del mensaje se rellenan con los datos de la llamada mediante `$.variables()`.\n\nExample: Auditar un pago\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nPasa un controlador al proveedor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Un controlador o `$` |\n\nReturns: `APICall` La llamada, para encadenar.\n\nEstablece `opt.controller` en `$.controller` (o en el propio `$`).\n\nExample: Pasar el controlador\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nRegistra el resultado de la llamada en la consola.\n\nReturns: `APICall` La llamada, para encadenar.\n\nImprime el nombre del proveedor, el esquema, el error y la respuesta.\n\nExample: Depurar una llamada\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nEnvía una petición a Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Token de Total API |\n| `type` | `String` | yes |  | El servicio de Total API |\n| `data` | `Object` | yes |  | Datos de la petición |\n| `callback` | `Function|Controller` | no |  | `function(err, response)`, o un controlador para enviar un archivo como stream |\n| `filename` | `String` | no |  | Nombre del archivo enviado como stream |\n\nReturns: `Promise|undefined` Una promesa cuando no hay callback\n\nEnvía `data` por POST a `https://{default_tapi}.api.totaljs.com/{type}/`. El token es por defecto `totalapi` (o `secret_totalapi`). Un `data` que no es un objeto se envía como `{ value: data }`. Sin callback devuelve una promesa. Una respuesta binaria llega al callback como un stream o, cuando `callback` es un controlador, se envía al cliente con `filename`. Con `allow_totalapi: false`, solo funciona `check`; las demás llamadas fallan con `totalapi_inactive`.\n\nExample: Comprobar el token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nEl token de Total API.\n\nReturns: `String`\n\nLo usan `TotalAPI()`, el proveedor `TotalAPI` de `API()` y el registro de auditoría. Se lee `secret_totalapi` cuando `totalapi` está vacío.\n\nExample: Establecer el token\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nLa región del servidor de Total API.\n\nReturns: `String`\n\nLas peticiones van a `https://{default_tapi}.api.totaljs.com/`. Por defecto: `eu`.\n\nExample: Región\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nEnvía los registros de auditoría a Total API.\n\nReturns: `Boolean`\n\nCuando es `true` y hay un token de Total API establecido, las entradas de auditoría se envían al servicio `logger` de Total API en lugar de a `DEF.onAudit()`. Por defecto: `false`.\n\nExample: Activar\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDeclara una ruta API: una sola URL POST que ejecuta acciones por nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La declaración de la ruta |\n| `fn` | `Function` | no |  | Un handler personalizado con el controlador como `this` |\n| `flags` | `Array` | no |  | Flags de la ruta |\n\nReturns: `Object` La ruta\n\nEl cliente envía por POST `{ \"schema\": \"name/param?query\", \"data\": {} }` a la URL. El signo antes del nombre establece cómo se gestionan los datos: `+` los valida como `POST`, `#` como `PATCH` (parcial), `-` no envía ninguno, como `GET`. Los parámetros de la URL pueden tener un tipo después de `:` (`uid`, `number`, `guid`, `date`); el primero se convierte en `$.id`. Sin `*Schema --> action`, la ruta ejecuta la acción con el mismo nombre (`--> name`). `+API` requiere un usuario con sesión iniciada y `-API` uno anónimo. Los nombres desconocidos responden `404` y los parámetros no válidos `400`.\n\nExample: Rutas API\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: Una petición\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nUna acción de ruta API gestionada por tu propia función.\n\nEn lugar de `*Schema --> action`, pasa una función. Se ejecuta con el controlador como `this`; `this.params` contiene los parámetros de la URL, `this.body` el `{ schema, data }` enviado y `this.id` el primer parámetro. Responde con cualquier método del controlador.\n\nExample: Una acción personalizada\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm3e3Zr60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Message Service et API","summary":"Les fonctions TMS, le client TMS, API(), NEWAPI(), TotalAPI() et les routes API.","markdown":"---\ntitle: Message Service et API\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service et API\n\n> Les fonctions TMS, le client TMS, API(), NEWAPI(), TotalAPI() et les routes API.\n\nLes canaux TMS sont déclarés avec `NEWPUBLISH()`, `NEWSUBSCRIBE()` et `NEWCALL()`, et une autre application se connecte avec `TMSCLIENT()`. `API()` appelle les fournisseurs enregistrés avec `NEWAPI()`. Le guide [Message Service et API](../../guides/message-service-and-apis/) explique comment ces éléments fonctionnent ensemble ; cette page est la référence exacte.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDéclare un canal TMS sur lequel ton application publie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du canal |\n| `schema` | `String|Object` | no |  | Une déclaration inline (`id:UID, name:String`), un objet de schéma JSON avec `$id`, ou le nom d'un schéma JSON ou d'un schéma Total.js. Omets-le pour supprimer le canal |\n\nReturns: `undefined`\n\nLe canal et son schéma JSON sont envoyés à chaque client TMS dans le message `meta`. Un nom de schéma qui n'existe pas lève une erreur. Sans `schema` (ou avec `null`), le canal est supprimé. Redéclarer un canal existant conserve son premier schéma.\n\nExample: Déclarer un canal\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Supprimer un canal\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nEnvoie un message aux clients TMS abonnés au canal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom d'un canal déclaré avec `NEWPUBLISH()` |\n| `data` | `Object` | yes |  | Le message |\n\nReturns: `undefined`\n\nSeuls les clients ayant annoncé un abonnement à `name` reçoivent le message. Elle ne fait rien lorsqu'aucun client TMS n'est connecté ou lorsque `name` n'a pas été déclaré avec `NEWPUBLISH()`. Les données ne sont pas validées sur le serveur ; `TMSCLIENT()` les convertit avec le schéma du canal.\n\nExample: Publier après une insertion\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDéclare un canal TMS sur lequel les clients publient et que ton application reçoit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du canal |\n| `schema` | `String|Object` | no |  | Une déclaration inline (`id:UID, name:String`), un objet de schéma JSON avec `$id`, ou le nom d'un schéma JSON ou d'un schéma Total.js. Omets-le pour supprimer le canal |\n| `callback` | `Function` | no |  | Un handler `function(data, client)` |\n\nReturns: `undefined`\n\nLes messages entrants du canal sont validés avec `schema` ; les messages invalides sont abandonnés et les messages valides vont aux handlers ajoutés avec `SUBSCRIBE()`. `callback` est un raccourci pour `SUBSCRIBE(name, callback)`. Sans `schema`, le canal est supprimé (ses handlers restent).\n\nExample: Déclarer un canal avec un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nAjoute un handler pour les messages d'un canal d'abonnement TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du canal |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nLe handler reçoit les données validées et le client WebSocket qui les a envoyées. Un canal peut avoir plusieurs handlers. Les messages n'arrivent que pour les canaux déclarés avec `NEWSUBSCRIBE()`. L'application annonce ses abonnements aux clients dans le message `meta` suivant.\n\nExample: Ajouter un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nSupprime un handler ou tous les handlers d'un canal TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du canal |\n| `callback` | `Function` | no |  | Le handler à supprimer |\n\nReturns: `Boolean` `true` lorsque quelque chose a été supprimé\n\nAvec `callback`, seul ce handler est supprimé (passe la même fonction que celle donnée à `SUBSCRIBE()`). Sans lui, tous les handlers du canal sont supprimés.\n\nExample: Supprimer un handler\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nEnregistre un appel distant TMS que les clients peuvent exécuter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'appel |\n| `schema` | `String|Object` | yes |  | Une déclaration inline (`id:UID, name:String`), un objet de schéma JSON avec `$id`, ou le nom d'un schéma JSON ou d'un schéma Total.js, ou `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` ou un nom d'opération |\n\nReturns: `undefined`\n\nLes données d'un appel sont validées avec `schema` ; une erreur de validation est renvoyée au client. `callback(data, next, client)` répond avec `next(err, response)`. Au lieu d'une fonction, `callback` peut être le nom d'une opération. Sans callback et avec un schéma comme `*Orders --> create`, l'appel exécute cette action de schéma. `NEWCALL(name, null)` supprime l'appel. Un appel qui n'existe pas répond avec l'erreur `404`.\n\nExample: Un appel avec une fonction\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: Un appel qui exécute une action de schéma\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nLes messages JSON échangés sur le point d'accès TMS.\n\nReturns: `Object`\n\nChaque message est un objet JSON avec `type` :\n\n- `meta` (du serveur vers le client) : `name`, `publish`, `subscribe` et `call` (tableaux de `{ id, schema }`) et `subscribers` (canaux auxquels l'application est abonnée). Envoyé après la connexion et une seconde après chaque modification.\n- `publish` (du serveur vers le client) : `{ id, data }`, envoyé par `PUBLISH()`.\n- `subscribe` (du client vers le serveur) : `{ id, data }`, un message pour un canal `NEWSUBSCRIBE()`.\n- `subscribers` (du client vers le serveur) : `{ subscribers: [names] }`, les canaux que le client veut recevoir.\n- `call` (dans les deux sens) : `{ id, data, callbackid }` ; la réponse ajoute `success: true` ou `error: true`.\n- `ping` : la réponse est `pong`.\n\nTu n'en as besoin que pour écrire un client TMS sans `TMSCLIENT()`. Un nouveau client démarre avec une liste d'abonnements vide et ne reçoit des messages `publish` que pour les canaux qu'il liste dans `subscribers`.\n\nExample: Un client s'abonne et effectue des appels\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nLe jeton que les clients TMS doivent envoyer.\n\nReturns: `String`\n\nLes clients l'envoient dans l'en-tête `x-token`. Un jeton erroné ferme la connexion avec le code `4001` ; plus de cinq tentatives échouées depuis une adresse IP la bloquent jusqu'à la réinitialisation quotidienne. Changer le jeton ferme les connexions TMS. La valeur peut aussi être un nombre. Par défaut : vide, tous les clients sont acceptés.\n\nExample: Protéger TMS\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nTaille maximale d'un message TMS en ko.\n\nReturns: `Number`\n\nAppliquée à la route WebSocket du point d'accès TMS (`default_tms_url`). Par défaut : `1024` (1 Mo).\n\nExample: Autoriser des messages plus gros\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nOption de schema.action() et de NEWACTION() qui déclare un canal de publication TMS.\n\nReturns: `Boolean|String`\n\nLe canal porte le nom de l'action : `Schema.action` pour `schema.action()`, le nom de l'action pour `NEWACTION()`. `true` utilise l'`input` (ou l'`output`) de l'action comme schéma du canal. Une chaîne est son propre schéma inline ; une chaîne qui commence par `+` ajoute ses champs à l'input. Envoie des messages avec `$.publish()`.\n\nExample: Publier depuis une action\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nPublie un message sur le canal TMS de l'action courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Le message |\n\nReturns: `SchemaOptions` Le même `$`, pour le chaînage\n\nFonctionne dans les actions déclarées avec l'option `publish` ; le nom du canal est l'ID de l'action. Comme `PUBLISH()`, elle ne fait rien sans client TMS connecté. Les champs de `value` sont copiés dans un nouvel objet.\n\nExample: Publier et répondre\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nSe connecte au point d'accès TMS d'une autre application Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL du point d'accès TMS, par exemple `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | Le `secret_tms` du serveur |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` Le client TMS\n\nRenvoie un client WebSocket (voir [WebSockets](../../guides/websockets/)) avec les méthodes supplémentaires `subscribe()`, `publish()` et `call()`. Une URL `http` est changée en `ws` et le client se reconnecte lorsque le serveur tombe. `token` est envoyé dans l'en-tête `x-token`. `callback(err, client, meta)` s'exécute une seule fois, après le premier message `meta`.\n\nExample: Se connecter\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nReçoit les messages d'un canal de publication du serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom d'un canal déclaré avec `NEWPUBLISH()` sur le serveur |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nLes données sont converties avec le schéma du canal issu de `meta`, et les handlers ne s'exécutent que pour les canaux que le serveur publie. Le client envoie sa liste d'abonnements au serveur peu après chaque appel, puis à nouveau après une reconnexion.\n\nExample: S'abonner\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nEnvoie un message vers un canal d'abonnement du serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom d'un canal déclaré avec `NEWSUBSCRIBE()` sur le serveur |\n| `data` | `Object` | yes |  | Le message |\n\nReturns: `undefined`\n\nLe serveur le valide avec le schéma de son canal `NEWSUBSCRIBE()`. Rien n'est envoyé tant que le client n'est pas connecté.\n\nExample: Publier\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nExécute un appel distant enregistré sur le serveur avec NEWCALL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom de l'appel |\n| `data` | `Object` | yes |  | Données de l'appel |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Timeout en millisecondes |\n\nReturns: `Promise|undefined` Une promesse lorsqu'il n'y a pas de callback\n\n`callback(err, response)` reçoit la réponse ; les erreurs du serveur arrivent sous forme d'`ErrorBuilder`. Sans callback, elle renvoie une promesse. Avant que la connexion soit prête, elle échoue avec `TMS is offline` ; sans réponse à temps, avec `408: Timeout`.\n\nExample: Appel avec un callback\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Appel avec await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true` lorsque le client est connecté et a reçu le meta.\n\nReturns: `Boolean`\n\nElle devient `false` lorsque la connexion se ferme, puis à nouveau `true` après le `meta` suivant.\n\nExample: Vérifier l'état\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nLe dernier message meta reçu du serveur.\n\nReturns: `Object`\n\nIl contient le `name` du serveur et les listes `publish`, `subscribe` et `call` avec les schémas JSON. Voir les messages TMS.\n\nExample: Lister les appels distants\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nÉmis chaque fois que le serveur envoie son meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Le message meta |\n\nLe serveur envoie le meta après la connexion, après une reconnexion et après toute modification de ses canaux ou de ses appels.\n\nExample: Surveiller les modifications\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nÉmis après chaque message meta, lorsque le client est prêt.\n\nUtilise-le pour exécuter du code après chaque reconnexion ; le callback de `TMSCLIENT()` ne s'exécute que la première fois.\n\nExample: Après chaque connexion\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nEnregistre un fournisseur d'API utilisé par API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du fournisseur, plusieurs séparés par des virgules, ou `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Omets-le pour supprimer le fournisseur |\n\nReturns: `undefined`\n\n`callback(opt, next)` s'exécute pour chaque appel `API()` portant ce nom, avec l'objet d'appel comme `this`. `opt` contient `name`, `schema`, `data`, `controller`, ainsi que `files` et `output` s'ils sont définis. Réponds avec `next(err, response)`. `name` n'est pas sensible à la casse, peut lister plusieurs noms séparés par des virgules, et `*` enregistre un fournisseur de repli pour les noms inconnus. Un nom sans `callback` supprime le fournisseur. Le fournisseur `TotalAPI` (alias `TAPI`) est enregistré par défaut.\n\nExample: Un fournisseur personnalisé\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nEnvoie une requête à un fournisseur d'API enregistré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nom du fournisseur, par exemple `TotalAPI` |\n| `schema` | `String` | yes |  | Le point d'accès ou l'opération du fournisseur |\n| `data` | `Object` | no |  | Données de la requête |\n| `$` | `Object` | no |  | Un contrôleur ou `$`, passé au fournisseur comme `opt.controller` |\n\nReturns: `APICall` L'objet d'appel\n\nRenvoie un objet d'appel. La requête démarre au tick suivant : chaîne donc les options et le callback immédiatement. Sans fournisseur pour `name` (et sans fournisseur `*`), l'appel échoue avec `API is not initialized`.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Dans une action\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nDéfinit le callback de l'appel d'API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)`, ou `$` |\n\nReturns: `APICall` L'appel, pour le chaînage\n\n`fn(err, response)`. Passe `$` (ou un objet avec `callback`) pour répondre à une action avec le résultat.\n\nExample: Avec $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nRetourne une promesse avec la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Un objet avec `invalid()`, comme `$` |\n\nReturns: `Promise` La réponse\n\nAvec `$`, une erreur est envoyée avec `$.invalid()` et la promesse n'est jamais résolue ; sans lui, la promesse est rejetée avec une erreur nommée `API(name --> schema)`.\n\nExample: Attendre la réponse\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nDéfinit le format de sortie de la réponse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Le format de sortie |\n\nReturns: `APICall` L'appel, pour le chaînage\n\nLe fournisseur le lit dans `opt.output`. Le fournisseur `TotalAPI` prend en charge `json` (par défaut), `html`, `text`, `plain`, `base64`, `buffer` ou `binary`, `stream`, et `#name id filename` pour enregistrer la réponse dans un FileStorage.\n\nExample: Enregistrer la réponse dans FileStorage\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nAjoute un fichier à la requête.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Nom du fichier |\n| `path` | `String` | yes |  | Chemin du fichier sur le disque |\n| `name` | `String` | no | `'file' + index` | Nom du champ de formulaire |\n\nReturns: `APICall` L'appel, pour le chaînage\n\nAjoute `{ name, filename, path }` à `opt.files`. Le fournisseur `TotalAPI` envoie alors les données et les fichiers sous forme de requête multipart.\n\nExample: Envoyer un fichier\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nTransforme une réponse vide en erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | L'erreur |\n| `reverse` | `Boolean` | no | `false` | Échouer lorsque la réponse n'est pas vide |\n\nReturns: `APICall` L'appel, pour le chaînage\n\nUne réponse vide (ou un tableau vide) devient `err`. Avec `reverse`, c'est au contraire une réponse non vide qui devient l'erreur. Alias : `api.err()`.\n\nExample: Exiger une réponse\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nExécute une fonction lorsque l'appel échoue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` L'appel, pour le chaînage\n\n`fn(err)` s'exécute en plus du callback.\n\nExample: Journaliser les erreurs\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nExécute une fonction avec la réponse lorsque l'appel réussit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` L'appel, pour le chaînage\n\n`fn(response)` s'exécute en plus du callback, uniquement en l'absence d'erreur.\n\nExample: Utiliser la réponse\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nÉcrit une entrée dans le journal d'audit lorsque l'appel réussit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Le `$` d'une action ou d'une opération |\n| `message` | `String` | no |  | Le message d'audit |\n| `type` | `String` | no |  | Type de l'entrée |\n\nReturns: `APICall` L'appel, pour le chaînage\n\nAppelle `$.audit(message, type)`. Les variables du message sont remplies à partir des données de l'appel avec `$.variables()`.\n\nExample: Auditer un paiement\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nPasse un contrôleur au fournisseur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Un contrôleur ou `$` |\n\nReturns: `APICall` L'appel, pour le chaînage\n\nDéfinit `opt.controller` à `$.controller` (ou à `$` lui-même).\n\nExample: Passer le contrôleur\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nAffiche le résultat de l'appel dans la console.\n\nReturns: `APICall` L'appel, pour le chaînage\n\nAffiche le nom du fournisseur, le schéma, l'erreur et la réponse.\n\nExample: Déboguer un appel\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nEnvoie une requête à Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Jeton Total API |\n| `type` | `String` | yes |  | Le service Total API |\n| `data` | `Object` | yes |  | Données de la requête |\n| `callback` | `Function|Controller` | no |  | `function(err, response)`, ou un contrôleur pour envoyer un fichier en stream |\n| `filename` | `String` | no |  | Nom du fichier envoyé en stream |\n\nReturns: `Promise|undefined` Une promesse lorsqu'il n'y a pas de callback\n\nEnvoie `data` en POST à `https://{default_tapi}.api.totaljs.com/{type}/`. Le jeton vaut par défaut `totalapi` (ou `secret_totalapi`). Une valeur `data` qui n'est pas un objet est envoyée sous la forme `{ value: data }`. Sans callback, elle renvoie une promesse. Une réponse binaire est passée au callback sous forme de stream ou, lorsque `callback` est un contrôleur, envoyée au client avec `filename`. Avec `allow_totalapi: false`, seul `check` fonctionne ; les autres appels échouent avec `totalapi_inactive`.\n\nExample: Vérifier le jeton\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nLe jeton Total API.\n\nReturns: `String`\n\nUtilisé par `TotalAPI()`, le fournisseur `TotalAPI` de `API()` et le journal d'audit. `secret_totalapi` est lu lorsque `totalapi` est vide.\n\nExample: Définir le jeton\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nLa région du serveur Total API.\n\nReturns: `String`\n\nLes requêtes vont vers `https://{default_tapi}.api.totaljs.com/`. Par défaut : `eu`.\n\nExample: Région\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nEnvoie les journaux d'audit à Total API.\n\nReturns: `Boolean`\n\nLorsque la valeur est `true` et qu'un jeton Total API est défini, les entrées d'audit sont envoyées au service `logger` de Total API au lieu de `DEF.onAudit()`. Par défaut : `false`.\n\nExample: Activer\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDéclare une route API : une seule URL POST qui exécute des actions par leur nom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La déclaration de la route |\n| `fn` | `Function` | no |  | Un handler personnalisé avec le contrôleur comme `this` |\n| `flags` | `Array` | no |  | Flags de la route |\n\nReturns: `Object` La route\n\nLe client envoie `{ \"schema\": \"name/param?query\", \"data\": {} }` en POST à l'URL. Le signe placé avant le nom définit le traitement des données : `+` les valide comme `POST`, `#` comme `PATCH` (partiel), `-` n'en envoie aucune comme `GET`. Les paramètres d'URL peuvent avoir un type après `:` (`uid`, `number`, `guid`, `date`) ; le premier devient `$.id`. Sans `*Schema --> action`, la route exécute l'action du même nom (`--> name`). `+API` exige un utilisateur connecté et `-API` un utilisateur anonyme. Les noms inconnus répondent `404`, les paramètres invalides `400`.\n\nExample: Routes API\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: Une requête\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nUne action de route API traitée par ta propre fonction.\n\nAu lieu de `*Schema --> action`, passe une fonction. Elle s'exécute avec le contrôleur comme `this` ; `this.params` contient les paramètres d'URL, `this.body` le `{ schema, data }` envoyé et `this.id` le premier paramètre. Réponds avec n'importe quelle méthode du contrôleur.\n\nExample: Une action personnalisée\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm3e3Zr60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Message Service e API","summary":"Le funzioni TMS, il client TMS, API(), NEWAPI(), TotalAPI() e le route API.","markdown":"---\ntitle: Message Service e API\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service e API\n\n> Le funzioni TMS, il client TMS, API(), NEWAPI(), TotalAPI() e le route API.\n\nI canali TMS si dichiarano con `NEWPUBLISH()`, `NEWSUBSCRIBE()` e `NEWCALL()`, e un'altra app si connette con `TMSCLIENT()`. `API()` chiama i provider registrati con `NEWAPI()`. La guida [Message Service e API](../../guides/message-service-and-apis/) spiega come le parti lavorano insieme; questa pagina è il riferimento esatto.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDichiara un canale TMS su cui la tua app pubblica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del canale |\n| `schema` | `String|Object` | no |  | Una dichiarazione inline (`id:UID, name:String`), un oggetto JSON schema con `$id`, oppure il nome di un JSON schema o di uno schema Total.js. Omettilo per rimuovere il canale |\n\nReturns: `undefined`\n\nIl canale e il suo schema JSON vengono inviati a ogni client TMS nel messaggio `meta`. Un nome di schema che non esiste genera un errore. Senza `schema` (o con `null`), il canale viene rimosso. Ridichiarare un canale esistente mantiene il suo primo schema.\n\nExample: Dichiarare un canale\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Rimuovere un canale\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nInvia un messaggio ai client TMS iscritti al canale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome di un canale dichiarato con `NEWPUBLISH()` |\n| `data` | `Object` | yes |  | Il messaggio |\n\nReturns: `undefined`\n\nSolo i client che hanno annunciato un'iscrizione a `name` ricevono il messaggio. Non fa nulla quando nessun client TMS è connesso o quando `name` non è stato dichiarato con `NEWPUBLISH()`. I dati non vengono validati sul server; `TMSCLIENT()` li converte con lo schema del canale.\n\nExample: Pubblicare dopo un inserimento\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDichiara un canale TMS su cui i client pubblicano e che la tua app riceve.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del canale |\n| `schema` | `String|Object` | no |  | Una dichiarazione inline (`id:UID, name:String`), un oggetto JSON schema con `$id`, oppure il nome di un JSON schema o di uno schema Total.js. Omettilo per rimuovere il canale |\n| `callback` | `Function` | no |  | Un handler `function(data, client)` |\n\nReturns: `undefined`\n\nI messaggi in arrivo sul canale vengono validati con `schema`; quelli non validi vengono scartati e quelli validi vanno agli handler aggiunti con `SUBSCRIBE()`. `callback` è una scorciatoia per `SUBSCRIBE(name, callback)`. Senza `schema`, il canale viene rimosso (i suoi handler restano).\n\nExample: Dichiarare un canale con un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nAggiunge un handler per i messaggi di un canale di iscrizione TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del canale |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nL'handler riceve i dati validati e il client WebSocket che li ha inviati. Un canale può avere molti handler. I messaggi arrivano solo per i canali dichiarati con `NEWSUBSCRIBE()`. L'app annuncia le sue iscrizioni ai client nel messaggio `meta` successivo.\n\nExample: Aggiungere un handler\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nRimuove un handler o tutti gli handler di un canale TMS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del canale |\n| `callback` | `Function` | no |  | L'handler da rimuovere |\n\nReturns: `Boolean` `true` quando è stato rimosso qualcosa\n\nCon `callback`, viene rimosso solo quell'handler (passa la stessa funzione che hai dato a `SUBSCRIBE()`). Senza, vengono rimossi tutti gli handler del canale.\n\nExample: Rimuovere un handler\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nRegistra una chiamata remota TMS che i client possono eseguire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della chiamata |\n| `schema` | `String|Object` | yes |  | Una dichiarazione inline (`id:UID, name:String`), un oggetto JSON schema con `$id`, il nome di un JSON schema o di uno schema Total.js, oppure `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` o il nome di un'operazione |\n\nReturns: `undefined`\n\nI dati di una chiamata vengono validati con `schema`; un errore di validazione torna al client. `callback(data, next, client)` risponde con `next(err, response)`. Invece di una funzione, `callback` può essere il nome di un'operazione. Senza callback e con uno schema come `*Orders --> create`, la chiamata esegue quell'azione dello schema. `NEWCALL(name, null)` rimuove la chiamata. Una chiamata che non esiste risponde con l'errore `404`.\n\nExample: Una chiamata con una funzione\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: Una chiamata che esegue un'azione dello schema\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nI messaggi JSON scambiati sull'endpoint TMS.\n\nReturns: `Object`\n\nOgni messaggio è un oggetto JSON con `type`:\n\n- `meta` (dal server al client): `name`, `publish`, `subscribe` e `call` (array di `{ id, schema }`) e `subscribers` (i canali a cui l'app è iscritta). Inviato dopo la connessione e un secondo dopo ogni modifica.\n- `publish` (dal server al client): `{ id, data }`, inviato da `PUBLISH()`.\n- `subscribe` (dal client al server): `{ id, data }`, un messaggio per un canale `NEWSUBSCRIBE()`.\n- `subscribers` (dal client al server): `{ subscribers: [names] }`, i canali che il client vuole ricevere.\n- `call` (in entrambe le direzioni): `{ id, data, callbackid }`; la risposta aggiunge `success: true` o `error: true`.\n- `ping`: riceve come risposta `pong`.\n\nTi serve solo per scrivere un client TMS senza `TMSCLIENT()`. Un nuovo client parte con un elenco vuoto di iscrizioni e riceve i messaggi `publish` solo per i canali che elenca in `subscribers`.\n\nExample: Un client si iscrive e chiama\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nIl token che i client TMS devono inviare.\n\nReturns: `String`\n\nI client lo inviano nell'header `x-token`. Un token errato chiude la connessione con il codice `4001`; più di cinque tentativi falliti da un indirizzo IP lo bloccano fino al reset giornaliero. Cambiare il token chiude le connessioni TMS. Il valore può anche essere un numero. Predefinito: vuoto, ogni client viene accettato.\n\nExample: Proteggere TMS\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nDimensione massima di un messaggio TMS in kB.\n\nReturns: `Number`\n\nApplicata alla route WebSocket dell'endpoint TMS (`default_tms_url`). Predefinito: `1024` (1 MB).\n\nExample: Consentire messaggi più grandi\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nOpzione di schema.action() e NEWACTION() che dichiara un canale di pubblicazione TMS.\n\nReturns: `Boolean|String`\n\nIl canale prende il nome dall'azione: `Schema.action` per `schema.action()`, il nome dell'azione per `NEWACTION()`. `true` usa l'`input` (o l'`output`) dell'azione come schema del canale. Una stringa è un proprio schema inline; una stringa che inizia con `+` aggiunge i suoi campi all'input. Invia i messaggi con `$.publish()`.\n\nExample: Pubblicare da un'azione\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nPubblica un messaggio sul canale TMS dell'azione corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il messaggio |\n\nReturns: `SchemaOptions` Lo stesso `$`, per concatenare le chiamate\n\nFunziona nelle azioni dichiarate con l'opzione `publish`; il nome del canale è l'ID dell'azione. Come `PUBLISH()`, non fa nulla senza un client TMS connesso. I campi di `value` vengono copiati in un nuovo oggetto.\n\nExample: Pubblicare e rispondere\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nSi connette all'endpoint TMS di un'altra app Total.js.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL dell'endpoint TMS, per esempio `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | Il `secret_tms` del server |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` Il client TMS\n\nRestituisce un client WebSocket (vedi [WebSocket](../../guides/websockets/)) con i metodi aggiuntivi `subscribe()`, `publish()` e `call()`. Un URL `http` viene cambiato in `ws` e il client si riconnette quando il server va giù. `token` viene inviato nell'header `x-token`. `callback(err, client, meta)` viene eseguita una volta, dopo il primo messaggio `meta`.\n\nExample: Connettersi\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nRiceve i messaggi di un canale di pubblicazione del server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome di un canale dichiarato con `NEWPUBLISH()` sul server |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nI dati vengono convertiti con lo schema del canale preso da `meta`, e gli handler vengono eseguiti solo per i canali che il server pubblica. Il client invia al server l'elenco delle sue iscrizioni poco dopo ogni chiamata e di nuovo dopo la riconnessione.\n\nExample: Iscriversi\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nInvia un messaggio a un canale di iscrizione del server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome di un canale dichiarato con `NEWSUBSCRIBE()` sul server |\n| `data` | `Object` | yes |  | Il messaggio |\n\nReturns: `undefined`\n\nIl server lo valida con lo schema del suo canale `NEWSUBSCRIBE()`. Finché il client non è connesso non viene inviato nulla.\n\nExample: Pubblicare\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nEsegue una chiamata remota registrata sul server con NEWCALL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome della chiamata |\n| `data` | `Object` | yes |  | Dati della chiamata |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Timeout in millisecondi |\n\nReturns: `Promise|undefined` Una promise quando non c'è callback\n\n`callback(err, response)` riceve la risposta; gli errori del server arrivano come `ErrorBuilder`. Senza callback restituisce una promise. Prima che la connessione sia pronta, fallisce con `TMS is offline`; senza risposta in tempo, con `408: Timeout`.\n\nExample: Chiamata con una callback\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Chiamata con await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true` quando il client è connesso e ha ricevuto il meta.\n\nReturns: `Boolean`\n\nDiventa `false` quando la connessione si chiude e di nuovo `true` dopo il `meta` successivo.\n\nExample: Controllare lo stato\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nL'ultimo messaggio meta ricevuto dal server.\n\nReturns: `Object`\n\nContiene il `name` del server e gli elenchi `publish`, `subscribe` e `call` con gli schemi JSON. Vedi i messaggi TMS.\n\nExample: Elencare le chiamate remote\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nEmesso ogni volta che il server invia il suo meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Il messaggio meta |\n\nIl server invia il meta dopo la connessione, dopo la riconnessione e dopo ogni modifica dei suoi canali o delle sue chiamate.\n\nExample: Osservare le modifiche\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nEmesso dopo ogni messaggio meta, quando il client è pronto.\n\nUsalo per eseguire codice dopo ogni riconnessione; la callback di `TMSCLIENT()` viene eseguita solo la prima volta.\n\nExample: Dopo ogni connessione\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nRegistra un provider di API usato da API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del provider, più nomi separati da virgole, oppure `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Omettila per rimuovere il provider |\n\nReturns: `undefined`\n\n`callback(opt, next)` viene eseguita per ogni chiamata `API()` con questo nome, con l'oggetto chiamata come `this`. `opt` contiene `name`, `schema`, `data`, `controller`, e `files` e `output` quando sono impostati. Rispondi con `next(err, response)`. `name` non distingue tra maiuscole e minuscole, può elencare più nomi separati da virgole, e `*` registra un fallback per i nomi sconosciuti. Un nome senza `callback` rimuove il provider. Il provider `TotalAPI` (alias `TAPI`) è registrato per impostazione predefinita.\n\nExample: Un provider personalizzato\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nInvia una richiesta a un provider di API registrato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Nome del provider, per esempio `TotalAPI` |\n| `schema` | `String` | yes |  | L'endpoint o l'operazione del provider |\n| `data` | `Object` | no |  | Dati della richiesta |\n| `$` | `Object` | no |  | Un controller o `$`, passato al provider come `opt.controller` |\n\nReturns: `APICall` L'oggetto chiamata\n\nRestituisce un oggetto chiamata. La richiesta parte al tick successivo, quindi concatena subito le opzioni e la callback. Senza un provider per `name` (e senza un provider `*`), la chiamata fallisce con `API is not initialized`.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Dentro un'azione\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nImposta la callback della chiamata API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)`, oppure `$` |\n\nReturns: `APICall` La chiamata, per concatenare\n\n`fn(err, response)`. Passa `$` (o un oggetto con `callback`) per rispondere a un'azione con il risultato.\n\nExample: Con $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nRestituisce una promessa con la risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Un oggetto con `invalid()`, come `$` |\n\nReturns: `Promise` La risposta\n\nCon `$`, un errore viene inviato con `$.invalid()` e la promise non si risolve mai; senza, la promise viene rifiutata con un errore chiamato `API(name --> schema)`.\n\nExample: Attendere la risposta con await\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nImposta il formato di output della risposta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Il formato di output |\n\nReturns: `APICall` La chiamata, per concatenare\n\nIl provider lo legge come `opt.output`. Il provider `TotalAPI` supporta `json` (predefinito), `html`, `text`, `plain`, `base64`, `buffer` o `binary`, `stream`, e `#name id filename` per salvare la risposta in un FileStorage.\n\nExample: Salvare la risposta in FileStorage\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nAggiunge un file alla richiesta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Nome del file |\n| `path` | `String` | yes |  | Percorso del file su disco |\n| `name` | `String` | no | `'file' + index` | Nome del campo del form |\n\nReturns: `APICall` La chiamata, per concatenare\n\nAggiunge `{ name, filename, path }` a `opt.files`. Il provider `TotalAPI` invia quindi i dati e i file come richiesta multipart.\n\nExample: Inviare un file\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nTrasforma una risposta vuota in un errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | L'errore |\n| `reverse` | `Boolean` | no | `false` | Fallisce quando la risposta non è vuota |\n\nReturns: `APICall` La chiamata, per concatenare\n\nUna risposta vuota (o un array vuoto) diventa `err`. Con `reverse`, è invece una risposta non vuota a diventare l'errore. Alias: `api.err()`.\n\nExample: Richiedere una risposta\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nEsegue una funzione quando la chiamata fallisce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` La chiamata, per concatenare\n\n`fn(err)` viene eseguita in aggiunta alla callback.\n\nExample: Registrare gli errori\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nEsegue una funzione con la risposta quando la chiamata riesce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` La chiamata, per concatenare\n\n`fn(response)` viene eseguita in aggiunta alla callback, solo in assenza di errori.\n\nExample: Usare la risposta\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nScrive una voce nel log di audit quando la chiamata riesce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Il `$` di un'azione o di un'operazione |\n| `message` | `String` | no |  | Il messaggio di audit |\n| `type` | `String` | no |  | Tipo della voce |\n\nReturns: `APICall` La chiamata, per concatenare\n\nChiama `$.audit(message, type)`. Le variabili nel messaggio vengono riempite con i dati della chiamata tramite `$.variables()`.\n\nExample: Registrare un pagamento nell'audit\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nPassa un controller al provider.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Un controller o `$` |\n\nReturns: `APICall` La chiamata, per concatenare\n\nImposta `opt.controller` a `$.controller` (o a `$` stesso).\n\nExample: Passare il controller\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nStampa nella console il risultato della chiamata.\n\nReturns: `APICall` La chiamata, per concatenare\n\nStampa il nome del provider, lo schema, l'errore e la risposta.\n\nExample: Fare il debug di una chiamata\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nInvia una richiesta a Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Token di Total API |\n| `type` | `String` | yes |  | Il servizio di Total API |\n| `data` | `Object` | yes |  | Dati della richiesta |\n| `callback` | `Function|Controller` | no |  | `function(err, response)`, oppure un controller per inviare un file in streaming |\n| `filename` | `String` | no |  | Nome di un file inviato in streaming |\n\nReturns: `Promise|undefined` Una promise quando non c'è callback\n\nInvia `data` in POST a `https://{default_tapi}.api.totaljs.com/{type}/`. Il token predefinito è `totalapi` (o `secret_totalapi`). Un `data` che non è un oggetto viene inviato come `{ value: data }`. Senza callback restituisce una promise. Una risposta binaria arriva alla callback come stream oppure, quando `callback` è un controller, viene inviata al client con `filename`. Con `allow_totalapi: false`, funziona solo `check`; le altre chiamate falliscono con `totalapi_inactive`.\n\nExample: Verificare il token\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nIl token di Total API.\n\nReturns: `String`\n\nUsato da `TotalAPI()`, dal provider `TotalAPI` di `API()` e dal logger di audit. `secret_totalapi` viene letto quando `totalapi` è vuoto.\n\nExample: Impostare il token\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nLa regione del server di Total API.\n\nReturns: `String`\n\nLe richieste vanno a `https://{default_tapi}.api.totaljs.com/`. Predefinito: `eu`.\n\nExample: Regione\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nInvia i log di audit a Total API.\n\nReturns: `Boolean`\n\nQuando è `true` ed è impostato un token di Total API, le voci di audit vengono inviate al servizio `logger` di Total API invece che a `DEF.onAudit()`. Predefinito: `false`.\n\nExample: Attivare\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDichiara una route API: un unico URL POST che esegue azioni per nome.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dichiarazione della route |\n| `fn` | `Function` | no |  | Un handler personalizzato con il controller come `this` |\n| `flags` | `Array` | no |  | Flag della route |\n\nReturns: `Object` La route\n\nIl client invia in POST `{ \"schema\": \"name/param?query\", \"data\": {} }` all'URL. Il segno prima del nome imposta come vengono gestiti i dati: `+` li valida come `POST`, `#` come `PATCH` (parziale), `-` non ne invia come `GET`. I parametri URL possono avere un tipo dopo `:` (`uid`, `number`, `guid`, `date`); il primo diventa `$.id`. Senza `*Schema --> action`, la route esegue l'azione con lo stesso nome (`--> name`). `+API` richiede un utente autenticato e `-API` uno anonimo. I nomi sconosciuti rispondono `404`, i parametri non validi `400`.\n\nExample: Route API\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: Una richiesta\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nUn'azione di una route API gestita da una tua funzione.\n\nAl posto di `*Schema --> action`, passa una funzione. Viene eseguita con il controller come `this`; `this.params` contiene i parametri URL, `this.body` il `{ schema, data }` inviato e `this.id` il primo parametro. Rispondi con qualsiasi metodo del controller.\n\nExample: Un'azione personalizzata\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jabm3e3Zr60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/message-service-and-apis/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Message Service a API","summary":"TMS funkcie, TMS klient, API(), NEWAPI(), TotalAPI() a API trasy.","markdown":"---\ntitle: Message Service a API\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/message-service-and-apis/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Message Service a API\n\n> TMS funkcie, TMS klient, API(), NEWAPI(), TotalAPI() a API trasy.\n\nTMS kanály sa deklarujú pomocou `NEWPUBLISH()`, `NEWSUBSCRIBE()` a `NEWCALL()` a iná aplikácia sa pripája pomocou `TMSCLIENT()`. `API()` volá poskytovateľov zaregistrovaných pomocou `NEWAPI()`. Príručka [Message Service a API](../../guides/message-service-and-apis/) vysvetľuje, ako časti spolupracujú; táto stránka je presná referencia.\n\n## API\n\n### NEWPUBLISH(name, [schema])\n\nType: `method` · Since: `0.0.42`\n\nDeklaruje TMS kanál, do ktorého tvoja aplikácia publikuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála |\n| `schema` | `String|Object` | no |  | Inline deklarácia (`id:UID, name:String`), objekt JSON schémy s `$id`, alebo názov JSON schémy či Total.js schémy. Vynechaj ju, aby sa kanál odstránil |\n\nReturns: `undefined`\n\nKanál a jeho JSON schéma sa posielajú každému TMS klientovi v správe `meta`. Názov schémy, ktorý neexistuje, vyhodí chybu. Bez `schema` (alebo s `null`) sa kanál odstráni. Opätovná deklarácia existujúceho kanála ponechá jeho prvú schému.\n\nExample: Deklarácia kanála\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number, email:Email');\n```\n\nExample: Odstránenie kanála\n```js\nNEWPUBLISH('orders_created');\n```\n\n### PUBLISH(name, data)\n\nType: `method` · Since: `0.0.42`\n\nPošle správu TMS klientom prihláseným na odber kanála.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála deklarovaného pomocou `NEWPUBLISH()` |\n| `data` | `Object` | yes |  | Správa |\n\nReturns: `undefined`\n\nSprávu dostanú iba klienti, ktorí ohlásili odber `name`. Nerobí nič, keď nie je pripojený žiadny TMS klient alebo keď `name` nebol deklarovaný pomocou `NEWPUBLISH()`. Dáta sa na serveri nevalidujú; `TMSCLIENT()` ich prevedie pomocou schémy kanála.\n\nExample: Publikovanie po vložení\n```js\nNEWPUBLISH('orders_created', 'id:UID, total:Number');\n\nfunction created(order) {\n\tPUBLISH('orders_created', { id: order.id, total: order.total });\n}\n```\n\n### NEWSUBSCRIBE(name, [schema], [callback])\n\nType: `method` · Since: `0.0.42`\n\nDeklaruje TMS kanál, do ktorého publikujú klienti a tvoja aplikácia z neho prijíma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála |\n| `schema` | `String|Object` | no |  | Inline deklarácia (`id:UID, name:String`), objekt JSON schémy s `$id`, alebo názov JSON schémy či Total.js schémy. Vynechaj ju, aby sa kanál odstránil |\n| `callback` | `Function` | no |  | Handler `function(data, client)` |\n\nReturns: `undefined`\n\nPrichádzajúce správy kanála sa validujú pomocou `schema`; neplatné správy sa zahodia a platné idú do handlerov pridaných pomocou `SUBSCRIBE()`. `callback` je skratka pre `SUBSCRIBE(name, callback)`. Bez `schema` sa kanál odstráni (jeho handlery zostanú).\n\nExample: Deklarácia kanála s handlerom\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number', function(data, client) {\n\tNOSQL('products').modify({ price: data.price }).where('id', data.id);\n});\n```\n\n### SUBSCRIBE(name, callback)\n\nType: `method` · Since: `0.0.42`\n\nPridá handler pre správy odberového TMS kanála.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála |\n| `callback` | `Function` | yes |  | `function(data, client)` |\n\nReturns: `undefined`\n\nHandler dostane zvalidované dáta a WebSocket klienta, ktorý ich poslal. Kanál môže mať mnoho handlerov. Správy prichádzajú iba pre kanály deklarované pomocou `NEWSUBSCRIBE()`. Aplikácia ohlási svoje odbery klientom v ďalšej správe `meta`.\n\nExample: Pridanie handlera\n```js\nNEWSUBSCRIBE('products_updated', '*id:UID, price:Number');\n\nSUBSCRIBE('products_updated', function(data, client) {\n\tconsole.log(client.ip, 'updated', data.id);\n});\n```\n\n### UNSUBSCRIBE(name, [callback])\n\nType: `method` · Since: `0.0.42`\n\nOdstráni jeden handler alebo všetky handlery TMS kanála.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála |\n| `callback` | `Function` | no |  | Handler na odstránenie |\n\nReturns: `Boolean` `true`, keď sa niečo odstránilo\n\nS `callback` sa odstráni iba tento handler (odovzdaj tú istú funkciu, ktorú si dal do `SUBSCRIBE()`). Bez neho sa odstránia všetky handlery kanála.\n\nExample: Odstránenie handlera\n```js\nfunction onupdate(data) {\n\tconsole.log(data);\n}\n\nSUBSCRIBE('products_updated', onupdate);\nUNSUBSCRIBE('products_updated', onupdate);\n```\n\n### NEWCALL(name, schema, [callback])\n\nType: `method` · Since: `0.0.45`\n\nZaregistruje vzdialené TMS volanie, ktoré môžu klienti spúšťať.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov volania |\n| `schema` | `String|Object` | yes |  | Inline deklarácia (`id:UID, name:String`), objekt JSON schémy s `$id`, alebo názov JSON schémy či Total.js schémy, alebo `*Schema --> action` |\n| `callback` | `Function|String` | no |  | `function(data, next, client)` alebo názov operácie |\n\nReturns: `undefined`\n\nDáta volania sa validujú pomocou `schema`; chyba validácie sa vráti klientovi. `callback(data, next, client)` odpovie pomocou `next(err, response)`. Namiesto funkcie môže byť `callback` názov operácie. Bez callbacku a so schémou ako `*Orders --> create` volanie spustí túto akciu schémy. `NEWCALL(name, null)` volanie odstráni. Volanie, ktoré neexistuje, odpovie chybou `404`.\n\nExample: Volanie s funkciou\n```js\nNEWCALL('products_detail', '*id:UID', function(data, next, client) {\n\tNOSQL('products').one().where('id', data.id).callback(next, 404);\n});\n```\n\nExample: Volanie, ktoré spúšťa akciu schémy\n```js\nNEWCALL('orders_create', '*Orders --> create');\n```\n\n### { type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }\n\nType: `type`\n\nJSON správy vymieňané na TMS endpointe.\n\nReturns: `Object`\n\nKaždá správa je JSON objekt s `type`:\n\n- `meta` (zo servera klientovi): `name`, `publish`, `subscribe` a `call` (polia `{ id, schema }`) a `subscribers` (kanály, ktoré aplikácia odoberá). Posiela sa po pripojení a sekundu po akejkoľvek zmene.\n- `publish` (zo servera klientovi): `{ id, data }`, posiela ho `PUBLISH()`.\n- `subscribe` (z klienta serveru): `{ id, data }`, správa pre kanál `NEWSUBSCRIBE()`.\n- `subscribers` (z klienta serveru): `{ subscribers: [names] }`, kanály, ktoré chce klient prijímať.\n- `call` (oboma smermi): `{ id, data, callbackid }`; odpoveď pridá `success: true` alebo `error: true`.\n- `ping`: odpovedá sa naň `pong`.\n\nPotrebuješ to len vtedy, ak píšeš TMS klienta bez `TMSCLIENT()`. Nový klient začína s prázdnym zoznamom odberov a správy `publish` prijíma len pre kanály, ktoré uvedie v `subscribers`.\n\nExample: Klient odoberá a volá\n```json\n{ \"type\": \"subscribers\", \"subscribers\": [\"orders_created\"] }\n{ \"type\": \"call\", \"id\": \"products_detail\", \"data\": { \"id\": \"1a2b3c\" }, \"callbackid\": \"1\" }\n```\n\n### secret_tms : token\n\nType: `config` · Since: `0.0.42`\n\nToken, ktorý musia TMS klienti posielať.\n\nReturns: `String`\n\nKlienti ho posielajú v hlavičke `x-token`. Nesprávny token zatvorí spojenie s kódom `4001`; viac ako päť neúspešných pokusov z jednej IP adresy ju zablokuje až do denného resetu. Zmena tokenu zatvorí TMS spojenia. Hodnota môže byť aj číslo. Predvolené: prázdne, prijme sa každý klient.\n\nExample: Ochrana TMS\n```text\nallow_tms  : true\nsecret_tms : my-secret-token\n```\n\n### default_tms_maxlength : 1024\n\nType: `config` · Since: `0.0.80`\n\nMaximálna veľkosť TMS správy v kB.\n\nReturns: `Number`\n\nUplatňuje sa na WebSocket trasu TMS endpointu (`default_tms_url`). Predvolené: `1024` (1 MB).\n\nExample: Povolenie väčších správ\n```text\ndefault_tms_maxlength : 5120\n```\n\n### publish: true | String\n\nType: `property` · Since: `0.0.72`\n\nVoľba schema.action() a NEWACTION(), ktorá deklaruje publikačný TMS kanál.\n\nReturns: `Boolean|String`\n\nKanál je pomenovaný podľa akcie: `Schema.action` pre `schema.action()`, názov akcie pre `NEWACTION()`. `true` použije `input` (alebo `output`) akcie ako schému kanála. Reťazec je vlastná inline schéma; reťazec, ktorý začína `+`, pridá svoje polia k vstupu. Správy posielaj pomocou `$.publish()`.\n\nExample: Publikovanie z akcie\n```js\nNEWSCHEMA('Orders', function(schema) {\n\tschema.action('create', {\n\t\tinput: '*email:Email, *total:Number',\n\t\tpublish: '+id:UID',\n\t\taction: function($, model) {\n\t\t\tmodel.id = UID();\n\t\t\t$.publish(model);\n\t\t\t$.success(model.id);\n\t\t}\n\t});\n});\n```\n\n### $.publish(value)\n\nType: `method` · Since: `0.0.72`\n\nPublikuje správu do TMS kanála aktuálnej akcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Správa |\n\nReturns: `SchemaOptions` To isté `$`, na reťazenie\n\nFunguje v akciách deklarovaných s voľbou `publish`; názov kanála je ID akcie. Ako `PUBLISH()` nerobí nič bez pripojeného TMS klienta. Polia `value` sa skopírujú do nového objektu.\n\nExample: Publikovanie a odpoveď\n```js\naction: function($, model) {\n\t$.publish(model).success();\n}\n```\n\n### TMSCLIENT(url, [token], [callback])\n\nType: `method` · Since: `0.0.45`\n\nPripojí sa k TMS endpointu inej Total.js aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL TMS endpointu, napríklad `https://app.example.com/$tms/` |\n| `token` | `String` | no |  | `secret_tms` servera |\n| `callback` | `Function` | no |  | `function(err, client, meta)` |\n\nReturns: `WebSocketClient` TMS klient\n\nVráti WebSocket klienta (pozri [WebSockety](../../guides/websockets/)) s ďalšími metódami `subscribe()`, `publish()` a `call()`. URL s `http` sa zmení na `ws` a klient sa znova pripojí, keď server spadne. `token` sa posiela v hlavičke `x-token`. `callback(err, client, meta)` sa spustí raz, po prvej správe `meta`.\n\nExample: Pripojenie\n```js\nTMSCLIENT('https://orders.example.com/$tms/', 'my-secret-token', function(err, client, meta) {\n\tconsole.log('Connected to', meta.name);\n});\n```\n\n### client.subscribe(name, callback)\n\nType: `method` · Since: `0.0.45`\n\nPrijíma správy z publikačného kanála servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála deklarovaného pomocou `NEWPUBLISH()` na serveri |\n| `callback` | `Function` | yes |  | `function(data)` |\n\nReturns: `undefined`\n\nDáta sa prevedú pomocou schémy kanála z `meta` a handlery sa spúšťajú iba pre kanály, ktoré server publikuje. Klient pošle serveru svoj zoznam odberov krátko po každom volaní a znova po opätovnom pripojení.\n\nExample: Odber\n```js\nclient.subscribe('orders_created', function(data) {\n\tconsole.log(data.id, data.total);\n});\n```\n\n### client.publish(name, data)\n\nType: `method` · Since: `0.0.45`\n\nPošle správu do odberového kanála servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov kanála deklarovaného pomocou `NEWSUBSCRIBE()` na serveri |\n| `data` | `Object` | yes |  | Správa |\n\nReturns: `undefined`\n\nServer ju zvaliduje schémou svojho kanála `NEWSUBSCRIBE()`. Kým klient nie je pripojený, nič sa neposiela.\n\nExample: Publikovanie\n```js\nclient.publish('products_updated', { id: '1a2b3c', price: 99 });\n```\n\n### client.call(name, data, [callback], [timeout])\n\nType: `method` · Since: `0.0.45`\n\nSpustí vzdialené volanie zaregistrované na serveri pomocou NEWCALL().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov volania |\n| `data` | `Object` | yes |  | Dáta volania |\n| `callback` | `Function` | no |  | `function(err, response)` |\n| `timeout` | `Number` | no | `10000` | Časový limit v milisekundách |\n\nReturns: `Promise|undefined` Promise, keď nie je zadaný callback\n\n`callback(err, response)` dostane odpoveď; chyby zo servera prichádzajú ako `ErrorBuilder`. Bez callbacku vráti promise. Pred pripravením spojenia zlyhá s `TMS is offline`; bez včasnej odpovede s `408: Timeout`.\n\nExample: Volanie s callbackom\n```js\nclient.call('products_detail', { id: '1a2b3c' }, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Volanie s await\n```js\nvar product = await client.call('products_detail', { id: '1a2b3c' });\n```\n\n### client.ready\n\nType: `property` · Since: `0.0.45`\n\n`true`, keď je klient pripojený a prijal meta.\n\nReturns: `Boolean`\n\nZmení sa na `false`, keď sa spojenie zatvorí, a znova na `true` po ďalšej `meta`.\n\nExample: Kontrola stavu\n```js\nif (client.ready)\n\tclient.publish('products_updated', { id: id, price: price });\n```\n\n### client.meta\n\nType: `property` · Since: `0.0.45`\n\nPosledná meta správa prijatá zo servera.\n\nReturns: `Object`\n\nObsahuje `name` servera a zoznamy `publish`, `subscribe` a `call` s JSON schémami. Pozri TMS správy.\n\nExample: Výpis vzdialených volaní\n```js\nconsole.log(client.meta.call.map(item => item.id));\n```\n\n### client.on('meta', function(meta) {})\n\nType: `event` · Since: `0.0.45`\n\nVyšle sa vždy, keď server pošle svoju meta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Meta správa |\n\nServer posiela meta po pripojení, po opätovnom pripojení a po akejkoľvek zmene svojich kanálov alebo volaní.\n\nExample: Sledovanie zmien\n```js\nclient.on('meta', function(meta) {\n\tconsole.log('Server publishes', meta.publish.length, 'channels');\n});\n```\n\n### client.on('ready', function() {})\n\nType: `event` · Since: `0.0.45`\n\nVyšle sa po každej meta správe, keď je klient pripravený.\n\nPouži ju na spustenie kódu po každom opätovnom pripojení; callback `TMSCLIENT()` sa spustí iba prvýkrát.\n\nExample: Po každom pripojení\n```js\nclient.on('ready', function() {\n\tconsole.log('TMS ready');\n});\n```\n\n### NEWAPI(name, [callback])\n\nType: `method` · Since: `0.0.65`\n\nZaregistruje poskytovateľa API, ktorého používa API().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poskytovateľa, viac názvov oddelených čiarkami, alebo `*` |\n| `callback` | `Function` | no |  | `function(opt, next)`. Vynechaj ho, aby sa poskytovateľ odstránil |\n\nReturns: `undefined`\n\n`callback(opt, next)` sa spustí pre každé volanie `API()` s týmto názvom, s objektom volania ako `this`. `opt` má `name`, `schema`, `data`, `controller` a, ak sú nastavené, `files` a `output`. Odpovedz pomocou `next(err, response)`. `name` nerozlišuje veľké a malé písmená, môže obsahovať viac názvov oddelených čiarkami a `*` zaregistruje záložného poskytovateľa pre neznáme názvy. Názov bez `callback` poskytovateľa odstráni. Poskytovateľ `TotalAPI` (alias `TAPI`) je zaregistrovaný predvolene.\n\nExample: Vlastný poskytovateľ\n```js\nNEWAPI('Payments', function(opt, next) {\n\tRESTBuilder.POST('https://payments.example.com/' + opt.schema + '/', opt.data).callback(next);\n});\n```\n\n### API(name, schema, [data], [$])\n\nType: `method`\n\nPošle požiadavku zaregistrovanému poskytovateľovi API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov poskytovateľa, napríklad `TotalAPI` |\n| `schema` | `String` | yes |  | Endpoint alebo operácia poskytovateľa |\n| `data` | `Object` | no |  | Dáta požiadavky |\n| `$` | `Object` | no |  | Kontrolér alebo `$`, odovzdaný poskytovateľovi ako `opt.controller` |\n\nReturns: `APICall` Objekt volania\n\nVráti objekt volania. Požiadavka sa spustí v ďalšom ticku, takže voľby a callback reťaz hneď. Bez poskytovateľa pre `name` (a bez poskytovateľa `*`) volanie zlyhá s `API is not initialized`.\n\nExample: Total API\n```js\nAPI('TotalAPI', 'check').callback(function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Vnútri akcie\n```js\naction: function($, model) {\n\tAPI('Payments', 'charge', model).callback($);\n}\n```\n\n### api.callback(fn)\n\nType: `method`\n\nNastaví callback volania API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function|Object` | yes |  | `function(err, response)`, alebo `$` |\n\nReturns: `APICall` Volanie, na reťazenie\n\n`fn(err, response)`. Odovzdaj `$` (alebo objekt s `callback`), aby si akcii odpovedal výsledkom.\n\nExample: S $\n```js\nAPI('TotalAPI', 'check').callback($);\n```\n\n### api.promise([$])\n\nType: `method`\n\nVráti promise s odpoveďou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | no |  | Objekt s `invalid()`, napríklad `$` |\n\nReturns: `Promise` Odpoveď\n\nS `$` sa chyba pošle pomocou `$.invalid()` a promise sa nikdy nevyrieši; bez neho sa promise zamietne s chybou s názvom `API(name --> schema)`.\n\nExample: Čakanie na odpoveď pomocou await\n```js\nvar response = await API('TotalAPI', 'check').promise($);\n```\n\n### api.output(type)\n\nType: `method`\n\nNastaví výstupný formát odpovede.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Výstupný formát |\n\nReturns: `APICall` Volanie, na reťazenie\n\nPoskytovateľ ho číta ako `opt.output`. Poskytovateľ `TotalAPI` podporuje `json` (predvolené), `html`, `text`, `plain`, `base64`, `buffer` alebo `binary`, `stream` a `#name id filename` na uloženie odpovede do FileStorage.\n\nExample: Uloženie odpovede do FileStorage\n```js\nAPI('TotalAPI', 'service_name', data).output('#invoices ' + UID() + ' invoice.pdf').callback(console.log);\n```\n\n### api.file(filename, path, [name])\n\nType: `method`\n\nPridá súbor k požiadavke.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Názov súboru |\n| `path` | `String` | yes |  | Cesta k súboru na disku |\n| `name` | `String` | no | `'file' + index` | Názov poľa formulára |\n\nReturns: `APICall` Volanie, na reťazenie\n\nPridá `{ name, filename, path }` do `opt.files`. Poskytovateľ `TotalAPI` potom pošle dáta a súbory ako multipart požiadavku.\n\nExample: Odoslanie súboru\n```js\nAPI('Payments', 'upload', { id: id }).file('scan.png', PATH.public('scan.png')).callback(console.log);\n```\n\n### api.error(err, [reverse])\n\nType: `method`\n\nZmení prázdnu odpoveď na chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `String` | yes |  | Chyba |\n| `reverse` | `Boolean` | no | `false` | Zlyhať, keď odpoveď nie je prázdna |\n\nReturns: `APICall` Volanie, na reťazenie\n\nPrázdna odpoveď (alebo prázdne pole) sa stane `err`. S `reverse` sa naopak chybou stane neprázdna odpoveď. Alias: `api.err()`.\n\nExample: Vyžadovanie odpovede\n```js\nAPI('Payments', 'detail', { id: id }).error('404').callback($);\n```\n\n### api.fail(fn)\n\nType: `method`\n\nSpustí funkciu, keď volanie zlyhá.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(err)` |\n\nReturns: `APICall` Volanie, na reťazenie\n\n`fn(err)` sa spustí popri callbacku.\n\nExample: Logovanie chýb\n```js\nAPI('Payments', 'charge', model).fail(console.error).data(console.log);\n```\n\n### api.data(fn)\n\nType: `method`\n\nSpustí funkciu s odpoveďou, keď volanie uspeje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function` | yes |  | `function(response)` |\n\nReturns: `APICall` Volanie, na reťazenie\n\n`fn(response)` sa spustí popri callbacku, iba bez chyby.\n\nExample: Použitie odpovede\n```js\nAPI('TotalAPI', 'check').data(function(response) {\n\tconsole.log(response);\n});\n```\n\n### api.audit($, [message], [type])\n\nType: `method`\n\nZapíše záznam do audit logu, keď volanie uspeje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | `$` akcie alebo operácie |\n| `message` | `String` | no |  | Správa auditu |\n| `type` | `String` | no |  | Typ záznamu |\n\nReturns: `APICall` Volanie, na reťazenie\n\nZavolá `$.audit(message, type)`. Premenné v správe sa vyplnia z dát volania pomocou `$.variables()`.\n\nExample: Audit platby\n```js\nAPI('Payments', 'charge', model).audit($, 'Charged {amount}').callback($);\n```\n\n### api.controller($)\n\nType: `method`\n\nOdovzdá kontrolér poskytovateľovi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `$` | `Object` | yes |  | Kontrolér alebo `$` |\n\nReturns: `APICall` Volanie, na reťazenie\n\nNastaví `opt.controller` na `$.controller` (alebo na samotné `$`).\n\nExample: Odovzdanie kontroléra\n```js\nAPI('Payments', 'charge', model).controller($).callback($);\n```\n\n### api.debug()\n\nType: `method`\n\nVypíše výsledok volania do konzoly.\n\nReturns: `APICall` Volanie, na reťazenie\n\nVypíše názov poskytovateľa, schému, chybu a odpoveď.\n\nExample: Ladenie volania\n```js\nAPI('TotalAPI', 'check').debug().callback(NOOP);\n```\n\n### TotalAPI([token], type, data, [callback], [filename])\n\nType: `method`\n\nPošle jednu požiadavku na Total API.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `token` | `String` | no | `CONF.totalapi` | Token Total API |\n| `type` | `String` | yes |  | Služba Total API |\n| `data` | `Object` | yes |  | Dáta požiadavky |\n| `callback` | `Function|Controller` | no |  | `function(err, response)`, alebo kontrolér na streamovanie súboru |\n| `filename` | `String` | no |  | Názov streamovaného súboru |\n\nReturns: `Promise|undefined` Promise, keď nie je zadaný callback\n\nPošle `data` na `https://{default_tapi}.api.totaljs.com/{type}/`. Token je predvolene `totalapi` (alebo `secret_totalapi`). `data`, ktoré nie sú objektom, sa pošlú ako `{ value: data }`. Bez callbacku vráti promise. Binárna odpoveď ide do callbacku ako stream, alebo, keď je `callback` kontrolér, sa pošle klientovi s `filename`. S `allow_totalapi: false` funguje iba `check`; ostatné volania zlyhajú s `totalapi_inactive`.\n\nExample: Kontrola tokenu\n```js\nTotalAPI('check', {}, function(err, response) {\n\tconsole.log(err, response);\n});\n```\n\nExample: Await\n```js\nvar response = await TotalAPI('check', {});\n```\n\n### totalapi : token\n\nType: `config`\n\nToken Total API.\n\nReturns: `String`\n\nPoužíva ho `TotalAPI()`, poskytovateľ `TotalAPI` pre `API()` a audit logger. Keď je `totalapi` prázdny, číta sa `secret_totalapi`.\n\nExample: Nastavenie tokenu\n```text\ntotalapi : my-totalapi-token\n```\n\n### default_tapi : eu\n\nType: `config`\n\nRegión servera Total API.\n\nReturns: `String`\n\nPožiadavky idú na `https://{default_tapi}.api.totaljs.com/`. Predvolené: `eu`.\n\nExample: Región\n```text\ndefault_tapi : eu\n```\n\n### allow_totalapilogger : false\n\nType: `config` · Since: `0.0.42`\n\nPosiela audit logy na Total API.\n\nReturns: `Boolean`\n\nKeď je `true` a je nastavený token Total API, záznamy auditu sa posielajú do služby `logger` Total API namiesto `DEF.onAudit()`. Predvolené: `false`.\n\nExample: Zapnutie\n```text\ntotalapi             : my-totalapi-token\nallow_totalapilogger : true\n```\n\n### ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])\n\nType: `method`\n\nDeklaruje API trasu: jednu POST URL, ktorá spúšťa akcie podľa názvu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Deklarácia trasy |\n| `fn` | `Function` | no |  | Vlastný handler s kontrolérom ako `this` |\n| `flags` | `Array` | no |  | Flagy trasy |\n\nReturns: `Object` Trasa\n\nKlient pošle na URL `{ \"schema\": \"name/param?query\", \"data\": {} }`. Znak pred názvom určuje, ako sa s dátami zaobchádza: `+` ich validuje ako `POST`, `#` ako `PATCH` (čiastočne), `-` neposiela žiadne ako `GET`. Parametre URL môžu mať typ za `:` (`uid`, `number`, `guid`, `date`); prvý sa stane `$.id`. Bez `*Schema --> action` trasa spustí akciu s rovnakým názvom (`--> name`). `+API` vyžaduje prihláseného používateľa a `-API` anonymného. Neznáme názvy odpovedajú `404`, neplatné parametre `400`.\n\nExample: API trasy\n```js\nexports.install = function() {\n\tROUTE('+API /api/ -orders_list      *Orders --> list');\n\tROUTE('+API /api/ +orders_create    *Orders --> create');\n\tROUTE('+API /api/ -orders_read/{id} *Orders --> read');\n};\n```\n\nExample: Požiadavka\n```json\n{ \"schema\": \"orders_read/1a2b3c?fields=id,total\" }\n```\n\n### ROUTE('API /url/ name', function() {})\n\nType: `method` · Since: `0.0.95`\n\nAkcia API trasy spracovaná tvojou vlastnou funkciou.\n\nNamiesto `*Schema --> action` odovzdaj funkciu. Spustí sa s kontrolérom ako `this`; `this.params` obsahuje parametre URL, `this.body` odoslané `{ schema, data }` a `this.id` prvý parameter. Odpovedz ľubovoľnou metódou kontroléra.\n\nExample: Vlastná akcia\n```js\nexports.install = function() {\n\tROUTE('API /api/ -ping', function() {\n\t\tthis.success();\n\t});\n\tROUTE('API /api/ +echo', function() {\n\t\tthis.json(this.body.data);\n\t});\n};\n```\n","entries":[{"type":"method","name":"NEWPUBLISH()","signature":"NEWPUBLISH(name, [schema])","since":"0.0.42","deprecated":false},{"type":"method","name":"PUBLISH()","signature":"PUBLISH(name, data)","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWSUBSCRIBE()","signature":"NEWSUBSCRIBE(name, [schema], [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"SUBSCRIBE()","signature":"SUBSCRIBE(name, callback)","since":"0.0.42","deprecated":false},{"type":"method","name":"UNSUBSCRIBE()","signature":"UNSUBSCRIBE(name, [callback])","since":"0.0.42","deprecated":false},{"type":"method","name":"NEWCALL()","signature":"NEWCALL(name, schema, [callback])","since":"0.0.45","deprecated":false},{"type":"type","name":"TMS messages","signature":"{ type: 'meta' | 'publish' | 'subscribe' | 'subscribers' | 'call' | 'ping' }","since":"","deprecated":false},{"type":"config","name":"secret_tms","signature":"secret_tms : token","since":"0.0.42","deprecated":false},{"type":"config","name":"default_tms_maxlength","signature":"default_tms_maxlength : 1024","since":"0.0.80","deprecated":false},{"type":"property","name":"action.publish","signature":"publish: true | String","since":"0.0.72","deprecated":false},{"type":"method","name":"$.publish()","signature":"$.publish(value)","since":"0.0.72","deprecated":false},{"type":"method","name":"TMSCLIENT()","signature":"TMSCLIENT(url, [token], [callback])","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.subscribe()","signature":"client.subscribe(name, callback)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.publish()","signature":"client.publish(name, data)","since":"0.0.45","deprecated":false},{"type":"method","name":"tmsclient.call()","signature":"client.call(name, data, [callback], [timeout])","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.ready","signature":"client.ready","since":"0.0.45","deprecated":false},{"type":"property","name":"tmsclient.meta","signature":"client.meta","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('meta')","signature":"client.on('meta', function(meta) {})","since":"0.0.45","deprecated":false},{"type":"event","name":"tmsclient.on('ready')","signature":"client.on('ready', function() {})","since":"0.0.45","deprecated":false},{"type":"method","name":"NEWAPI()","signature":"NEWAPI(name, [callback])","since":"0.0.65","deprecated":false},{"type":"method","name":"API()","signature":"API(name, schema, [data], [$])","since":"","deprecated":false},{"type":"method","name":"apicall.callback()","signature":"api.callback(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.promise()","signature":"api.promise([$])","since":"","deprecated":false},{"type":"method","name":"apicall.output()","signature":"api.output(type)","since":"","deprecated":false},{"type":"method","name":"apicall.file()","signature":"api.file(filename, path, [name])","since":"","deprecated":false},{"type":"method","name":"apicall.error()","signature":"api.error(err, [reverse])","since":"","deprecated":false},{"type":"method","name":"apicall.fail()","signature":"api.fail(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.data()","signature":"api.data(fn)","since":"","deprecated":false},{"type":"method","name":"apicall.audit()","signature":"api.audit($, [message], [type])","since":"","deprecated":false},{"type":"method","name":"apicall.controller()","signature":"api.controller($)","since":"","deprecated":false},{"type":"method","name":"apicall.debug()","signature":"api.debug()","since":"","deprecated":false},{"type":"method","name":"TotalAPI()","signature":"TotalAPI([token], type, data, [callback], [filename])","since":"","deprecated":false},{"type":"config","name":"totalapi","signature":"totalapi : token","since":"","deprecated":false},{"type":"config","name":"default_tapi","signature":"default_tapi : eu","since":"","deprecated":false},{"type":"config","name":"allow_totalapilogger","signature":"allow_totalapilogger : false","since":"0.0.42","deprecated":false},{"type":"method","name":"ROUTE('API ...')","signature":"ROUTE('[+|-]API /url/ [+|#|-]name[/{param}] [*Schema --> action]', [fn], [flags])","since":"","deprecated":false},{"type":"method","name":"Custom Route API action","signature":"ROUTE('API /url/ name', function() {})","since":"0.0.95","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmL91hV60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Images","summary":"The global Image object, the methods of an image, and the image config keys.","markdown":"---\ntitle: Images\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Images\n\n> The global Image object, the methods of an image, and the image config keys.\n\nThe global `Image` object loads and measures images, and an image object builds the commands for GraphicsMagick or ImageMagick. The guide [Images](../../guides/images/) explains how to use them with examples; this page is the exact reference.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nAn image with a list of operations for GraphicsMagick or ImageMagick.\n\nReturns: `Image`\n\nCreate it with `Image.load()`; the constructor is `Image.Image` (alias `Image.Picture`). Properties:\n\n- `filename` — the source file, or `null` for a stream or a buffer\n- `outputType` — the output format; the extension of the file, `jpg` for streams and buffers, or the value of `output()`\n- `width`, `height` — the values passed to `Image.load()` (they are not measured)\n- `builder` — the list of operations added so far\n\nAll operation methods return the image. Add your own methods with `F.prototypes()`, whose argument has the `Image` prototype.\n\nExample: Extend the prototype\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCreates an image object from a file, a stream or a buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | A file name, a readable stream or a buffer with the image. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) or `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Stored in `image.width`; not used by the operations. |\n| `height` | `Number` | no |  | Stored in `image.height`; not used by the operations. |\n\nReturns: `Image` A new image.\n\nNothing is read or run yet. For a file name, the output format is the file extension; for a stream or a buffer, it is `jpg` until you call `output()`.\n\nExample: Resize a file\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: From a buffer with ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nThe same function as `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | A file name, a readable stream or a buffer with the image. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) or `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Stored in `image.width`; not used by the operations. |\n| `height` | `Number` | no |  | Stored in `image.height`; not used by the operations. |\n\nReturns: `Image` A new image.\n\nCreates an image object; the arguments and the result are the same as in `Image.load()`.\n\nExample: Create an image\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nReturns the width and height of an image from its first bytes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Extension or MIME type. |\n| `buffer` | `Buffer` | yes |  | The beginning of the file (the whole file for SVG; for JPEG, enough bytes to reach the frame header). |\n\nReturns: `Object` `{ width, height }`, or `undefined`/`null` when it cannot be read.\n\nCalls the measuring function for the type. `type` is an extension with or without the dot, or a MIME type: `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). For other types it returns `undefined`. No external tool is needed.\n\nExample: Measure an uploaded buffer\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nReturns the width and height of a JPG image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`\n\nWalks the JPEG markers to the first frame header (SOF). Returns `null` when the buffer is not a JPEG or the header is not in the buffer.\n\nExample: Measure a file\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nReturns the width and height of a PNG image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`\n\nReads the size from the IHDR chunk; 24 bytes are enough.\n\nExample: Measure a file\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nReturns the width and height of a GIF image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`\n\nReads the logical screen size; 10 bytes are enough.\n\nExample: Measure a file\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nReturns the width and height of a BMP image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`\n\nReads the size from the BMP header. The height is always positive (top-down bitmaps have a negative height in the file).\n\nExample: Measure a file\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nReturns the width and height of a PSD image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`\n\nReads the size from the Photoshop header.\n\nExample: Measure a file\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nReturns the width and height of a lossy or lossless WebP image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The beginning of the file. |\n\nReturns: `Object` `{ width, height }`, or `undefined`.\n\nSupports lossy (`VP8 `) and lossless (`VP8L`) WebP images. It needs the first 30 bytes. It returns `undefined` for an unknown header.\n\nExample: Measure a WebP file\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nReturns the width and height of an SVG image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | The SVG file. |\n\nReturns: `Object` `{ width, height }`, or `undefined`.\n\nSearches the text for the first `width=\"N\"` and `height=\"N\"` attributes with whole numbers. Units and `viewBox` are not read. It returns `undefined` when there are no such attributes, and `0` for a missing side.\n\nExample: Measure an SVG\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegisters a stream that processes every output of a type.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Output type, for example `png` or `.png`. |\n| `fn` | `Function` | yes |  | Returns a new transform stream. |\n\nReturns: `undefined`\n\n`fn()` must return a new transform (duplex) stream on each call. The output of `pipe()` and `stream()` for that type passes through it. After `save()`, the saved file is read, passed through the stream and written again before the callback. Only one middleware per type; a new one replaces the old one. The type is matched with the output type (`png`, `jpg`...), so `jpeg` and `jpg` are different.\n\nExample: Pass all PNG output through a stream\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nResizes the image and keeps its aspect ratio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Width in pixels. Use `0` or `null` to compute it from the height. |\n| `h` | `Number` | no |  | Height in pixels. Omit it to compute it from the width. |\n| `options` | `String` | no |  | A suffix of the size: `!` (ignore aspect ratio), `>` (only shrink), `<` (only enlarge), `^` (fill), `%` (percent). |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-resize WxH`. With only the width, the height is computed, and the other way round. The image fits into the box; add `options` to change it.\n\nExample: Common sizes\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nFills the size and crops the rest around the center.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Width in pixels. |\n| `h` | `Number` | yes |  | Height in pixels. |\n| `color` | `String` | no | `'white'` | Background color, for example `white` or `#F0F0F0`. |\n\nReturns: `Image` The same image, for chaining.\n\nResizes with `^` so the image covers `w` x `h`, then crops the center part. The result has exactly the given size. `resize_center()` is an alias.\n\nExample: A square avatar\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nFills the size and crops the rest around a side or a corner.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Width in pixels. |\n| `h` | `Number` | yes |  | Height in pixels. |\n| `align` | `String` | no | `'center'` | Which part to keep. |\n| `color` | `String` | no | `'white'` | Background color, for example `white` or `#F0F0F0`. |\n\nReturns: `Image` The same image, for chaining.\n\nLike `resizeCenter()`, but keeps the part given by `align` (the values of `align()`, for example `top`, `bottom`, `top left`). `resize_align()` is an alias.\n\nExample: Keep the top part\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nFits the whole image into the size and fills the empty area.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Width in pixels. |\n| `h` | `Number` | yes |  | Height in pixels. |\n| `color` | `String` | no | `'white'` | Background color, for example `white` or `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Resize filter. |\n\nReturns: `Image` The same image, for chaining.\n\nRuns `thumbnail(w, h)` with the filter, centers the result and extends it to exactly `w` x `h` with the background color. Nothing is cut off.\n\nExample: Product picture on white\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nResizes the image with the `-thumbnail` option.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Width in pixels. Use `0` or `null` to compute it from the height. |\n| `h` | `Number` | no |  | Height in pixels. Omit it to compute it from the width. |\n| `options` | `String` | no |  | A suffix of the size: `!` (ignore aspect ratio), `>` (only shrink), `<` (only enlarge), `^` (fill), `%` (percent). |\n\nReturns: `Image` The same image, for chaining.\n\nWorks like `resize()`. The tool also removes the profiles, so it is a good choice for small previews.\n\nExample: Preview\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nResizes the image without a resampling filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Width in pixels. Use `0` or `null` to compute it from the height. |\n| `h` | `Number` | no |  | Height in pixels. Omit it to compute it from the width. |\n| `options` | `String` | no |  | A suffix of the size: `!` (ignore aspect ratio), `>` (only shrink), `<` (only enlarge), `^` (fill), `%` (percent). |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-scale`. It is faster than `resize()` and gives a lower quality.\n\nExample: Half size\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nCuts out a rectangle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Width in pixels. |\n| `h` | `Number` | yes |  | Height in pixels. |\n| `x` | `Number` | no | `0` | Left offset. |\n| `y` | `Number` | no | `0` | Top offset. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-crop WxH+X+Y`. The offset is relative to the gravity set with `align()` (top left by default). The offset must be zero or positive.\n\nExample: Crop a region\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nSets the canvas size.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Width in pixels. Use `0` or `null` to compute it from the height. |\n| `h` | `Number` | no |  | Height in pixels. Omit it to compute it from the width. |\n| `x` | `Number` | no |  | Horizontal offset. |\n| `y` | `Number` | no |  | Vertical offset. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-extent`. A larger canvas is filled with the background color; a smaller one cuts the image. `x` and `y` move the image (negative values are allowed).\n\nExample: Square canvas\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nSets the gravity of `crop()`, `extent()` and `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The position. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-gravity`. Values: `top left`, `top`, `top right`, `left`, `center` (or `middle`), `right`, `bottom left`, `bottom`, `bottom right`; the words can be in any order (`left top`) and `center` can be added (`top center`). Other values go to the tool unchanged, for example `NorthEast`. `gravity()` is an alias.\n\nExample: Watermark in the corner\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nSets the resampling filter for resizing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Filter name. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-filter`, for example `Lanczos`, `Box`, `Hamming`, `Triangle`. See the documentation of your tool for all names.\n\nExample: Sharp downscale\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nSets the compression quality.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | From 1 to 100. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-quality`. Without an argument, the value is `80`.\n\nExample: Set the quality\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nRotates the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Degrees. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-rotate`. Positive values rotate clockwise. It runs after the resize and crop operations (priority 8).\n\nExample: Rotate\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nMirrors the image vertically (top to bottom).\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-flip`.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nMirrors the image horizontally (left to right).\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-flop`.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nBlurs the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | The blur radius. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-blur`. The value is passed to the tool, so it can be a number or `radiusxsigma`, for example `0x8`.\n\nExample: Blur\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nConverts the image to gray.\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-colorspace Gray`.\n\nExample: Gray\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nGives the image a sepia tone.\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-modulate 115,0,100` and `-colorize 7,21,50`.\n\nExample: Sepia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nStretches the contrast to the full range.\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-normalize`.\n\nExample: Normalize\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nReduces the number of colors.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | The maximum number of colors. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-colors`. Useful for small PNG and GIF files.\n\nExample: 256 colors\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nSets the bit depth of a channel.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits per channel, for example `8`. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-depth`.\n\nExample: 8 bits\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nSets the background color.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | A color name or `#RRGGBB`. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-background` and `-extent 0x0`. The color fills transparent areas and the area added by `extent()`, `rotate()` and `miniature()`.\n\nExample: White background\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nSets the fill color for drawing.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | A color name or `#RRGGBB`. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-fill`. Use it with `command()` options that draw, for example `-colorize`.\n\nExample: Fill\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDraws another image over this one.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The watermark file. |\n| `x` | `Number` | no | `0` | Horizontal offset. |\n| `y` | `Number` | no | `0` | Vertical offset. |\n| `w` | `Number` | no | `0` | Width of the watermark. |\n| `h` | `Number` | no | `0` | Height of the watermark. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-draw` with `image over X,Y W,H filename`. The file name must not contain spaces or quotes. The position is relative to the gravity from `align()`. With `w` and `h` set to `0`, the watermark keeps its size.\n\nExample: Logo in the bottom right corner\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nLimits the resources the tool can use.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | The resource. |\n| `value` | `Number|String` | yes |  | The limit, in the units of the tool. |\n\nReturns: `Image` The same image, for chaining.\n\nAdds `-limit type value`, for example `memory`, `map`, `disk`, `threads`. When you call it, `default_image_consumption` is not applied to this image.\n\nExample: Two threads\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nRemoves the profiles and metadata.\n\nReturns: `Image` The same image, for chaining.\n\nAdds `+profile \"*\"`, which removes EXIF, ICC and other profiles and makes the file smaller. `save()`, `pipe()` and `stream()` call it on their own when the image has no operation.\n\nExample: Strip metadata\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nSets the output format.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | For example `png`, `webp`, `.jpg`. |\n\nReturns: `Image` The same image, for chaining.\n\nChanges `image.outputType` (a leading dot is removed). `pipe()` and `stream()` use it as the format, and `res.image()` uses it for the `Content-Type`. `save()` takes the format from the extension of the target file.\n\nExample: Convert a stream to PNG\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nCalls a function with the image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Adds the operations. |\n\nReturns: `Image` The same image, for chaining.\n\n`fn` is called with the image as `this` and as the argument. Use it to reuse a set of operations.\n\nExample: Reusable preset\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAdds any option of the tool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The option, for example `-sharpen`. |\n| `value` | `String|Number` | no |  | The value of the option. |\n| `priority` | `Number|Boolean` | no | `10` | Order of the option. |\n| `escape` | `Boolean` | no | `false` | Quote the value. |\n\nReturns: `Image` The same image, for chaining.\n\nUse it for options without their own method, for example `-strip`, `-sharpen` or `-define`. The options run in the order of their priority (see the guide). `escape` puts the value in quotes and removes `'` from it; use it for values that come from users. With `priority` set to `true`, the priority is `0` and the value is escaped.\n\nExample: Sharpen and interlace\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nRemoves all operations.\n\nReturns: `Image` The same image, for chaining.\n\nEmpties `image.builder`. `save()` calls it after it runs, so one image object can be used again.\n\nExample: Start again\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nReads the width and height of the source file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` is `{ width, height }`. |\n\nReturns: `Image` The same image, for chaining.\n\nReads the beginning of the file and measures it in JavaScript. It works only for an image loaded from a file name with the extension `.jpg`, `.png`, `.gif` or `.webp` (lower or upper case); other extensions, `.jpeg` included, give an error. For a stream or a buffer use `Image.measure()`, and for other formats `identify()`.\n\nExample: Measure a file\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nReads the type and size of the source file with the external tool.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` is `{ type, width, height }`, for example `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` The same image, for chaining.\n\nRuns `gm identify` (or `identify` for `im` and `magick`) and parses the first line. It needs an image loaded from a file name.\n\nExample: Identify\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nRuns the operations and saves the result to a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | The target file. |\n| `callback` | `Function(err, saved)` | no |  | `saved` is `true` on success and `false` on an error. |\n| `writer` | `Function(stdin)` | no |  | Gets the input stream of the tool, to write the source yourself. |\n\nReturns: `Image` The same image, for chaining.\n\nWithout `filename`, the source file is overwritten. The format follows the extension of `filename`. A registered `Image.middleware()` for the output type runs after the file is written. After the run, the operations are cleared.\n\nExample: Save a copy as WebP\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nRuns the operations and pipes the result into a writable stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | A writable stream, for example a file stream or `res`. |\n| `type` | `String` | no | `image.outputType` | Output format. |\n| `options` | `Object` | no |  | Options of `pipe()`. |\n\nReturns: `Image` The same image, for chaining.\n\n`type` is the output format: `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` or `ico`. Another value or none uses `image.outputType`. `options` are passed to `stream.pipe()`. Errors of the tool are emitted as `error` events of `stream`.\n\nExample: Write to a file stream\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nRuns the operations and returns the result as a readable stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Output format. |\n| `writer` | `Function(stdin)` | no |  | Writes the source data. |\n\nReturns: `ReadableStream` The output of the tool (through the middleware, if one is registered).\n\n`type` works as in `pipe()`. `writer(stdin)` can write the source into the tool yourself.\n\nExample: Upload a resized image\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nLimits the memory of GraphicsMagick or ImageMagick, as a percentage.\n\nReturns: `Number`\n\nWhen it is not `0`, each image without its own `limit()` gets `-limit memory` (15 × value) and `-limit map` (30 × value). It is disabled by default because some versions of GraphicsMagick fail with these limits. A `%` sign in the config file is allowed.\n\nDefault: `0` (disabled).\n\nExample: Half of the default limits\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmL91hV60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Bilder","summary":"Das globale Image-Objekt, die Methoden eines Bildes und die Konfigurationsschlüssel für Bilder.","markdown":"---\ntitle: Bilder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Bilder\n\n> Das globale Image-Objekt, die Methoden eines Bildes und die Konfigurationsschlüssel für Bilder.\n\nDas globale Objekt `Image` lädt und vermisst Bilder, und ein Bildobjekt baut die Befehle für GraphicsMagick oder ImageMagick. Die Anleitung [Bilder](../../guides/images/) erklärt mit Beispielen, wie du sie verwendest; diese Seite ist die genaue Referenz.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nEin Bild mit einer Liste von Operationen für GraphicsMagick oder ImageMagick.\n\nReturns: `Image`\n\nErstelle es mit `Image.load()`; der Konstruktor ist `Image.Image` (Alias `Image.Picture`). Eigenschaften:\n\n- `filename` — die Quelldatei oder `null` bei einem Stream oder Buffer\n- `outputType` — das Ausgabeformat; die Endung der Datei, `jpg` bei Streams und Buffern oder der Wert von `output()`\n- `width`, `height` — die an `Image.load()` übergebenen Werte (sie werden nicht gemessen)\n- `builder` — die Liste der bisher hinzugefügten Operationen\n\nAlle Operationsmethoden geben das Bild zurück. Füge eigene Methoden mit `F.prototypes()` hinzu, dessen Argument den `Image`-Prototyp enthält.\n\nExample: Den Prototyp erweitern\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nErstellt ein Bildobjekt aus einer Datei, einem Stream oder einem Buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Ein Dateiname, ein lesbarer Stream oder ein Buffer mit dem Bild. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) oder `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Wird in `image.width` gespeichert; von den Operationen nicht verwendet. |\n| `height` | `Number` | no |  | Wird in `image.height` gespeichert; von den Operationen nicht verwendet. |\n\nReturns: `Image` Ein neues Bild.\n\nEs wird noch nichts gelesen oder ausgeführt. Bei einem Dateinamen ist das Ausgabeformat die Dateiendung; bei einem Stream oder Buffer ist es `jpg`, bis du `output()` aufrufst.\n\nExample: Eine Datei skalieren\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: Aus einem Buffer mit ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nDieselbe Funktion wie `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Ein Dateiname, ein lesbarer Stream oder ein Buffer mit dem Bild. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) oder `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Wird in `image.width` gespeichert; von den Operationen nicht verwendet. |\n| `height` | `Number` | no |  | Wird in `image.height` gespeichert; von den Operationen nicht verwendet. |\n\nReturns: `Image` Ein neues Bild.\n\nErstellt ein Bildobjekt; die Argumente und das Ergebnis sind dieselben wie bei `Image.load()`.\n\nExample: Ein Bild erstellen\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines Bildes anhand seiner ersten Bytes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Endung oder MIME-Typ. |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei (bei SVG die ganze Datei; bei JPEG genug Bytes, um den Frame-Header zu erreichen). |\n\nReturns: `Object` `{ width, height }` oder `undefined`/`null`, wenn es nicht gelesen werden kann.\n\nRuft die Messfunktion für den Typ auf. `type` ist eine Endung mit oder ohne Punkt oder ein MIME-Typ: `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). Für andere Typen gibt sie `undefined` zurück. Es ist kein externes Werkzeug nötig.\n\nExample: Einen hochgeladenen Buffer vermessen\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines JPG-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`\n\nDurchläuft die JPEG-Marker bis zum ersten Frame-Header (SOF). Gibt `null` zurück, wenn der Buffer kein JPEG ist oder der Header nicht im Buffer liegt.\n\nExample: Eine Datei vermessen\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines PNG-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`\n\nLiest die Größe aus dem IHDR-Chunk; 24 Bytes genügen.\n\nExample: Eine Datei vermessen\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines GIF-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`\n\nLiest die logische Bildschirmgröße; 10 Bytes genügen.\n\nExample: Eine Datei vermessen\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines BMP-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`\n\nLiest die Größe aus dem BMP-Header. Die Höhe ist immer positiv (Top-down-Bitmaps haben in der Datei eine negative Höhe).\n\nExample: Eine Datei vermessen\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines PSD-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }`\n\nLiest die Größe aus dem Photoshop-Header.\n\nExample: Eine Datei vermessen\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nGibt die Breite und Höhe eines verlustbehafteten oder verlustfreien WebP-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Der Anfang der Datei. |\n\nReturns: `Object` `{ width, height }` oder `undefined`.\n\nUnterstützt verlustbehaftete (`VP8 `) und verlustfreie (`VP8L`) WebP-Bilder. Es braucht die ersten 30 Bytes. Bei einem unbekannten Header gibt es `undefined` zurück.\n\nExample: Eine WebP-Datei messen\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nGibt Breite und Höhe eines SVG-Bildes zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Die SVG-Datei. |\n\nReturns: `Object` `{ width, height }` oder `undefined`.\n\nDurchsucht den Text nach den ersten Attributen `width=\"N\"` und `height=\"N\"` mit ganzen Zahlen. Einheiten und `viewBox` werden nicht gelesen. Gibt `undefined` zurück, wenn es keine solchen Attribute gibt, und `0` für eine fehlende Seite.\n\nExample: Ein SVG vermessen\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistriert einen Stream, der jede Ausgabe eines Typs verarbeitet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Ausgabetyp, zum Beispiel `png` oder `.png`. |\n| `fn` | `Function` | yes |  | Gibt einen neuen Transform-Stream zurück. |\n\nReturns: `undefined`\n\n`fn()` muss bei jedem Aufruf einen neuen Transform-Stream (Duplex) zurückgeben. Die Ausgabe von `pipe()` und `stream()` für diesen Typ läuft durch ihn hindurch. Nach `save()` wird die gespeicherte Datei gelesen, durch den Stream geleitet und vor dem Callback erneut geschrieben. Nur eine Middleware pro Typ; eine neue ersetzt die alte. Der Typ wird mit dem Ausgabetyp (`png`, `jpg`...) verglichen, daher sind `jpeg` und `jpg` verschieden.\n\nExample: Alle PNG-Ausgaben durch einen Stream leiten\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild und behält sein Seitenverhältnis bei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Breite in Pixeln. Verwende `0` oder `null`, um sie aus der Höhe zu berechnen. |\n| `h` | `Number` | no |  | Höhe in Pixeln. Lass sie weg, um sie aus der Breite zu berechnen. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` (Seitenverhältnis ignorieren), `>` (nur verkleinern), `<` (nur vergrößern), `^` (ausfüllen), `%` (Prozent). |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-resize WxH` hinzu. Wird nur die Breite angegeben, wird die Höhe berechnet, und umgekehrt. Das Bild passt in den Rahmen; füge `options` hinzu, um das zu ändern.\n\nExample: Gängige Größen\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nFüllt die Größe aus und schneidet den Rest um die Mitte herum ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Breite in Pixeln. |\n| `h` | `Number` | yes |  | Höhe in Pixeln. |\n| `color` | `String` | no | `'white'` | Hintergrundfarbe, zum Beispiel `white` oder `#F0F0F0`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nSkaliert mit `^`, sodass das Bild `w` x `h` abdeckt, und schneidet dann den mittleren Teil aus. Das Ergebnis hat genau die angegebene Größe. `resize_center()` ist ein Alias.\n\nExample: Ein quadratischer Avatar\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nFüllt die Größe aus und schneidet den Rest um eine Seite oder Ecke herum ab.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Breite in Pixeln. |\n| `h` | `Number` | yes |  | Höhe in Pixeln. |\n| `align` | `String` | no | `'center'` | Welcher Teil behalten wird. |\n| `color` | `String` | no | `'white'` | Hintergrundfarbe, zum Beispiel `white` oder `#F0F0F0`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nWie `resizeCenter()`, behält aber den durch `align` angegebenen Teil (die Werte von `align()`, zum Beispiel `top`, `bottom`, `top left`). `resize_align()` ist ein Alias.\n\nExample: Den oberen Teil behalten\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nPasst das ganze Bild in die Größe ein und füllt den leeren Bereich.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Breite in Pixeln. |\n| `h` | `Number` | yes |  | Höhe in Pixeln. |\n| `color` | `String` | no | `'white'` | Hintergrundfarbe, zum Beispiel `white` oder `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Skalierungsfilter. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFührt `thumbnail(w, h)` mit dem Filter aus, zentriert das Ergebnis und erweitert es mit der Hintergrundfarbe auf genau `w` x `h`. Es wird nichts abgeschnitten.\n\nExample: Produktbild auf Weiß\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild mit der Option `-thumbnail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Breite in Pixeln. Verwende `0` oder `null`, um sie aus der Höhe zu berechnen. |\n| `h` | `Number` | no |  | Höhe in Pixeln. Lass sie weg, um sie aus der Breite zu berechnen. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` (Seitenverhältnis ignorieren), `>` (nur verkleinern), `<` (nur vergrößern), `^` (ausfüllen), `%` (Prozent). |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFunktioniert wie `resize()`. Das Werkzeug entfernt außerdem die Profile, daher ist es eine gute Wahl für kleine Vorschauen.\n\nExample: Vorschau\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nSkaliert das Bild ohne Resampling-Filter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Breite in Pixeln. Verwende `0` oder `null`, um sie aus der Höhe zu berechnen. |\n| `h` | `Number` | no |  | Höhe in Pixeln. Lass sie weg, um sie aus der Breite zu berechnen. |\n| `options` | `String` | no |  | Ein Suffix der Größe: `!` (Seitenverhältnis ignorieren), `>` (nur verkleinern), `<` (nur vergrößern), `^` (ausfüllen), `%` (Prozent). |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-scale` hinzu. Es ist schneller als `resize()` und liefert eine geringere Qualität.\n\nExample: Halbe Größe\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nSchneidet ein Rechteck aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Breite in Pixeln. |\n| `h` | `Number` | yes |  | Höhe in Pixeln. |\n| `x` | `Number` | no | `0` | Versatz von links. |\n| `y` | `Number` | no | `0` | Versatz von oben. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-crop WxH+X+Y` hinzu. Der Versatz bezieht sich auf die mit `align()` gesetzte Ausrichtung (standardmäßig oben links). Der Versatz muss null oder positiv sein.\n\nExample: Einen Bereich zuschneiden\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nSetzt die Größe der Arbeitsfläche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Breite in Pixeln. Verwende `0` oder `null`, um sie aus der Höhe zu berechnen. |\n| `h` | `Number` | no |  | Höhe in Pixeln. Lass sie weg, um sie aus der Breite zu berechnen. |\n| `x` | `Number` | no |  | Horizontaler Versatz. |\n| `y` | `Number` | no |  | Vertikaler Versatz. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-extent` hinzu. Eine größere Arbeitsfläche wird mit der Hintergrundfarbe gefüllt; eine kleinere schneidet das Bild ab. `x` und `y` verschieben das Bild (negative Werte sind erlaubt).\n\nExample: Quadratische Arbeitsfläche\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nSetzt die Ausrichtung (Gravity) von `crop()`, `extent()` und `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Die Position. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-gravity` hinzu. Werte: `top left`, `top`, `top right`, `left`, `center` (oder `middle`), `right`, `bottom left`, `bottom`, `bottom right`; die Wörter können in beliebiger Reihenfolge stehen (`left top`), und `center` kann hinzugefügt werden (`top center`). Andere Werte gehen unverändert an das Werkzeug, zum Beispiel `NorthEast`. `gravity()` ist ein Alias.\n\nExample: Wasserzeichen in der Ecke\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nSetzt den Resampling-Filter für das Skalieren.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Name des Filters. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-filter` hinzu, zum Beispiel `Lanczos`, `Box`, `Hamming`, `Triangle`. Alle Namen findest du in der Dokumentation deines Werkzeugs.\n\nExample: Scharfes Verkleinern\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nSetzt die Kompressionsqualität.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | Von 1 bis 100. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-quality` hinzu. Ohne Argument ist der Wert `80`.\n\nExample: Die Qualität setzen\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nDreht das Bild.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Grad. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-rotate` hinzu. Positive Werte drehen im Uhrzeigersinn. Läuft nach den Skalierungs- und Zuschneideoperationen (Priorität 8).\n\nExample: Drehen\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nSpiegelt das Bild vertikal (von oben nach unten).\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-flip` hinzu.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nSpiegelt das Bild horizontal (von links nach rechts).\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-flop` hinzu.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nZeichnet das Bild weich.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Der Radius der Unschärfe. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-blur` hinzu. Der Wert wird an das Werkzeug übergeben, er kann also eine Zahl oder `radiusxsigma` sein, zum Beispiel `0x8`.\n\nExample: Weichzeichnen\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nWandelt das Bild in Graustufen um.\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-colorspace Gray` hinzu.\n\nExample: Graustufen\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nGibt dem Bild einen Sepiaton.\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-modulate 115,0,100` und `-colorize 7,21,50` hinzu.\n\nExample: Sepia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nStreckt den Kontrast auf den vollen Bereich.\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-normalize` hinzu.\n\nExample: Normalisieren\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nReduziert die Anzahl der Farben.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Die maximale Anzahl der Farben. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-colors` hinzu. Nützlich für kleine PNG- und GIF-Dateien.\n\nExample: 256 Farben\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nSetzt die Bittiefe eines Kanals.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits pro Kanal, zum Beispiel `8`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-depth` hinzu.\n\nExample: 8 Bit\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nSetzt die Hintergrundfarbe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Ein Farbname oder `#RRGGBB`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-background` und `-extent 0x0` hinzu. Die Farbe füllt transparente Bereiche und den Bereich, der durch `extent()`, `rotate()` und `miniature()` hinzukommt.\n\nExample: Weißer Hintergrund\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nSetzt die Füllfarbe zum Zeichnen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Ein Farbname oder `#RRGGBB`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-fill` hinzu. Verwende es mit `command()`-Optionen, die zeichnen, zum Beispiel `-colorize`.\n\nExample: Füllen\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nZeichnet ein anderes Bild über dieses.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die Datei des Wasserzeichens. |\n| `x` | `Number` | no | `0` | Horizontaler Versatz. |\n| `y` | `Number` | no | `0` | Vertikaler Versatz. |\n| `w` | `Number` | no | `0` | Breite des Wasserzeichens. |\n| `h` | `Number` | no | `0` | Höhe des Wasserzeichens. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-draw` mit `image over X,Y W,H filename` hinzu. Der Dateiname darf keine Leerzeichen oder Anführungszeichen enthalten. Die Position bezieht sich auf die Ausrichtung aus `align()`. Wenn `w` und `h` auf `0` gesetzt sind, behält das Wasserzeichen seine Größe.\n\nExample: Logo in der unteren rechten Ecke\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nBegrenzt die Ressourcen, die das Werkzeug verwenden darf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Die Ressource. |\n| `value` | `Number|String` | yes |  | Das Limit, in den Einheiten des Werkzeugs. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `-limit type value` hinzu, zum Beispiel `memory`, `map`, `disk`, `threads`. Wenn du die Methode aufrufst, wird `default_image_consumption` auf dieses Bild nicht angewendet.\n\nExample: Zwei Threads\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nEntfernt die Profile und Metadaten.\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFügt `+profile \"*\"` hinzu, was EXIF-, ICC- und andere Profile entfernt und die Datei verkleinert. `save()`, `pipe()` und `stream()` rufen die Methode selbst auf, wenn das Bild keine Operation hat.\n\nExample: Metadaten entfernen\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nSetzt das Ausgabeformat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Zum Beispiel `png`, `webp`, `.jpg`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nÄndert `image.outputType` (ein führender Punkt wird entfernt). `pipe()` und `stream()` verwenden es als Format, und `res.image()` verwendet es für den `Content-Type`. `save()` nimmt das Format aus der Endung der Zieldatei.\n\nExample: Einen Stream in PNG umwandeln\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nRuft eine Funktion mit dem Bild auf.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Fügt die Operationen hinzu. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\n`fn` wird mit dem Bild als `this` und als Argument aufgerufen. Verwende es, um eine Reihe von Operationen wiederzuverwenden.\n\nExample: Wiederverwendbare Voreinstellung\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nFügt eine beliebige Option des Werkzeugs hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Die Option, zum Beispiel `-sharpen`. |\n| `value` | `String|Number` | no |  | Der Wert der Option. |\n| `priority` | `Number|Boolean` | no | `10` | Reihenfolge der Option. |\n| `escape` | `Boolean` | no | `false` | Den Wert in Anführungszeichen setzen. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nVerwende es für Optionen ohne eigene Methode, zum Beispiel `-strip`, `-sharpen` oder `-define`. Die Optionen laufen in der Reihenfolge ihrer Priorität (siehe die Anleitung). `escape` setzt den Wert in Anführungszeichen und entfernt `'` daraus; verwende es für Werte, die von Benutzern stammen. Wenn `priority` auf `true` gesetzt ist, ist die Priorität `0`, und der Wert wird maskiert.\n\nExample: Schärfen und Interlacing\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nEntfernt alle Operationen.\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nLeert `image.builder`. `save()` ruft die Methode nach der Ausführung auf, sodass ein Bildobjekt erneut verwendet werden kann.\n\nExample: Neu beginnen\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nLiest Breite und Höhe der Quelldatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` ist `{ width, height }`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nLiest den Anfang der Datei und vermisst sie in JavaScript. Funktioniert nur für ein Bild, das aus einem Dateinamen mit der Endung `.jpg`, `.png`, `.gif` oder `.webp` (klein oder groß geschrieben) geladen wurde; andere Endungen, einschließlich `.jpeg`, ergeben einen Fehler. Für einen Stream oder Buffer verwende `Image.measure()`, für andere Formate `identify()`.\n\nExample: Eine Datei vermessen\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nLiest Typ und Größe der Quelldatei mit dem externen Werkzeug.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` ist `{ type, width, height }`, zum Beispiel `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nFührt `gm identify` (oder `identify` für `im` und `magick`) aus und parst die erste Zeile. Benötigt ein Bild, das aus einem Dateinamen geladen wurde.\n\nExample: Identifizieren\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nFührt die Operationen aus und speichert das Ergebnis in einer Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | Die Zieldatei. |\n| `callback` | `Function(err, saved)` | no |  | `saved` ist bei Erfolg `true` und bei einem Fehler `false`. |\n| `writer` | `Function(stdin)` | no |  | Erhält den Eingabestream des Werkzeugs, um die Quelle selbst zu schreiben. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\nOhne `filename` wird die Quelldatei überschrieben. Das Format folgt der Endung von `filename`. Eine für den Ausgabetyp registrierte `Image.middleware()` läuft, nachdem die Datei geschrieben wurde. Nach der Ausführung werden die Operationen geleert.\n\nExample: Eine Kopie als WebP speichern\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nFührt die Operationen aus und leitet das Ergebnis in einen beschreibbaren Stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Ein beschreibbarer Stream, zum Beispiel ein Datei-Stream oder `res`. |\n| `type` | `String` | no | `image.outputType` | Ausgabeformat. |\n| `options` | `Object` | no |  | Optionen von `pipe()`. |\n\nReturns: `Image` Dasselbe Bild, zum Verketten.\n\n`type` ist das Ausgabeformat: `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` oder `ico`. Ein anderer oder kein Wert verwendet `image.outputType`. `options` werden an `stream.pipe()` übergeben. Fehler des Werkzeugs werden als `error`-Events von `stream` gesendet.\n\nExample: In einen Datei-Stream schreiben\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nFührt die Operationen aus und gibt das Ergebnis als lesbaren Stream zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Ausgabeformat. |\n| `writer` | `Function(stdin)` | no |  | Schreibt die Quelldaten. |\n\nReturns: `ReadableStream` Die Ausgabe des Werkzeugs (durch die Middleware, falls eine registriert ist).\n\n`type` funktioniert wie bei `pipe()`. Mit `writer(stdin)` kannst du die Quelle selbst in das Werkzeug schreiben.\n\nExample: Ein skaliertes Bild hochladen\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nBegrenzt den Speicher von GraphicsMagick oder ImageMagick, als Prozentwert.\n\nReturns: `Number`\n\nWenn der Wert nicht `0` ist, erhält jedes Bild ohne eigenes `limit()` die Optionen `-limit memory` (15 × Wert) und `-limit map` (30 × Wert). Standardmäßig ist es deaktiviert, weil einige Versionen von GraphicsMagick mit diesen Limits fehlschlagen. Ein `%`-Zeichen in der Konfigurationsdatei ist erlaubt.\n\nStandard: `0` (deaktiviert).\n\nExample: Die Hälfte der Standardlimits\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmL91hV60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Imágenes","summary":"El objeto global Image, los métodos de una imagen y las claves de configuración de imágenes.","markdown":"---\ntitle: \"Imágenes\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Imágenes\n\n> El objeto global Image, los métodos de una imagen y las claves de configuración de imágenes.\n\nEl objeto global `Image` carga y mide imágenes, y un objeto de imagen construye los comandos para GraphicsMagick o ImageMagick. La guía [Imágenes](../../guides/images/) explica cómo usarlos con ejemplos; esta página es la referencia exacta.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nUna imagen con una lista de operaciones para GraphicsMagick o ImageMagick.\n\nReturns: `Image`\n\nCréala con `Image.load()`; el constructor es `Image.Image` (alias `Image.Picture`). Propiedades:\n\n- `filename` — el archivo de origen, o `null` para un stream o un buffer\n- `outputType` — el formato de salida; la extensión del archivo, `jpg` para streams y buffers, o el valor de `output()`\n- `width`, `height` — los valores pasados a `Image.load()` (no se miden)\n- `builder` — la lista de operaciones añadidas hasta ahora\n\nTodos los métodos de operación devuelven la imagen. Añade tus propios métodos con `F.prototypes()`, cuyo argumento tiene el prototipo `Image`.\n\nExample: Extender el prototipo\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrea un objeto de imagen a partir de un archivo, un stream o un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nombre de archivo, un stream de lectura o un buffer con la imagen. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) o `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Se guarda en `image.width`; las operaciones no lo usan. |\n| `height` | `Number` | no |  | Se guarda en `image.height`; las operaciones no lo usan. |\n\nReturns: `Image` Una imagen nueva.\n\nTodavía no se lee ni se ejecuta nada. Para un nombre de archivo, el formato de salida es la extensión del archivo; para un stream o un buffer, es `jpg` hasta que llames a `output()`.\n\nExample: Redimensionar un archivo\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: Desde un buffer con ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nLa misma función que `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nombre de archivo, un stream de lectura o un buffer con la imagen. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) o `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Se guarda en `image.width`; las operaciones no lo usan. |\n| `height` | `Number` | no |  | Se guarda en `image.height`; las operaciones no lo usan. |\n\nReturns: `Image` Una imagen nueva.\n\nCrea un objeto de imagen; los argumentos y el resultado son los mismos que en `Image.load()`.\n\nExample: Crear una imagen\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen a partir de sus primeros bytes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Extensión o tipo MIME. |\n| `buffer` | `Buffer` | yes |  | El principio del archivo (el archivo completo para SVG; para JPEG, bytes suficientes para llegar a la cabecera del frame). |\n\nReturns: `Object` `{ width, height }`, o `undefined`/`null` cuando no se puede leer.\n\nLlama a la función de medición del tipo. `type` es una extensión con o sin punto, o un tipo MIME: `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). Para otros tipos devuelve `undefined`. No se necesita ninguna herramienta externa.\n\nExample: Medir un buffer subido\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen JPG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`\n\nRecorre los marcadores JPEG hasta la primera cabecera de frame (SOF). Devuelve `null` cuando el buffer no es un JPEG o la cabecera no está en el buffer.\n\nExample: Medir un archivo\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen PNG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`\n\nLee el tamaño del chunk IHDR; bastan 24 bytes.\n\nExample: Medir un archivo\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen GIF.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`\n\nLee el tamaño lógico de pantalla; bastan 10 bytes.\n\nExample: Medir un archivo\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen BMP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`\n\nLee el tamaño de la cabecera BMP. El alto siempre es positivo (los bitmaps de arriba abajo tienen un alto negativo en el archivo).\n\nExample: Medir un archivo\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen PSD.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`\n\nLee el tamaño de la cabecera de Photoshop.\n\nExample: Medir un archivo\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen WebP con o sin pérdida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El principio del archivo. |\n\nReturns: `Object` `{ width, height }`, o `undefined`.\n\nAdmite imágenes WebP con pérdida (`VP8 `) y sin pérdida (`VP8L`). Necesita los primeros 30 bytes. Devuelve `undefined` para una cabecera desconocida.\n\nExample: Medir un archivo WebP\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nDevuelve el ancho y el alto de una imagen SVG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | El archivo SVG. |\n\nReturns: `Object` `{ width, height }`, o `undefined`.\n\nBusca en el texto los primeros atributos `width=\"N\"` y `height=\"N\"` con números enteros. No se leen las unidades ni `viewBox`. Devuelve `undefined` cuando no existen esos atributos, y `0` para el lado que falte.\n\nExample: Medir un SVG\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistra un stream que procesa toda la salida de un tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Tipo de salida, por ejemplo `png` o `.png`. |\n| `fn` | `Function` | yes |  | Devuelve un stream de transformación nuevo. |\n\nReturns: `undefined`\n\n`fn()` debe devolver un stream de transformación (duplex) nuevo en cada llamada. La salida de `pipe()` y `stream()` para ese tipo pasa por él. Después de `save()`, el archivo guardado se lee, pasa por el stream y se vuelve a escribir antes del callback. Solo un middleware por tipo; uno nuevo sustituye al anterior. El tipo se compara con el tipo de salida (`png`, `jpg`...), así que `jpeg` y `jpg` son distintos.\n\nExample: Pasar toda la salida PNG por un stream\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen y mantiene su relación de aspecto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Ancho en píxeles. Usa `0` o `null` para calcularlo a partir del alto. |\n| `h` | `Number` | no |  | Alto en píxeles. Omítelo para calcularlo a partir del ancho. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` (ignora la relación de aspecto), `>` (solo reduce), `<` (solo amplía), `^` (rellena), `%` (porcentaje). |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-resize WxH`. Con solo el ancho, se calcula el alto, y al revés. La imagen se ajusta dentro del recuadro; añade `options` para cambiarlo.\n\nExample: Tamaños habituales\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nRellena el tamaño y recorta el resto alrededor del centro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Ancho en píxeles. |\n| `h` | `Number` | yes |  | Alto en píxeles. |\n| `color` | `String` | no | `'white'` | Color de fondo, por ejemplo `white` o `#F0F0F0`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nRedimensiona con `^` para que la imagen cubra `w` x `h` y después recorta la parte central. El resultado tiene exactamente el tamaño indicado. `resize_center()` es un alias.\n\nExample: Un avatar cuadrado\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nRellena el tamaño y recorta el resto alrededor de un lado o una esquina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Ancho en píxeles. |\n| `h` | `Number` | yes |  | Alto en píxeles. |\n| `align` | `String` | no | `'center'` | Qué parte conservar. |\n| `color` | `String` | no | `'white'` | Color de fondo, por ejemplo `white` o `#F0F0F0`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nComo `resizeCenter()`, pero conserva la parte indicada por `align` (los valores de `align()`, por ejemplo `top`, `bottom`, `top left`). `resize_align()` es un alias.\n\nExample: Conservar la parte superior\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nAjusta la imagen completa al tamaño y rellena el área vacía.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Ancho en píxeles. |\n| `h` | `Number` | yes |  | Alto en píxeles. |\n| `color` | `String` | no | `'white'` | Color de fondo, por ejemplo `white` o `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Filtro de redimensionado. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nEjecuta `thumbnail(w, h)` con el filtro, centra el resultado y lo amplía exactamente a `w` x `h` con el color de fondo. No se recorta nada.\n\nExample: Foto de producto sobre blanco\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen con la opción `-thumbnail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Ancho en píxeles. Usa `0` o `null` para calcularlo a partir del alto. |\n| `h` | `Number` | no |  | Alto en píxeles. Omítelo para calcularlo a partir del ancho. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` (ignora la relación de aspecto), `>` (solo reduce), `<` (solo amplía), `^` (rellena), `%` (porcentaje). |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nFunciona como `resize()`. La herramienta además elimina los perfiles, así que es una buena opción para vistas previas pequeñas.\n\nExample: Vista previa\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nRedimensiona la imagen sin filtro de remuestreo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Ancho en píxeles. Usa `0` o `null` para calcularlo a partir del alto. |\n| `h` | `Number` | no |  | Alto en píxeles. Omítelo para calcularlo a partir del ancho. |\n| `options` | `String` | no |  | Un sufijo del tamaño: `!` (ignora la relación de aspecto), `>` (solo reduce), `<` (solo amplía), `^` (rellena), `%` (porcentaje). |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-scale`. Es más rápido que `resize()` y da una calidad menor.\n\nExample: Mitad de tamaño\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nRecorta un rectángulo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Ancho en píxeles. |\n| `h` | `Number` | yes |  | Alto en píxeles. |\n| `x` | `Number` | no | `0` | Desplazamiento izquierdo. |\n| `y` | `Number` | no | `0` | Desplazamiento superior. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-crop WxH+X+Y`. El desplazamiento es relativo a la gravedad establecida con `align()` (arriba a la izquierda por defecto). El desplazamiento debe ser cero o positivo.\n\nExample: Recortar una región\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nEstablece el tamaño del lienzo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Ancho en píxeles. Usa `0` o `null` para calcularlo a partir del alto. |\n| `h` | `Number` | no |  | Alto en píxeles. Omítelo para calcularlo a partir del ancho. |\n| `x` | `Number` | no |  | Desplazamiento horizontal. |\n| `y` | `Number` | no |  | Desplazamiento vertical. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-extent`. Un lienzo más grande se rellena con el color de fondo; uno más pequeño recorta la imagen. `x` e `y` mueven la imagen (se permiten valores negativos).\n\nExample: Lienzo cuadrado\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nEstablece la gravedad de `crop()`, `extent()` y `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posición. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-gravity`. Valores: `top left`, `top`, `top right`, `left`, `center` (o `middle`), `right`, `bottom left`, `bottom`, `bottom right`; las palabras pueden ir en cualquier orden (`left top`) y se puede añadir `center` (`top center`). Los demás valores llegan sin cambios a la herramienta, por ejemplo `NorthEast`. `gravity()` es un alias.\n\nExample: Marca de agua en la esquina\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nEstablece el filtro de remuestreo para redimensionar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Nombre del filtro. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-filter`, por ejemplo `Lanczos`, `Box`, `Hamming`, `Triangle`. Consulta la documentación de tu herramienta para ver todos los nombres.\n\nExample: Reducción nítida\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nEstablece la calidad de compresión.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | De 1 a 100. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-quality`. Sin argumento, el valor es `80`.\n\nExample: Establecer la calidad\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nRota la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Grados. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-rotate`. Los valores positivos rotan en el sentido de las agujas del reloj. Se ejecuta después de las operaciones de redimensionado y recorte (prioridad 8).\n\nExample: Rotar\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nRefleja la imagen verticalmente (de arriba abajo).\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-flip`.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nRefleja la imagen horizontalmente (de izquierda a derecha).\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-flop`.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nDesenfoca la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | El radio del desenfoque. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-blur`. El valor se pasa a la herramienta, así que puede ser un número o `radiusxsigma`, por ejemplo `0x8`.\n\nExample: Desenfocar\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nConvierte la imagen a escala de grises.\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-colorspace Gray`.\n\nExample: Gris\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nDa a la imagen un tono sepia.\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-modulate 115,0,100` y `-colorize 7,21,50`.\n\nExample: Sepia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nEstira el contraste a todo el rango.\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-normalize`.\n\nExample: Normalizar\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nReduce el número de colores.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | El número máximo de colores. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-colors`. Útil para archivos PNG y GIF pequeños.\n\nExample: 256 colores\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nEstablece la profundidad de bits de un canal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits por canal, por ejemplo `8`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-depth`.\n\nExample: 8 bits\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nEstablece el color de fondo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Un nombre de color o `#RRGGBB`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-background` y `-extent 0x0`. El color rellena las áreas transparentes y el área añadida por `extent()`, `rotate()` y `miniature()`.\n\nExample: Fondo blanco\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nEstablece el color de relleno para dibujar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Un nombre de color o `#RRGGBB`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-fill`. Úsalo con opciones de `command()` que dibujan, por ejemplo `-colorize`.\n\nExample: Relleno\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDibuja otra imagen encima de esta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo de la marca de agua. |\n| `x` | `Number` | no | `0` | Desplazamiento horizontal. |\n| `y` | `Number` | no | `0` | Desplazamiento vertical. |\n| `w` | `Number` | no | `0` | Ancho de la marca de agua. |\n| `h` | `Number` | no | `0` | Alto de la marca de agua. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-draw` con `image over X,Y W,H filename`. El nombre del archivo no debe contener espacios ni comillas. La posición es relativa a la gravedad de `align()`. Con `w` y `h` a `0`, la marca de agua conserva su tamaño.\n\nExample: Logo en la esquina inferior derecha\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nLimita los recursos que puede usar la herramienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | El recurso. |\n| `value` | `Number|String` | yes |  | El límite, en las unidades de la herramienta. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `-limit type value`, por ejemplo `memory`, `map`, `disk`, `threads`. Cuando la llamas, `default_image_consumption` no se aplica a esta imagen.\n\nExample: Dos hilos\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nElimina los perfiles y los metadatos.\n\nReturns: `Image` La misma imagen, para encadenar.\n\nAñade `+profile \"*\"`, que elimina los perfiles EXIF, ICC y otros y hace el archivo más pequeño. `save()`, `pipe()` y `stream()` lo llaman por su cuenta cuando la imagen no tiene ninguna operación.\n\nExample: Quitar los metadatos\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nEstablece el formato de salida.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Por ejemplo `png`, `webp`, `.jpg`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nCambia `image.outputType` (se elimina el punto inicial). `pipe()` y `stream()` lo usan como formato, y `res.image()` lo usa para el `Content-Type`. `save()` toma el formato de la extensión del archivo de destino.\n\nExample: Convertir un stream a PNG\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nLlama a una función con la imagen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Añade las operaciones. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\n`fn` se llama con la imagen como `this` y como argumento. Úsalo para reutilizar un conjunto de operaciones.\n\nExample: Preajuste reutilizable\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAñade cualquier opción de la herramienta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La opción, por ejemplo `-sharpen`. |\n| `value` | `String|Number` | no |  | El valor de la opción. |\n| `priority` | `Number|Boolean` | no | `10` | Orden de la opción. |\n| `escape` | `Boolean` | no | `false` | Poner el valor entre comillas. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nÚsalo para opciones que no tienen su propio método, por ejemplo `-strip`, `-sharpen` o `-define`. Las opciones se ejecutan en el orden de su prioridad (consulta la guía). `escape` pone el valor entre comillas y le quita `'`; úsalo para valores que vienen de los usuarios. Con `priority` a `true`, la prioridad es `0` y el valor se escapa.\n\nExample: Enfocar y entrelazar\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nElimina todas las operaciones.\n\nReturns: `Image` La misma imagen, para encadenar.\n\nVacía `image.builder`. `save()` la llama después de ejecutarse, así que un mismo objeto de imagen se puede volver a usar.\n\nExample: Empezar de nuevo\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nLee el ancho y el alto del archivo de origen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` es `{ width, height }`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nLee el principio del archivo y lo mide en JavaScript. Solo funciona con una imagen cargada desde un nombre de archivo con la extensión `.jpg`, `.png`, `.gif` o `.webp` (en minúsculas o mayúsculas); otras extensiones, incluida `.jpeg`, dan un error. Para un stream o un buffer usa `Image.measure()`, y para otros formatos `identify()`.\n\nExample: Medir un archivo\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nLee el tipo y el tamaño del archivo de origen con la herramienta externa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` es `{ type, width, height }`, por ejemplo `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nEjecuta `gm identify` (o `identify` para `im` y `magick`) y analiza la primera línea. Necesita una imagen cargada desde un nombre de archivo.\n\nExample: Identificar\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nEjecuta las operaciones y guarda el resultado en un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | El archivo de destino. |\n| `callback` | `Function(err, saved)` | no |  | `saved` es `true` si tiene éxito y `false` si hay un error. |\n| `writer` | `Function(stdin)` | no |  | Recibe el stream de entrada de la herramienta, para que escribas tú mismo el origen. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\nSin `filename`, se sobrescribe el archivo de origen. El formato sigue la extensión de `filename`. Un `Image.middleware()` registrado para el tipo de salida se ejecuta después de escribir el archivo. Tras la ejecución, las operaciones se borran.\n\nExample: Guardar una copia como WebP\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nEjecuta las operaciones y envía el resultado por pipe a un stream de escritura.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un stream de escritura, por ejemplo un stream de archivo o `res`. |\n| `type` | `String` | no | `image.outputType` | Formato de salida. |\n| `options` | `Object` | no |  | Opciones de `pipe()`. |\n\nReturns: `Image` La misma imagen, para encadenar.\n\n`type` es el formato de salida: `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` o `ico`. Otro valor, o ninguno, usa `image.outputType`. `options` se pasan a `stream.pipe()`. Los errores de la herramienta se emiten como eventos `error` de `stream`.\n\nExample: Escribir en un stream de archivo\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nEjecuta las operaciones y devuelve el resultado como un stream de lectura.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Formato de salida. |\n| `writer` | `Function(stdin)` | no |  | Escribe los datos de origen. |\n\nReturns: `ReadableStream` La salida de la herramienta (a través del middleware, si hay uno registrado).\n\n`type` funciona como en `pipe()`. `writer(stdin)` te permite escribir tú mismo el origen en la herramienta.\n\nExample: Subir una imagen redimensionada\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nLimita la memoria de GraphicsMagick o ImageMagick, como porcentaje.\n\nReturns: `Number`\n\nCuando no es `0`, cada imagen sin su propio `limit()` recibe `-limit memory` (15 × valor) y `-limit map` (30 × valor). Está desactivado por defecto porque algunas versiones de GraphicsMagick fallan con estos límites. Se permite un signo `%` en el archivo de configuración.\n\nPor defecto: `0` (desactivado).\n\nExample: La mitad de los límites por defecto\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmL91hV60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Images","summary":"L'objet global Image, les méthodes d'une image et les clés de configuration des images.","markdown":"---\ntitle: Images\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Images\n\n> L'objet global Image, les méthodes d'une image et les clés de configuration des images.\n\nL'objet global `Image` charge et mesure des images, et un objet image construit les commandes pour GraphicsMagick ou ImageMagick. Le guide [Images](../../guides/images/) explique comment les utiliser avec des exemples ; cette page est la référence exacte.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nUne image avec une liste d'opérations pour GraphicsMagick ou ImageMagick.\n\nReturns: `Image`\n\nCrée-la avec `Image.load()` ; le constructeur est `Image.Image` (alias `Image.Picture`). Propriétés :\n\n- `filename` — le fichier source, ou `null` pour un stream ou un buffer\n- `outputType` — le format de sortie ; l'extension du fichier, `jpg` pour les streams et les buffers, ou la valeur de `output()`\n- `width`, `height` — les valeurs passées à `Image.load()` (elles ne sont pas mesurées)\n- `builder` — la liste des opérations ajoutées jusqu'ici\n\nToutes les méthodes d'opération renvoient l'image. Ajoute tes propres méthodes avec `F.prototypes()`, dont l'argument possède le prototype `Image`.\n\nExample: Étendre le prototype\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrée un objet image à partir d'un fichier, d'un stream ou d'un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nom de fichier, un stream lisible ou un buffer contenant l'image. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) ou `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Stocké dans `image.width` ; non utilisé par les opérations. |\n| `height` | `Number` | no |  | Stocké dans `image.height` ; non utilisé par les opérations. |\n\nReturns: `Image` Une nouvelle image.\n\nRien n'est encore lu ni exécuté. Pour un nom de fichier, le format de sortie est l'extension du fichier ; pour un stream ou un buffer, c'est `jpg` tant que tu n'appelles pas `output()`.\n\nExample: Redimensionner un fichier\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: Depuis un buffer avec ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nLa même fonction que `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nom de fichier, un stream lisible ou un buffer contenant l'image. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) ou `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Stocké dans `image.width` ; non utilisé par les opérations. |\n| `height` | `Number` | no |  | Stocké dans `image.height` ; non utilisé par les opérations. |\n\nReturns: `Image` Une nouvelle image.\n\nCrée un objet image ; les arguments et le résultat sont les mêmes que pour `Image.load()`.\n\nExample: Créer une image\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image à partir de ses premiers octets.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Extension ou type MIME. |\n| `buffer` | `Buffer` | yes |  | Le début du fichier (le fichier entier pour SVG ; pour JPEG, suffisamment d'octets pour atteindre l'en-tête de frame). |\n\nReturns: `Object` `{ width, height }`, ou `undefined`/`null` lorsqu'elle ne peut pas être lue.\n\nAppelle la fonction de mesure correspondant au type. `type` est une extension avec ou sans le point, ou un type MIME : `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). Pour les autres types, elle renvoie `undefined`. Aucun outil externe n'est nécessaire.\n\nExample: Mesurer un buffer envoyé\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image JPG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`\n\nParcourt les marqueurs JPEG jusqu'au premier en-tête de frame (SOF). Renvoie `null` lorsque le buffer n'est pas un JPEG ou que l'en-tête ne se trouve pas dans le buffer.\n\nExample: Mesurer un fichier\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image PNG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`\n\nLit la taille dans le chunk IHDR ; 24 octets suffisent.\n\nExample: Mesurer un fichier\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image GIF.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`\n\nLit la taille de l'écran logique ; 10 octets suffisent.\n\nExample: Mesurer un fichier\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image BMP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`\n\nLit la taille dans l'en-tête BMP. La hauteur est toujours positive (les bitmaps top-down ont une hauteur négative dans le fichier).\n\nExample: Mesurer un fichier\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image PSD.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`\n\nLit la taille dans l'en-tête Photoshop.\n\nExample: Mesurer un fichier\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image WebP avec ou sans perte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le début du fichier. |\n\nReturns: `Object` `{ width, height }`, ou `undefined`.\n\nPrend en charge les images WebP avec perte (`VP8 `) et sans perte (`VP8L`). Elle a besoin des 30 premiers octets. Elle renvoie `undefined` pour un en-tête inconnu.\n\nExample: Mesurer un fichier WebP\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nRenvoie la largeur et la hauteur d'une image SVG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Le fichier SVG. |\n\nReturns: `Object` `{ width, height }`, ou `undefined`.\n\nRecherche dans le texte les premiers attributs `width=\"N\"` et `height=\"N\"` avec des nombres entiers. Les unités et `viewBox` ne sont pas lus. Elle renvoie `undefined` lorsqu'il n'y a pas de tels attributs, et `0` pour un côté manquant.\n\nExample: Mesurer un SVG\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nEnregistre un stream qui traite chaque sortie d'un type donné.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Type de sortie, par exemple `png` ou `.png`. |\n| `fn` | `Function` | yes |  | Renvoie un nouveau stream de transformation. |\n\nReturns: `undefined`\n\n`fn()` doit renvoyer un nouveau stream de transformation (duplex) à chaque appel. La sortie de `pipe()` et de `stream()` pour ce type passe par celui-ci. Après `save()`, le fichier enregistré est lu, passé dans le stream et réécrit avant le callback. Un seul middleware par type ; un nouveau remplace l'ancien. Le type est comparé au type de sortie (`png`, `jpg`...) : `jpeg` et `jpg` sont donc différents.\n\nExample: Faire passer toute la sortie PNG dans un stream\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image en conservant son ratio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Largeur en pixels. Utilise `0` ou `null` pour la calculer à partir de la hauteur. |\n| `h` | `Number` | no |  | Hauteur en pixels. Omets-la pour la calculer à partir de la largeur. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` (ignorer le ratio), `>` (réduire uniquement), `<` (agrandir uniquement), `^` (remplir), `%` (pourcentage). |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-resize WxH`. Avec seulement la largeur, la hauteur est calculée, et inversement. L'image tient dans le cadre ; ajoute `options` pour changer ce comportement.\n\nExample: Tailles courantes\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nRemplit la taille et recadre le reste autour du centre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Largeur en pixels. |\n| `h` | `Number` | yes |  | Hauteur en pixels. |\n| `color` | `String` | no | `'white'` | Couleur de fond, par exemple `white` ou `#F0F0F0`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nRedimensionne avec `^` pour que l'image couvre `w` x `h`, puis recadre la partie centrale. Le résultat a exactement la taille donnée. `resize_center()` est un alias.\n\nExample: Un avatar carré\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nRemplit la taille et recadre le reste autour d'un côté ou d'un coin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Largeur en pixels. |\n| `h` | `Number` | yes |  | Hauteur en pixels. |\n| `align` | `String` | no | `'center'` | La partie à conserver. |\n| `color` | `String` | no | `'white'` | Couleur de fond, par exemple `white` ou `#F0F0F0`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nComme `resizeCenter()`, mais conserve la partie indiquée par `align` (les valeurs de `align()`, par exemple `top`, `bottom`, `top left`). `resize_align()` est un alias.\n\nExample: Conserver la partie supérieure\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nFait tenir l'image entière dans la taille et remplit la zone vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Largeur en pixels. |\n| `h` | `Number` | yes |  | Hauteur en pixels. |\n| `color` | `String` | no | `'white'` | Couleur de fond, par exemple `white` ou `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Filtre de redimensionnement. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nExécute `thumbnail(w, h)` avec le filtre, centre le résultat et l'étend à exactement `w` x `h` avec la couleur de fond. Rien n'est coupé.\n\nExample: Photo de produit sur fond blanc\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image avec l'option `-thumbnail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Largeur en pixels. Utilise `0` ou `null` pour la calculer à partir de la hauteur. |\n| `h` | `Number` | no |  | Hauteur en pixels. Omets-la pour la calculer à partir de la largeur. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` (ignorer le ratio), `>` (réduire uniquement), `<` (agrandir uniquement), `^` (remplir), `%` (pourcentage). |\n\nReturns: `Image` La même image, pour le chaînage.\n\nFonctionne comme `resize()`. L'outil supprime aussi les profils : c'est donc un bon choix pour les petits aperçus.\n\nExample: Aperçu\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nRedimensionne l'image sans filtre de rééchantillonnage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Largeur en pixels. Utilise `0` ou `null` pour la calculer à partir de la hauteur. |\n| `h` | `Number` | no |  | Hauteur en pixels. Omets-la pour la calculer à partir de la largeur. |\n| `options` | `String` | no |  | Un suffixe de la taille : `!` (ignorer le ratio), `>` (réduire uniquement), `<` (agrandir uniquement), `^` (remplir), `%` (pourcentage). |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-scale`. C'est plus rapide que `resize()` et donne une qualité inférieure.\n\nExample: Moitié de la taille\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nDécoupe un rectangle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Largeur en pixels. |\n| `h` | `Number` | yes |  | Hauteur en pixels. |\n| `x` | `Number` | no | `0` | Décalage à gauche. |\n| `y` | `Number` | no | `0` | Décalage en haut. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-crop WxH+X+Y`. Le décalage est relatif à la gravité définie avec `align()` (en haut à gauche par défaut). Le décalage doit être nul ou positif.\n\nExample: Recadrer une zone\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nDéfinit la taille du canevas.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Largeur en pixels. Utilise `0` ou `null` pour la calculer à partir de la hauteur. |\n| `h` | `Number` | no |  | Hauteur en pixels. Omets-la pour la calculer à partir de la largeur. |\n| `x` | `Number` | no |  | Décalage horizontal. |\n| `y` | `Number` | no |  | Décalage vertical. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-extent`. Un canevas plus grand est rempli avec la couleur de fond ; un canevas plus petit coupe l'image. `x` et `y` déplacent l'image (les valeurs négatives sont autorisées).\n\nExample: Canevas carré\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nDéfinit la gravité de `crop()`, `extent()` et `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La position. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-gravity`. Valeurs : `top left`, `top`, `top right`, `left`, `center` (ou `middle`), `right`, `bottom left`, `bottom`, `bottom right` ; les mots peuvent être dans n'importe quel ordre (`left top`) et `center` peut être ajouté (`top center`). Les autres valeurs sont transmises telles quelles à l'outil, par exemple `NorthEast`. `gravity()` est un alias.\n\nExample: Filigrane dans le coin\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nDéfinit le filtre de rééchantillonnage pour le redimensionnement.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Nom du filtre. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-filter`, par exemple `Lanczos`, `Box`, `Hamming`, `Triangle`. Consulte la documentation de ton outil pour tous les noms.\n\nExample: Réduction nette\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nDéfinit la qualité de compression.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | De 1 à 100. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-quality`. Sans argument, la valeur est `80`.\n\nExample: Définir la qualité\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nFait pivoter l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Degrés. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-rotate`. Les valeurs positives font pivoter dans le sens horaire. Elle s'exécute après les opérations de redimensionnement et de recadrage (priorité 8).\n\nExample: Pivoter\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nRetourne l'image verticalement (de haut en bas).\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-flip`.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nRetourne l'image horizontalement (de gauche à droite).\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-flop`.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nFloute l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Le rayon du flou. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-blur`. La valeur est transmise à l'outil : elle peut donc être un nombre ou `radiusxsigma`, par exemple `0x8`.\n\nExample: Flou\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nConvertit l'image en niveaux de gris.\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-colorspace Gray`.\n\nExample: Niveaux de gris\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nDonne à l'image un ton sépia.\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-modulate 115,0,100` et `-colorize 7,21,50`.\n\nExample: Sépia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nÉtire le contraste sur toute la plage.\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-normalize`.\n\nExample: Normaliser\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nRéduit le nombre de couleurs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Le nombre maximal de couleurs. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-colors`. Utile pour les petits fichiers PNG et GIF.\n\nExample: 256 couleurs\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nDéfinit la profondeur de bits d'un canal.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bits par canal, par exemple `8`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-depth`.\n\nExample: 8 bits\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nDéfinit la couleur de fond.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Un nom de couleur ou `#RRGGBB`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-background` et `-extent 0x0`. La couleur remplit les zones transparentes et la zone ajoutée par `extent()`, `rotate()` et `miniature()`.\n\nExample: Fond blanc\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nDéfinit la couleur de remplissage pour le dessin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Un nom de couleur ou `#RRGGBB`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-fill`. Utilise-la avec des options de `command()` qui dessinent, par exemple `-colorize`.\n\nExample: Remplissage\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDessine une autre image par-dessus celle-ci.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier du filigrane. |\n| `x` | `Number` | no | `0` | Décalage horizontal. |\n| `y` | `Number` | no | `0` | Décalage vertical. |\n| `w` | `Number` | no | `0` | Largeur du filigrane. |\n| `h` | `Number` | no | `0` | Hauteur du filigrane. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-draw` avec `image over X,Y W,H filename`. Le nom de fichier ne doit contenir ni espaces ni guillemets. La position est relative à la gravité définie par `align()`. Avec `w` et `h` à `0`, le filigrane conserve sa taille.\n\nExample: Logo dans le coin inférieur droit\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nLimite les ressources que l'outil peut utiliser.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La ressource. |\n| `value` | `Number|String` | yes |  | La limite, dans les unités de l'outil. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `-limit type value`, par exemple `memory`, `map`, `disk`, `threads`. Lorsque tu l'appelles, `default_image_consumption` n'est pas appliqué à cette image.\n\nExample: Deux threads\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nSupprime les profils et les métadonnées.\n\nReturns: `Image` La même image, pour le chaînage.\n\nAjoute `+profile \"*\"`, qui supprime les profils EXIF, ICC et autres et réduit la taille du fichier. `save()`, `pipe()` et `stream()` l'appellent d'eux-mêmes lorsque l'image n'a aucune opération.\n\nExample: Supprimer les métadonnées\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nDéfinit le format de sortie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Par exemple `png`, `webp`, `.jpg`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nModifie `image.outputType` (un point initial est supprimé). `pipe()` et `stream()` l'utilisent comme format, et `res.image()` l'utilise pour le `Content-Type`. `save()` prend le format dans l'extension du fichier cible.\n\nExample: Convertir un stream en PNG\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nAppelle une fonction avec l'image.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Ajoute les opérations. |\n\nReturns: `Image` La même image, pour le chaînage.\n\n`fn` est appelée avec l'image comme `this` et comme argument. Utilise-la pour réutiliser un ensemble d'opérations.\n\nExample: Préréglage réutilisable\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAjoute n'importe quelle option de l'outil.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | L'option, par exemple `-sharpen`. |\n| `value` | `String|Number` | no |  | La valeur de l'option. |\n| `priority` | `Number|Boolean` | no | `10` | Ordre de l'option. |\n| `escape` | `Boolean` | no | `false` | Mettre la valeur entre guillemets. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nUtilise-la pour les options sans méthode dédiée, par exemple `-strip`, `-sharpen` ou `-define`. Les options s'exécutent dans l'ordre de leur priorité (voir le guide). `escape` met la valeur entre guillemets et en retire `'` ; utilise-le pour les valeurs provenant des utilisateurs. Avec `priority` à `true`, la priorité est `0` et la valeur est échappée.\n\nExample: Netteté et entrelacement\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nSupprime toutes les opérations.\n\nReturns: `Image` La même image, pour le chaînage.\n\nVide `image.builder`. `save()` l'appelle après son exécution : un même objet image peut donc être réutilisé.\n\nExample: Recommencer\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nLit la largeur et la hauteur du fichier source.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` vaut `{ width, height }`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nLit le début du fichier et le mesure en JavaScript. Elle ne fonctionne que pour une image chargée depuis un nom de fichier avec l'extension `.jpg`, `.png`, `.gif` ou `.webp` (en minuscules ou en majuscules) ; les autres extensions, `.jpeg` compris, donnent une erreur. Pour un stream ou un buffer, utilise `Image.measure()`, et pour les autres formats `identify()`.\n\nExample: Mesurer un fichier\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nLit le type et la taille du fichier source avec l'outil externe.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` vaut `{ type, width, height }`, par exemple `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nExécute `gm identify` (ou `identify` pour `im` et `magick`) et analyse la première ligne. Elle nécessite une image chargée depuis un nom de fichier.\n\nExample: Identifier\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nExécute les opérations et enregistre le résultat dans un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | Le fichier cible. |\n| `callback` | `Function(err, saved)` | no |  | `saved` vaut `true` en cas de succès et `false` en cas d'erreur. |\n| `writer` | `Function(stdin)` | no |  | Reçoit le stream d'entrée de l'outil, pour écrire la source toi-même. |\n\nReturns: `Image` La même image, pour le chaînage.\n\nSans `filename`, le fichier source est écrasé. Le format suit l'extension de `filename`. Un `Image.middleware()` enregistré pour le type de sortie s'exécute après l'écriture du fichier. Après l'exécution, les opérations sont effacées.\n\nExample: Enregistrer une copie en WebP\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nExécute les opérations et envoie le résultat dans un stream inscriptible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Un stream inscriptible, par exemple un stream de fichier ou `res`. |\n| `type` | `String` | no | `image.outputType` | Format de sortie. |\n| `options` | `Object` | no |  | Options de `pipe()`. |\n\nReturns: `Image` La même image, pour le chaînage.\n\n`type` est le format de sortie : `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` ou `ico`. Une autre valeur, ou aucune, utilise `image.outputType`. `options` est passé à `stream.pipe()`. Les erreurs de l'outil sont émises comme événements `error` de `stream`.\n\nExample: Écrire dans un stream de fichier\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nExécute les opérations et renvoie le résultat sous forme de stream lisible.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Format de sortie. |\n| `writer` | `Function(stdin)` | no |  | Écrit les données source. |\n\nReturns: `ReadableStream` La sortie de l'outil (passée par le middleware, s'il y en a un d'enregistré).\n\n`type` fonctionne comme dans `pipe()`. `writer(stdin)` permet d'écrire toi-même la source dans l'outil.\n\nExample: Envoyer une image redimensionnée\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nLimite la mémoire de GraphicsMagick ou d'ImageMagick, en pourcentage.\n\nReturns: `Number`\n\nLorsqu'elle ne vaut pas `0`, chaque image sans son propre `limit()` reçoit `-limit memory` (15 × valeur) et `-limit map` (30 × valeur). Elle est désactivée par défaut, car certaines versions de GraphicsMagick échouent avec ces limites. Un signe `%` est autorisé dans le fichier de configuration.\n\nValeur par défaut : `0` (désactivée).\n\nExample: La moitié des limites par défaut\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmL91hV60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Immagini","summary":"L'oggetto globale Image, i metodi di un'immagine e le chiavi di configurazione delle immagini.","markdown":"---\ntitle: Immagini\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Immagini\n\n> L'oggetto globale Image, i metodi di un'immagine e le chiavi di configurazione delle immagini.\n\nL'oggetto globale `Image` carica e misura le immagini, e un oggetto immagine costruisce i comandi per GraphicsMagick o ImageMagick. La guida [Immagini](../../guides/images/) spiega come usarli con degli esempi; questa pagina è il riferimento esatto.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nUn'immagine con un elenco di operazioni per GraphicsMagick o ImageMagick.\n\nReturns: `Image`\n\nCreala con `Image.load()`; il costruttore è `Image.Image` (alias `Image.Picture`). Proprietà:\n\n- `filename` — il file sorgente, oppure `null` per uno stream o un buffer\n- `outputType` — il formato di output; l'estensione del file, `jpg` per stream e buffer, oppure il valore di `output()`\n- `width`, `height` — i valori passati a `Image.load()` (non vengono misurati)\n- `builder` — l'elenco delle operazioni aggiunte finora\n\nTutti i metodi delle operazioni restituiscono l'immagine. Aggiungi i tuoi metodi con `F.prototypes()`, il cui argomento ha il prototipo `Image`.\n\nExample: Estendere il prototipo\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nCrea un oggetto immagine da un file, uno stream o un buffer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nome di file, uno stream leggibile o un buffer con l'immagine. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) o `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Salvato in `image.width`; non usato dalle operazioni. |\n| `height` | `Number` | no |  | Salvato in `image.height`; non usato dalle operazioni. |\n\nReturns: `Image` Una nuova immagine.\n\nNon viene ancora letto né eseguito nulla. Per un nome di file, il formato di output è l'estensione del file; per uno stream o un buffer, è `jpg` finché non chiami `output()`.\n\nExample: Ridimensionare un file\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: Da un buffer con ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nLa stessa funzione di `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Un nome di file, uno stream leggibile o un buffer con l'immagine. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) o `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Salvato in `image.width`; non usato dalle operazioni. |\n| `height` | `Number` | no |  | Salvato in `image.height`; non usato dalle operazioni. |\n\nReturns: `Image` Una nuova immagine.\n\nCrea un oggetto immagine; gli argomenti e il risultato sono gli stessi di `Image.load()`.\n\nExample: Creare un'immagine\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine a partire dai suoi primi byte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Estensione o tipo MIME. |\n| `buffer` | `Buffer` | yes |  | L'inizio del file (l'intero file per SVG; per JPEG, abbastanza byte da raggiungere l'header del frame). |\n\nReturns: `Object` `{ width, height }`, oppure `undefined`/`null` quando non può essere letto.\n\nChiama la funzione di misura per il tipo. `type` è un'estensione con o senza punto, oppure un tipo MIME: `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). Per gli altri tipi restituisce `undefined`. Non serve alcuno strumento esterno.\n\nExample: Misurare un buffer caricato\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine JPG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`\n\nScorre i marker JPEG fino al primo header di frame (SOF). Restituisce `null` quando il buffer non è un JPEG o l'header non si trova nel buffer.\n\nExample: Misurare un file\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine PNG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`\n\nLegge le dimensioni dal chunk IHDR; bastano 24 byte.\n\nExample: Misurare un file\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine GIF.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`\n\nLegge le dimensioni dello schermo logico; bastano 10 byte.\n\nExample: Misurare un file\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine BMP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`\n\nLegge le dimensioni dall'header BMP. L'altezza è sempre positiva (le bitmap top-down hanno un'altezza negativa nel file).\n\nExample: Misurare un file\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine PSD.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`\n\nLegge le dimensioni dall'header di Photoshop.\n\nExample: Misurare un file\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nRestituisce la larghezza e l'altezza di un'immagine WebP lossy o lossless.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | L'inizio del file. |\n\nReturns: `Object` `{ width, height }`, oppure `undefined`.\n\nSupporta immagini WebP lossy (`VP8 `) e lossless (`VP8L`). Servono i primi 30 byte. Restituisce `undefined` per un'intestazione sconosciuta.\n\nExample: Misurare un file WebP\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nRestituisce larghezza e altezza di un'immagine SVG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Il file SVG. |\n\nReturns: `Object` `{ width, height }`, oppure `undefined`.\n\nCerca nel testo i primi attributi `width=\"N\"` e `height=\"N\"` con numeri interi. Le unità e `viewBox` non vengono letti. Restituisce `undefined` quando questi attributi non ci sono, e `0` per un lato mancante.\n\nExample: Misurare un SVG\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nRegistra uno stream che elabora ogni output di un tipo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Tipo di output, per esempio `png` o `.png`. |\n| `fn` | `Function` | yes |  | Restituisce un nuovo stream di trasformazione. |\n\nReturns: `undefined`\n\n`fn()` deve restituire un nuovo stream di trasformazione (duplex) a ogni chiamata. L'output di `pipe()` e `stream()` per quel tipo passa attraverso di esso. Dopo `save()`, il file salvato viene letto, passato attraverso lo stream e scritto di nuovo prima della callback. Un solo middleware per tipo; uno nuovo sostituisce il precedente. Il tipo viene confrontato con il tipo di output (`png`, `jpg`...), quindi `jpeg` e `jpg` sono diversi.\n\nExample: Far passare tutto l'output PNG attraverso uno stream\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine mantenendo le proporzioni.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Larghezza in pixel. Usa `0` o `null` per calcolarla dall'altezza. |\n| `h` | `Number` | no |  | Altezza in pixel. Omettila per calcolarla dalla larghezza. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` (ignora le proporzioni), `>` (solo riduce), `<` (solo ingrandisce), `^` (riempie), `%` (percentuale). |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-resize WxH`. Con la sola larghezza, l'altezza viene calcolata, e viceversa. L'immagine si adatta al riquadro; aggiungi `options` per cambiare questo comportamento.\n\nExample: Dimensioni comuni\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nRiempie la dimensione e ritaglia il resto attorno al centro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Larghezza in pixel. |\n| `h` | `Number` | yes |  | Altezza in pixel. |\n| `color` | `String` | no | `'white'` | Colore di sfondo, per esempio `white` o `#F0F0F0`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nRidimensiona con `^` in modo che l'immagine copra `w` x `h`, poi ritaglia la parte centrale. Il risultato ha esattamente la dimensione indicata. `resize_center()` è un alias.\n\nExample: Un avatar quadrato\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nRiempie la dimensione e ritaglia il resto attorno a un lato o a un angolo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Larghezza in pixel. |\n| `h` | `Number` | yes |  | Altezza in pixel. |\n| `align` | `String` | no | `'center'` | Quale parte mantenere. |\n| `color` | `String` | no | `'white'` | Colore di sfondo, per esempio `white` o `#F0F0F0`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nCome `resizeCenter()`, ma mantiene la parte indicata da `align` (i valori di `align()`, per esempio `top`, `bottom`, `top left`). `resize_align()` è un alias.\n\nExample: Mantenere la parte superiore\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nAdatta l'intera immagine alla dimensione e riempie l'area vuota.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Larghezza in pixel. |\n| `h` | `Number` | yes |  | Altezza in pixel. |\n| `color` | `String` | no | `'white'` | Colore di sfondo, per esempio `white` o `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Filtro di ridimensionamento. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nEsegue `thumbnail(w, h)` con il filtro, centra il risultato e lo estende esattamente a `w` x `h` con il colore di sfondo. Non viene tagliato nulla.\n\nExample: Foto di prodotto su bianco\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine con l'opzione `-thumbnail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Larghezza in pixel. Usa `0` o `null` per calcolarla dall'altezza. |\n| `h` | `Number` | no |  | Altezza in pixel. Omettila per calcolarla dalla larghezza. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` (ignora le proporzioni), `>` (solo riduce), `<` (solo ingrandisce), `^` (riempie), `%` (percentuale). |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nFunziona come `resize()`. Lo strumento rimuove anche i profili, quindi è una buona scelta per piccole anteprime.\n\nExample: Anteprima\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nRidimensiona l'immagine senza filtro di ricampionamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Larghezza in pixel. Usa `0` o `null` per calcolarla dall'altezza. |\n| `h` | `Number` | no |  | Altezza in pixel. Omettila per calcolarla dalla larghezza. |\n| `options` | `String` | no |  | Un suffisso della dimensione: `!` (ignora le proporzioni), `>` (solo riduce), `<` (solo ingrandisce), `^` (riempie), `%` (percentuale). |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-scale`. È più veloce di `resize()` e dà una qualità inferiore.\n\nExample: Metà dimensione\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nRitaglia un rettangolo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Larghezza in pixel. |\n| `h` | `Number` | yes |  | Altezza in pixel. |\n| `x` | `Number` | no | `0` | Offset da sinistra. |\n| `y` | `Number` | no | `0` | Offset dall'alto. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-crop WxH+X+Y`. L'offset è relativo alla gravity impostata con `align()` (in alto a sinistra per impostazione predefinita). L'offset deve essere zero o positivo.\n\nExample: Ritagliare una regione\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nImposta la dimensione della tela.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Larghezza in pixel. Usa `0` o `null` per calcolarla dall'altezza. |\n| `h` | `Number` | no |  | Altezza in pixel. Omettila per calcolarla dalla larghezza. |\n| `x` | `Number` | no |  | Offset orizzontale. |\n| `y` | `Number` | no |  | Offset verticale. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-extent`. Una tela più grande viene riempita con il colore di sfondo; una più piccola taglia l'immagine. `x` e `y` spostano l'immagine (sono ammessi valori negativi).\n\nExample: Tela quadrata\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nImposta la gravity di `crop()`, `extent()` e `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La posizione. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-gravity`. Valori: `top left`, `top`, `top right`, `left`, `center` (o `middle`), `right`, `bottom left`, `bottom`, `bottom right`; le parole possono essere in qualsiasi ordine (`left top`) e si può aggiungere `center` (`top center`). Gli altri valori passano allo strumento invariati, per esempio `NorthEast`. `gravity()` è un alias.\n\nExample: Filigrana nell'angolo\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nImposta il filtro di ricampionamento per il ridimensionamento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Nome del filtro. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-filter`, per esempio `Lanczos`, `Box`, `Hamming`, `Triangle`. Consulta la documentazione del tuo strumento per tutti i nomi.\n\nExample: Riduzione nitida\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nImposta la qualità di compressione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | Da 1 a 100. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-quality`. Senza argomento, il valore è `80`.\n\nExample: Impostare la qualità\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nRuota l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Gradi. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-rotate`. I valori positivi ruotano in senso orario. Viene eseguito dopo le operazioni di ridimensionamento e ritaglio (priorità 8).\n\nExample: Ruotare\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nSpecchia l'immagine verticalmente (dall'alto in basso).\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-flip`.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nSpecchia l'immagine orizzontalmente (da sinistra a destra).\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-flop`.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nSfoca l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Il raggio della sfocatura. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-blur`. Il valore viene passato allo strumento, quindi può essere un numero o `radiusxsigma`, per esempio `0x8`.\n\nExample: Sfocare\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nConverte l'immagine in scala di grigi.\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-colorspace Gray`.\n\nExample: Grigio\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nDà all'immagine un tono seppia.\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-modulate 115,0,100` e `-colorize 7,21,50`.\n\nExample: Seppia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nEstende il contrasto all'intera gamma.\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-normalize`.\n\nExample: Normalizzare\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nRiduce il numero di colori.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Il numero massimo di colori. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-colors`. Utile per piccoli file PNG e GIF.\n\nExample: 256 colori\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nImposta la profondità di bit di un canale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bit per canale, per esempio `8`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-depth`.\n\nExample: 8 bit\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nImposta il colore di sfondo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Il nome di un colore o `#RRGGBB`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-background` e `-extent 0x0`. Il colore riempie le aree trasparenti e l'area aggiunta da `extent()`, `rotate()` e `miniature()`.\n\nExample: Sfondo bianco\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nImposta il colore di riempimento per il disegno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Il nome di un colore o `#RRGGBB`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-fill`. Usalo con le opzioni di `command()` che disegnano, per esempio `-colorize`.\n\nExample: Riempimento\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nDisegna un'altra immagine sopra questa.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file della filigrana. |\n| `x` | `Number` | no | `0` | Offset orizzontale. |\n| `y` | `Number` | no | `0` | Offset verticale. |\n| `w` | `Number` | no | `0` | Larghezza della filigrana. |\n| `h` | `Number` | no | `0` | Altezza della filigrana. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-draw` con `image over X,Y W,H filename`. Il nome del file non deve contenere spazi né virgolette. La posizione è relativa alla gravity di `align()`. Con `w` e `h` impostati a `0`, la filigrana mantiene le sue dimensioni.\n\nExample: Logo nell'angolo in basso a destra\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nLimita le risorse che lo strumento può usare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | La risorsa. |\n| `value` | `Number|String` | yes |  | Il limite, nelle unità dello strumento. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `-limit type value`, per esempio `memory`, `map`, `disk`, `threads`. Quando la chiami, `default_image_consumption` non viene applicato a questa immagine.\n\nExample: Due thread\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nRimuove i profili e i metadati.\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nAggiunge `+profile \"*\"`, che rimuove EXIF, ICC e altri profili e rende il file più piccolo. `save()`, `pipe()` e `stream()` la chiamano da soli quando l'immagine non ha alcuna operazione.\n\nExample: Rimuovere i metadati\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nImposta il formato di output.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Per esempio `png`, `webp`, `.jpg`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nCambia `image.outputType` (un punto iniziale viene rimosso). `pipe()` e `stream()` lo usano come formato, e `res.image()` lo usa per il `Content-Type`. `save()` prende il formato dall'estensione del file di destinazione.\n\nExample: Convertire uno stream in PNG\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nChiama una funzione con l'immagine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Aggiunge le operazioni. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\n`fn` viene chiamata con l'immagine come `this` e come argomento. Usala per riutilizzare un insieme di operazioni.\n\nExample: Preset riutilizzabile\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nAggiunge qualsiasi opzione dello strumento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | L'opzione, per esempio `-sharpen`. |\n| `value` | `String|Number` | no |  | Il valore dell'opzione. |\n| `priority` | `Number|Boolean` | no | `10` | Ordine dell'opzione. |\n| `escape` | `Boolean` | no | `false` | Mette il valore tra virgolette. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nUsala per le opzioni senza un metodo dedicato, per esempio `-strip`, `-sharpen` o `-define`. Le opzioni vengono eseguite nell'ordine della loro priorità (vedi la guida). `escape` mette il valore tra virgolette e ne rimuove `'`; usalo per i valori che arrivano dagli utenti. Con `priority` impostato a `true`, la priorità è `0` e il valore viene sottoposto a escape.\n\nExample: Nitidezza e interlacciamento\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nRimuove tutte le operazioni.\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nSvuota `image.builder`. `save()` la chiama dopo l'esecuzione, così lo stesso oggetto immagine può essere riutilizzato.\n\nExample: Ricominciare\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nLegge larghezza e altezza del file sorgente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` è `{ width, height }`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nLegge l'inizio del file e lo misura in JavaScript. Funziona solo per un'immagine caricata da un nome di file con estensione `.jpg`, `.png`, `.gif` o `.webp` (minuscola o maiuscola); le altre estensioni, compresa `.jpeg`, danno un errore. Per uno stream o un buffer usa `Image.measure()`, e per gli altri formati `identify()`.\n\nExample: Misurare un file\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nLegge il tipo e le dimensioni del file sorgente con lo strumento esterno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` è `{ type, width, height }`, per esempio `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nEsegue `gm identify` (o `identify` per `im` e `magick`) e analizza la prima riga. Richiede un'immagine caricata da un nome di file.\n\nExample: Identificare\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nEsegue le operazioni e salva il risultato in un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | Il file di destinazione. |\n| `callback` | `Function(err, saved)` | no |  | `saved` è `true` in caso di successo e `false` in caso di errore. |\n| `writer` | `Function(stdin)` | no |  | Riceve lo stream di input dello strumento, per scrivere tu la sorgente. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\nSenza `filename`, il file sorgente viene sovrascritto. Il formato segue l'estensione di `filename`. Un `Image.middleware()` registrato per il tipo di output viene eseguito dopo la scrittura del file. Dopo l'esecuzione, le operazioni vengono cancellate.\n\nExample: Salvare una copia come WebP\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nEsegue le operazioni e invia il risultato in pipe a uno stream scrivibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Uno stream scrivibile, per esempio uno stream di file o `res`. |\n| `type` | `String` | no | `image.outputType` | Formato di output. |\n| `options` | `Object` | no |  | Opzioni di `pipe()`. |\n\nReturns: `Image` La stessa immagine, per concatenare le chiamate.\n\n`type` è il formato di output: `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` o `ico`. Un altro valore o nessun valore usa `image.outputType`. `options` vengono passate a `stream.pipe()`. Gli errori dello strumento vengono emessi come eventi `error` di `stream`.\n\nExample: Scrivere in uno stream di file\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nEsegue le operazioni e restituisce il risultato come stream leggibile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Formato di output. |\n| `writer` | `Function(stdin)` | no |  | Scrive i dati sorgente. |\n\nReturns: `ReadableStream` L'output dello strumento (attraverso il middleware, se ne è registrato uno).\n\n`type` funziona come in `pipe()`. `writer(stdin)` ti permette di scrivere tu la sorgente nello strumento.\n\nExample: Caricare un'immagine ridimensionata\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nLimita la memoria di GraphicsMagick o ImageMagick, in percentuale.\n\nReturns: `Number`\n\nQuando non è `0`, ogni immagine senza un proprio `limit()` riceve `-limit memory` (15 × valore) e `-limit map` (30 × valore). È disattivata per impostazione predefinita perché alcune versioni di GraphicsMagick falliscono con questi limiti. Nel file di configurazione è ammesso il segno `%`.\n\nPredefinito: `0` (disattivato).\n\nExample: Metà dei limiti predefiniti\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmL91hV60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/images/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Obrázky","summary":"Globálny objekt Image, metódy obrázka a konfiguračné kľúče pre obrázky.","markdown":"---\ntitle: \"Obrázky\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/images/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Obrázky\n\n> Globálny objekt Image, metódy obrázka a konfiguračné kľúče pre obrázky.\n\nGlobálny objekt `Image` načítava a meria obrázky a objekt obrázka zostavuje príkazy pre GraphicsMagick alebo ImageMagick. Príručka [Obrázky](../../guides/images/) vysvetľuje ich použitie na príkladoch; táto stránka je presná referencia.\n\n## API\n\n### new Image.Image(source, [converter], [width], [height])\n\nType: `class`\n\nObrázok so zoznamom operácií pre GraphicsMagick alebo ImageMagick.\n\nReturns: `Image`\n\nVytvoríš ho pomocou `Image.load()`; konštruktor je `Image.Image` (alias `Image.Picture`). Vlastnosti:\n\n- `filename` — zdrojový súbor, alebo `null` pre stream alebo buffer\n- `outputType` — výstupný formát; prípona súboru, `jpg` pre streamy a buffery, alebo hodnota `output()`\n- `width`, `height` — hodnoty odovzdané do `Image.load()` (nemerajú sa)\n- `builder` — zoznam doteraz pridaných operácií\n\nVšetky metódy operácií vracajú obrázok. Vlastné metódy pridáš pomocou `F.prototypes()`, ktorej argument má prototyp `Image`.\n\nExample: Rozšírenie prototypu\n```js\nF.prototypes(function(proto) {\n\tproto.Image.avatar = function() {\n\t\treturn this.resizeCenter(128, 128).quality(80);\n\t};\n});\n\nImage.load(filename).avatar().save(target);\n```\n\n### Image.load(source, [converter], [width], [height])\n\nType: `method`\n\nVytvorí objekt obrázka zo súboru, streamu alebo buffera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Názov súboru, čitateľný stream alebo buffer s obrázkom. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) alebo `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Uloží sa do `image.width`; operácie ho nepoužívajú. |\n| `height` | `Number` | no |  | Uloží sa do `image.height`; operácie ho nepoužívajú. |\n\nReturns: `Image` Nový obrázok.\n\nZatiaľ sa nič nečíta ani nespúšťa. Pri názve súboru je výstupným formátom prípona súboru; pri streame alebo bufferi je to `jpg`, kým nezavoláš `output()`.\n\nExample: Zmena veľkosti súboru\n```js\nImage.load(PATH.public('photos/1.jpg')).resize(640).save(PATH.public('photos/1-small.jpg'));\n```\n\nExample: Z buffera s ImageMagick 7\n```js\nvar image = Image.load(buffer, 'magick');\nimage.output('png');\nimage.resize(64, 64);\nimage.pipe(res);\n```\n\n### Image.init(source, [converter], [width], [height])\n\nType: `method`\n\nTá istá funkcia ako `Image.load()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String|Stream|Buffer` | yes |  | Názov súboru, čitateľný stream alebo buffer s obrázkom. |\n| `converter` | `String` | no | `CONF.default_image_converter` | `gm` (GraphicsMagick), `im` (ImageMagick 6, `convert`) alebo `magick` (ImageMagick 7). |\n| `width` | `Number` | no |  | Uloží sa do `image.width`; operácie ho nepoužívajú. |\n| `height` | `Number` | no |  | Uloží sa do `image.height`; operácie ho nepoužívajú. |\n\nReturns: `Image` Nový obrázok.\n\nVytvorí objekt obrázka; argumenty aj výsledok sú rovnaké ako pri `Image.load()`.\n\nExample: Vytvorenie obrázka\n```js\nvar image = Image.init(filename);\nimage.grayscale().save(filename);\n```\n\n### Image.measure(type, buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka z jeho prvých bajtov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Prípona alebo MIME typ. |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru (pri SVG celý súbor; pri JPEG dosť bajtov na dosiahnutie hlavičky rámca). |\n\nReturns: `Object` `{ width, height }`, alebo `undefined`/`null`, keď sa nedá prečítať.\n\nZavolá meraciu funkciu pre daný typ. `type` je prípona s bodkou alebo bez nej, alebo MIME typ: `jpg`, `jpeg`, `png`, `gif`, `svg`, `webp`, `bmp`, `psd` (`image/jpeg`, `image/png`, `image/gif`, `image/svg+xml`, `image/webp`, `image/bmp`, `image/vnd.adobe.photoshop`). Pre iné typy vráti `undefined`. Nie je potrebný žiadny externý nástroj.\n\nExample: Zmeranie nahraného buffera\n```js\nvar size = Image.measure('image/png', buffer);\nif (size && size.width > 2000)\n\tconsole.log('Too large');\n```\n\n### Image.measureJPG(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka JPG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`\n\nPrechádza značky JPEG až po prvú hlavičku rámca (SOF). Vráti `null`, keď buffer nie je JPEG alebo hlavička nie je v bufferi.\n\nExample: Zmeranie súboru\n```js\nvar size = Image.measureJPG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePNG(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka PNG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`\n\nPrečíta veľkosť z chunku IHDR; stačí 24 bajtov.\n\nExample: Zmeranie súboru\n```js\nvar size = Image.measurePNG(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureGIF(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka GIF.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`\n\nPrečíta logickú veľkosť obrazovky; stačí 10 bajtov.\n\nExample: Zmeranie súboru\n```js\nvar size = Image.measureGIF(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureBMP(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka BMP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`\n\nPrečíta veľkosť z hlavičky BMP. Výška je vždy kladná (bitmapy zhora nadol majú v súbore zápornú výšku).\n\nExample: Zmeranie súboru\n```js\nvar size = Image.measureBMP(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measurePSD(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka PSD.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }`\n\nPrečíta veľkosť z hlavičky Photoshopu.\n\nExample: Zmeranie súboru\n```js\nvar size = Image.measurePSD(Fs.readFileSync(filename));\nconsole.log(size.width, size.height);\n```\n\n### Image.measureWEBP(buffer)\n\nType: `method`\n\nVráti šírku a výšku stratového alebo bezstratového obrázka WebP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Začiatok súboru. |\n\nReturns: `Object` `{ width, height }` alebo `undefined`.\n\nPodporuje stratové (`VP8 `) a bezstratové (`VP8L`) obrázky WebP. Potrebuje prvých 30 bajtov. Pri neznámej hlavičke vráti `undefined`.\n\nExample: Zmeranie súboru WebP\n```js\nvar size = Image.measureWEBP(Fs.readFileSync(PATH.public('img/hero.webp')));\n```\n\n### Image.measureSVG(buffer)\n\nType: `method`\n\nVráti šírku a výšku obrázka SVG.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `buffer` | `Buffer` | yes |  | Súbor SVG. |\n\nReturns: `Object` `{ width, height }`, alebo `undefined`.\n\nHľadá v texte prvé atribúty `width=\"N\"` a `height=\"N\"` s celými číslami. Jednotky a `viewBox` sa nečítajú. Vráti `undefined`, keď takéto atribúty neexistujú, a `0` pre chýbajúci rozmer.\n\nExample: Zmeranie SVG\n```js\nvar size = Image.measureSVG(Buffer.from('<svg width=\"120\" height=\"40\"></svg>'));\n// { width: 120, height: 40 }\n```\n\n### Image.middleware(type, fn)\n\nType: `method`\n\nZaregistruje stream, ktorý spracuje každý výstup daného typu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Výstupný typ, napríklad `png` alebo `.png`. |\n| `fn` | `Function` | yes |  | Vracia nový transformačný stream. |\n\nReturns: `undefined`\n\n`fn()` musí pri každom volaní vrátiť nový transformačný (duplex) stream. Výstup `pipe()` a `stream()` pre daný typ ním prechádza. Po `save()` sa uložený súbor prečíta, prejde streamom a pred callbackom sa zapíše znova. Pre jeden typ je len jeden middleware; nový nahradí starý. Typ sa porovnáva s výstupným typom (`png`, `jpg`...), takže `jpeg` a `jpg` sú rozdielne.\n\nExample: Prechod všetkého PNG výstupu cez stream\n```js\nvar Stream = require('stream');\n\nImage.middleware('png', function() {\n\treturn new Stream.PassThrough();\n});\n```\n\n### image.resize([w], [h], [options])\n\nType: `method`\n\nZmení veľkosť obrázka a zachová jeho pomer strán.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Šírka v pixeloch. Použi `0` alebo `null`, aby sa dopočítala z výšky. |\n| `h` | `Number` | no |  | Výška v pixeloch. Vynechaj ju, aby sa dopočítala zo šírky. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` (ignoruje pomer strán), `>` (iba zmenšuje), `<` (iba zväčšuje), `^` (vyplní), `%` (percentá). |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-resize WxH`. Ak zadáš iba šírku, výška sa dopočíta, a naopak. Obrázok sa vojde do rámca; na zmenu pridaj `options`.\n\nExample: Bežné veľkosti\n```js\nimage.resize(800);           // width 800\nimage.resize(null, 600);     // height 600\nimage.resize(800, 600, '!'); // exactly 800x600\nimage.resize(1920, 1920, '>'); // only shrink\n```\n\n### image.resizeCenter(w, h, [color])\n\nType: `method`\n\nVyplní veľkosť a zvyšok oreže okolo stredu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka v pixeloch. |\n| `h` | `Number` | yes |  | Výška v pixeloch. |\n| `color` | `String` | no | `'white'` | Farba pozadia, napríklad `white` alebo `#F0F0F0`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nZmení veľkosť s `^`, aby obrázok pokryl `w` x `h`, potom oreže strednú časť. Výsledok má presne zadanú veľkosť. `resize_center()` je alias.\n\nExample: Štvorcový avatar\n```js\nImage.load(filename).resizeCenter(200, 200).save(target);\n```\n\n### image.resizeAlign(w, h, [align], [color])\n\nType: `method`\n\nVyplní veľkosť a zvyšok oreže okolo strany alebo rohu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka v pixeloch. |\n| `h` | `Number` | yes |  | Výška v pixeloch. |\n| `align` | `String` | no | `'center'` | Ktorú časť zachovať. |\n| `color` | `String` | no | `'white'` | Farba pozadia, napríklad `white` alebo `#F0F0F0`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nAko `resizeCenter()`, ale zachová časť danú `align` (hodnoty `align()`, napríklad `top`, `bottom`, `top left`). `resize_align()` je alias.\n\nExample: Zachovanie hornej časti\n```js\nimage.resizeAlign(1200, 400, 'top');\n```\n\n### image.miniature(w, h, [color], [filter])\n\nType: `method`\n\nVloží celý obrázok do veľkosti a vyplní prázdnu plochu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka v pixeloch. |\n| `h` | `Number` | yes |  | Výška v pixeloch. |\n| `color` | `String` | no | `'white'` | Farba pozadia, napríklad `white` alebo `#F0F0F0`. |\n| `filter` | `String` | no | `'Hamming'` | Filter pre zmenu veľkosti. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nSpustí `thumbnail(w, h)` s filtrom, vycentruje výsledok a rozšíri ho na presne `w` x `h` farbou pozadia. Nič sa neoreže.\n\nExample: Obrázok produktu na bielom pozadí\n```js\nimage.miniature(300, 300);\nimage.miniature(300, 300, '#000000', 'Lanczos');\n```\n\n### image.thumbnail([w], [h], [options])\n\nType: `method`\n\nZmení veľkosť obrázka s voľbou `-thumbnail`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Šírka v pixeloch. Použi `0` alebo `null`, aby sa dopočítala z výšky. |\n| `h` | `Number` | no |  | Výška v pixeloch. Vynechaj ju, aby sa dopočítala zo šírky. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` (ignoruje pomer strán), `>` (iba zmenšuje), `<` (iba zväčšuje), `^` (vyplní), `%` (percentá). |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nFunguje ako `resize()`. Nástroj navyše odstráni profily, takže je to dobrá voľba pre malé náhľady.\n\nExample: Náhľad\n```js\nimage.thumbnail(150, 150);\n```\n\n### image.scale([w], [h], [options])\n\nType: `method`\n\nZmení veľkosť obrázka bez prevzorkovacieho filtra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Šírka v pixeloch. Použi `0` alebo `null`, aby sa dopočítala z výšky. |\n| `h` | `Number` | no |  | Výška v pixeloch. Vynechaj ju, aby sa dopočítala zo šírky. |\n| `options` | `String` | no |  | Prípona veľkosti: `!` (ignoruje pomer strán), `>` (iba zmenšuje), `<` (iba zväčšuje), `^` (vyplní), `%` (percentá). |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-scale`. Je rýchlejšia ako `resize()` a dáva nižšiu kvalitu.\n\nExample: Polovičná veľkosť\n```js\nimage.scale(50, 50, '%');\n```\n\n### image.crop(w, h, [x], [y])\n\nType: `method`\n\nVyreže obdĺžnik.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | yes |  | Šírka v pixeloch. |\n| `h` | `Number` | yes |  | Výška v pixeloch. |\n| `x` | `Number` | no | `0` | Posun zľava. |\n| `y` | `Number` | no | `0` | Posun zhora. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-crop WxH+X+Y`. Posun je relatívny voči gravitácii nastavenej pomocou `align()` (predvolene vľavo hore). Posun musí byť nulový alebo kladný.\n\nExample: Orezanie oblasti\n```js\nimage.crop(400, 300, 50, 20);\n```\n\n### image.extent([w], [h], [x], [y])\n\nType: `method`\n\nNastaví veľkosť plátna.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `w` | `Number` | no |  | Šírka v pixeloch. Použi `0` alebo `null`, aby sa dopočítala z výšky. |\n| `h` | `Number` | no |  | Výška v pixeloch. Vynechaj ju, aby sa dopočítala zo šírky. |\n| `x` | `Number` | no |  | Vodorovný posun. |\n| `y` | `Number` | no |  | Zvislý posun. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-extent`. Väčšie plátno sa vyplní farbou pozadia; menšie obrázok oreže. `x` a `y` posúvajú obrázok (záporné hodnoty sú povolené).\n\nExample: Štvorcové plátno\n```js\nimage.background('white').align('center').extent(500, 500);\n```\n\n### image.align(type)\n\nType: `method`\n\nNastaví gravitáciu pre `crop()`, `extent()` a `watermark()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Pozícia. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-gravity`. Hodnoty: `top left`, `top`, `top right`, `left`, `center` (alebo `middle`), `right`, `bottom left`, `bottom`, `bottom right`; slová môžu byť v ľubovoľnom poradí (`left top`) a môžeš pridať `center` (`top center`). Iné hodnoty idú do nástroja bez zmeny, napríklad `NorthEast`. `gravity()` je alias.\n\nExample: Vodoznak v rohu\n```js\nimage.align('bottom right');\nimage.watermark(PATH.public('img/logo.png'), 10, 10);\n```\n\n### image.filter(type)\n\nType: `method`\n\nNastaví prevzorkovací filter pre zmenu veľkosti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Názov filtra. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-filter`, napríklad `Lanczos`, `Box`, `Hamming`, `Triangle`. Všetky názvy nájdeš v dokumentácii svojho nástroja.\n\nExample: Ostré zmenšenie\n```js\nimage.filter('Lanczos').resize(800);\n```\n\n### image.quality([percentage])\n\nType: `method`\n\nNastaví kvalitu kompresie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `percentage` | `Number` | no | `80` | Od 1 do 100. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-quality`. Bez argumentu je hodnota `80`.\n\nExample: Nastavenie kvality\n```js\nimage.quality(85);\n```\n\n### image.rotate(deg)\n\nType: `method`\n\nOtočí obrázok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `deg` | `Number` | yes | `0` | Stupne. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-rotate`. Kladné hodnoty otáčajú v smere hodinových ručičiek. Spustí sa po operáciách zmeny veľkosti a orezania (priorita 8).\n\nExample: Otočenie\n```js\nimage.rotate(90);\n```\n\n### image.flip()\n\nType: `method`\n\nZrkadlí obrázok zvisle (zhora nadol).\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-flip`.\n\nExample: Flip\n```js\nimage.flip();\n```\n\n### image.flop()\n\nType: `method`\n\nZrkadlí obrázok vodorovne (zľava doprava).\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-flop`.\n\nExample: Flop\n```js\nimage.flop();\n```\n\n### image.blur(radius)\n\nType: `method`\n\nRozmaže obrázok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `radius` | `Number|String` | yes |  | Polomer rozmazania. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-blur`. Hodnota sa odovzdá nástroju, takže môže byť číslo alebo `radiusxsigma`, napríklad `0x8`.\n\nExample: Rozmazanie\n```js\nimage.blur('0x8');\n```\n\n### image.grayscale()\n\nType: `method`\n\nPrevedie obrázok do odtieňov sivej.\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-colorspace Gray`.\n\nExample: Odtiene sivej\n```js\nimage.grayscale();\n```\n\n### image.sepia()\n\nType: `method`\n\nDá obrázku tón sépie.\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-modulate 115,0,100` a `-colorize 7,21,50`.\n\nExample: Sépia\n```js\nimage.sepia();\n```\n\n### image.normalize()\n\nType: `method`\n\nRoztiahne kontrast na celý rozsah.\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-normalize`.\n\nExample: Normalizácia\n```js\nimage.normalize();\n```\n\n### image.colors(value)\n\nType: `method`\n\nZníži počet farieb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Maximálny počet farieb. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-colors`. Užitočné pre malé súbory PNG a GIF.\n\nExample: 256 farieb\n```js\nimage.output('png').colors(256);\n```\n\n### image.bitdepth(value)\n\nType: `method`\n\nNastaví bitovú hĺbku kanála.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number` | yes |  | Bity na kanál, napríklad `8`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-depth`.\n\nExample: 8 bitov\n```js\nimage.bitdepth(8);\n```\n\n### image.background(color)\n\nType: `method`\n\nNastaví farbu pozadia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Názov farby alebo `#RRGGBB`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-background` a `-extent 0x0`. Farba vyplní priehľadné oblasti a plochu pridanú pomocou `extent()`, `rotate()` a `miniature()`.\n\nExample: Biele pozadie\n```js\nimage.background('#FFFFFF');\n```\n\n### image.fill(color)\n\nType: `method`\n\nNastaví farbu výplne pre kreslenie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `color` | `String` | yes |  | Názov farby alebo `#RRGGBB`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-fill`. Použi ju s voľbami `command()`, ktoré kreslia, napríklad `-colorize`.\n\nExample: Výplň\n```js\nimage.fill('red');\n```\n\n### image.watermark(filename, [x], [y], [w], [h])\n\nType: `method`\n\nNakreslí iný obrázok cez tento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor vodoznaku. |\n| `x` | `Number` | no | `0` | Vodorovný posun. |\n| `y` | `Number` | no | `0` | Zvislý posun. |\n| `w` | `Number` | no | `0` | Šírka vodoznaku. |\n| `h` | `Number` | no | `0` | Výška vodoznaku. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-draw` s `image over X,Y W,H filename`. Názov súboru nesmie obsahovať medzery ani úvodzovky. Pozícia je relatívna voči gravitácii z `align()`. Keď sú `w` a `h` nastavené na `0`, vodoznak si zachová svoju veľkosť.\n\nExample: Logo v pravom dolnom rohu\n```js\nImage.load(filename)\n\t.resize(1200)\n\t.align('bottom right')\n\t.watermark(PATH.public('img/logo.png'), 20, 20)\n\t.save(target);\n```\n\n### image.limit(type, value)\n\nType: `method`\n\nObmedzí zdroje, ktoré môže nástroj používať.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Zdroj. |\n| `value` | `Number|String` | yes |  | Limit, v jednotkách nástroja. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `-limit type value`, napríklad `memory`, `map`, `disk`, `threads`. Keď ju zavoláš, `default_image_consumption` sa na tento obrázok neuplatní.\n\nExample: Dve vlákna\n```js\nimage.limit('threads', 2);\n```\n\n### image.minify()\n\nType: `method`\n\nOdstráni profily a metadáta.\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPridá `+profile \"*\"`, čo odstráni EXIF, ICC a ďalšie profily a zmenší súbor. `save()`, `pipe()` a `stream()` ju zavolajú samy, keď obrázok nemá žiadnu operáciu.\n\nExample: Odstránenie metadát\n```js\nImage.load(filename).minify().save(filename);\n```\n\n### image.output(type)\n\nType: `method`\n\nNastaví výstupný formát.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | yes |  | Napríklad `png`, `webp`, `.jpg`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nZmení `image.outputType` (úvodná bodka sa odstráni). `pipe()` a `stream()` ho používajú ako formát a `res.image()` ho používa pre `Content-Type`. `save()` berie formát z prípony cieľového súboru.\n\nExample: Konverzia streamu do PNG\n```js\nImage.load(stream).output('png').resize(100).pipe(res);\n```\n\n### image.make(fn)\n\nType: `method`\n\nZavolá funkciu s obrázkom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(image)` | yes |  | Pridá operácie. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\n`fn` sa zavolá s obrázkom ako `this` aj ako argumentom. Použi ju na opakované použitie sady operácií.\n\nExample: Opakovane použiteľná predvoľba\n```js\nfunction preview(image) {\n\timage.resize(300).quality(70);\n}\n\nImage.load(filename).make(preview).save(target);\n```\n\n### image.command(key, [value], [priority], [escape])\n\nType: `method`\n\nPridá ľubovoľnú voľbu nástroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Voľba, napríklad `-sharpen`. |\n| `value` | `String|Number` | no |  | Hodnota voľby. |\n| `priority` | `Number|Boolean` | no | `10` | Poradie voľby. |\n| `escape` | `Boolean` | no | `false` | Dať hodnotu do úvodzoviek. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPouži ju pre voľby bez vlastnej metódy, napríklad `-strip`, `-sharpen` alebo `-define`. Voľby sa spúšťajú v poradí podľa priority (pozri príručku). `escape` dá hodnotu do úvodzoviek a odstráni z nej `'`; použi ho pre hodnoty, ktoré pochádzajú od používateľov. Keď je `priority` nastavené na `true`, priorita je `0` a hodnota sa escapuje.\n\nExample: Doostrenie a prekladanie\n```js\nimage.resize(800);\nimage.command('-sharpen', '0x1');\nimage.command('-interlace', 'Plane');\n```\n\n### image.clear()\n\nType: `method`\n\nOdstráni všetky operácie.\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nVyprázdni `image.builder`. `save()` ju zavolá po spustení, takže jeden objekt obrázka môžeš použiť znova.\n\nExample: Začať odznova\n```js\nimage.clear().resize(100);\n```\n\n### image.measure(callback)\n\nType: `method`\n\nPrečíta šírku a výšku zdrojového súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, size)` | yes |  | `size` je `{ width, height }`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nPrečíta začiatok súboru a zmeria ho v JavaScripte. Funguje iba pre obrázok načítaný z názvu súboru s príponou `.jpg`, `.png`, `.gif` alebo `.webp` (malými alebo veľkými písmenami); iné prípony, vrátane `.jpeg`, vedú k chybe. Pre stream alebo buffer použi `Image.measure()` a pre iné formáty `identify()`.\n\nExample: Zmeranie súboru\n```js\nImage.load(PATH.public('img/a.jpg')).measure(function(err, size) {\n\tconsole.log(size.width, size.height);\n});\n```\n\n### image.identify(callback)\n\nType: `method`\n\nPrečíta typ a veľkosť zdrojového súboru pomocou externého nástroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(err, info)` | yes |  | `info` je `{ type, width, height }`, napríklad `{ type: 'JPEG', width: 800, height: 600 }`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nSpustí `gm identify` (alebo `identify` pre `im` a `magick`) a spracuje prvý riadok. Potrebuje obrázok načítaný z názvu súboru.\n\nExample: Identifikácia\n```js\nImage.load(filename).identify(function(err, info) {\n\terr && console.error(err);\n\tinfo && console.log(info.type, info.width, info.height);\n});\n```\n\n### image.save([filename], [callback], [writer])\n\nType: `method`\n\nSpustí operácie a uloží výsledok do súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `the source file` | Cieľový súbor. |\n| `callback` | `Function(err, saved)` | no |  | `saved` je `true` pri úspechu a `false` pri chybe. |\n| `writer` | `Function(stdin)` | no |  | Získa vstupný stream nástroja, aby si zdroj zapísal sám. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\nBez `filename` sa prepíše zdrojový súbor. Formát sa riadi príponou `filename`. Zaregistrovaný `Image.middleware()` pre výstupný typ sa spustí po zapísaní súboru. Po spustení sa operácie vymažú.\n\nExample: Uloženie kópie ako WebP\n```js\nImage.load(PATH.public('img/photo.jpg'))\n\t.resize(1024)\n\t.quality(75)\n\t.save(PATH.public('img/photo.webp'), function(err, saved) {\n\t\tif (err)\n\t\t\tconsole.error(err);\n\t});\n```\n\n### image.pipe(stream, [type], [options])\n\nType: `method`\n\nSpustí operácie a presmeruje výsledok do zapisovateľného streamu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Zapisovateľný stream, napríklad súborový stream alebo `res`. |\n| `type` | `String` | no | `image.outputType` | Výstupný formát. |\n| `options` | `Object` | no |  | Voľby `pipe()`. |\n\nReturns: `Image` Ten istý obrázok, na reťazenie.\n\n`type` je výstupný formát: `jpg`, `jpeg`, `png`, `gif`, `apng`, `heif`, `heic`, `webp` alebo `ico`. Iná hodnota alebo žiadna použije `image.outputType`. `options` sa odovzdajú do `stream.pipe()`. Chyby nástroja sa vysielajú ako udalosti `error` streamu `stream`.\n\nExample: Zápis do súborového streamu\n```js\nvar target = Fs.createWriteStream(PATH.temp('thumb.png'));\nImage.load(buffer).resize(64, 64).pipe(target, 'png');\n```\n\n### image.stream([type], [writer])\n\nType: `method`\n\nSpustí operácie a vráti výsledok ako čitateľný stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no | `image.outputType` | Výstupný formát. |\n| `writer` | `Function(stdin)` | no |  | Zapíše zdrojové dáta. |\n\nReturns: `ReadableStream` Výstup nástroja (cez middleware, ak je zaregistrovaný).\n\n`type` funguje ako v `pipe()`. `writer(stdin)` môže zdroj zapísať do nástroja sám.\n\nExample: Nahratie obrázka so zmenenou veľkosťou\n```js\nvar stream = Image.load(filename).resize(500).stream('jpg');\nstream.pipe(Fs.createWriteStream(PATH.temp('small.jpg')));\n```\n\n### default_image_consumption : 0\n\nType: `config`\n\nObmedzí pamäť GraphicsMagick alebo ImageMagick, v percentách.\n\nReturns: `Number`\n\nKeď nie je `0`, každý obrázok bez vlastného `limit()` dostane `-limit memory` (15 × hodnota) a `-limit map` (30 × hodnota). Predvolene je vypnutý, pretože niektoré verzie GraphicsMagick s týmito limitmi zlyhávajú. Znak `%` v konfiguračnom súbore je povolený.\n\nPredvolené: `0` (vypnuté).\n\nExample: Polovica predvolených limitov\n```text\ndefault_image_consumption : 50\n```\n","entries":[{"type":"class","name":"Image","signature":"new Image.Image(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.load()","signature":"Image.load(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.init()","signature":"Image.init(source, [converter], [width], [height])","since":"","deprecated":false},{"type":"method","name":"Image.measure()","signature":"Image.measure(type, buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureJPG()","signature":"Image.measureJPG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePNG()","signature":"Image.measurePNG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureGIF()","signature":"Image.measureGIF(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureBMP()","signature":"Image.measureBMP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measurePSD()","signature":"Image.measurePSD(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureWEBP()","signature":"Image.measureWEBP(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.measureSVG()","signature":"Image.measureSVG(buffer)","since":"","deprecated":false},{"type":"method","name":"Image.middleware()","signature":"Image.middleware(type, fn)","since":"","deprecated":false},{"type":"method","name":"image.resize()","signature":"image.resize([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.resizeCenter()","signature":"image.resizeCenter(w, h, [color])","since":"","deprecated":false},{"type":"method","name":"image.resizeAlign()","signature":"image.resizeAlign(w, h, [align], [color])","since":"","deprecated":false},{"type":"method","name":"image.miniature()","signature":"image.miniature(w, h, [color], [filter])","since":"","deprecated":false},{"type":"method","name":"image.thumbnail()","signature":"image.thumbnail([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.scale()","signature":"image.scale([w], [h], [options])","since":"","deprecated":false},{"type":"method","name":"image.crop()","signature":"image.crop(w, h, [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.extent()","signature":"image.extent([w], [h], [x], [y])","since":"","deprecated":false},{"type":"method","name":"image.align()","signature":"image.align(type)","since":"","deprecated":false},{"type":"method","name":"image.filter()","signature":"image.filter(type)","since":"","deprecated":false},{"type":"method","name":"image.quality()","signature":"image.quality([percentage])","since":"","deprecated":false},{"type":"method","name":"image.rotate()","signature":"image.rotate(deg)","since":"","deprecated":false},{"type":"method","name":"image.flip()","signature":"image.flip()","since":"","deprecated":false},{"type":"method","name":"image.flop()","signature":"image.flop()","since":"","deprecated":false},{"type":"method","name":"image.blur()","signature":"image.blur(radius)","since":"","deprecated":false},{"type":"method","name":"image.grayscale()","signature":"image.grayscale()","since":"","deprecated":false},{"type":"method","name":"image.sepia()","signature":"image.sepia()","since":"","deprecated":false},{"type":"method","name":"image.normalize()","signature":"image.normalize()","since":"","deprecated":false},{"type":"method","name":"image.colors()","signature":"image.colors(value)","since":"","deprecated":false},{"type":"method","name":"image.bitdepth()","signature":"image.bitdepth(value)","since":"","deprecated":false},{"type":"method","name":"image.background()","signature":"image.background(color)","since":"","deprecated":false},{"type":"method","name":"image.fill()","signature":"image.fill(color)","since":"","deprecated":false},{"type":"method","name":"image.watermark()","signature":"image.watermark(filename, [x], [y], [w], [h])","since":"","deprecated":false},{"type":"method","name":"image.limit()","signature":"image.limit(type, value)","since":"","deprecated":false},{"type":"method","name":"image.minify()","signature":"image.minify()","since":"","deprecated":false},{"type":"method","name":"image.output()","signature":"image.output(type)","since":"","deprecated":false},{"type":"method","name":"image.make()","signature":"image.make(fn)","since":"","deprecated":false},{"type":"method","name":"image.command()","signature":"image.command(key, [value], [priority], [escape])","since":"","deprecated":false},{"type":"method","name":"image.clear()","signature":"image.clear()","since":"","deprecated":false},{"type":"method","name":"image.measure()","signature":"image.measure(callback)","since":"","deprecated":false},{"type":"method","name":"image.identify()","signature":"image.identify(callback)","since":"","deprecated":false},{"type":"method","name":"image.save()","signature":"image.save([filename], [callback], [writer])","since":"","deprecated":false},{"type":"method","name":"image.pipe()","signature":"image.pipe(stream, [type], [options])","since":"","deprecated":false},{"type":"method","name":"image.stream()","signature":"image.stream([type], [writer])","since":"","deprecated":false},{"type":"config","name":"default_image_consumption","signature":"default_image_consumption : 0","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabmHV5ai61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"HTTP server","summary":"Functions for starting the server, CORS, proxies, redirects and error handling.","markdown":"---\ntitle: HTTP server\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# HTTP server\n\n> Functions for starting the server, CORS, proxies, redirects and error handling.\n\nFunctions and settings of the HTTP server that are not routes: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, error pages and error helpers. The guide [HTTP server: CORS, proxy and errors](../../guides/http-server/) explains them with examples; this page is the exact reference. The sitemap has its own page: [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nStarts the HTTP server and loads the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` or `'release'`. |\n| `options` | `Object` | no |  | Start options, see [HTTP options](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)`; the server listens only when you call `listen()`. Same as `options.middleware`. |\n\nReturns: `undefined`\n\nLoads the configuration, the sitemap and all files of the application, then listens. `mode` is `'debug'` or `'release'`. Command-line arguments are read too: a number sets the port when `options.port` is empty, and any other argument that is not a URL and does not start with `--` becomes `unixsocket`. The start script normally calls this function for you.\n\nExample: Start on a port\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Start later\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nStarts the application with an HTTPS server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` or `'release'`. |\n| `options` | `Object` | yes |  | Start options with `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, as in `HTTP()`. |\n\nReturns: `undefined`\n\nWorks as `HTTP()` but creates a Node.js `https` server. `options.https` is passed to `https.createServer()`: a `key` or `cert` string that contains a dot is read as a file, other strings are decoded from base64. Other TLS options of Node.js can be added to the same object.\n\nExample: Certificates from files\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nThe options object of `HTTP()` and `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | The port. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | The IP address. |\n| `unixsocket` | `String` | no |  | A Unix socket path to listen on instead of a port. |\n| `unixsocket777` | `Boolean` | no | `false` | Sets the permissions of the socket file to `0777`. |\n| `config` | `Object` | no |  | Values copied into `CONF` before the configuration is used. |\n| `https` | `Object` | no |  | `{ key, cert }` and other TLS options for `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)` that starts listening. |\n| `id` | `String` | no |  | The identifier of the instance, kept in `F.id`. |\n\nThe same object is passed to the start script `require('total4/release')(options)` or `require('total4/debug')(options)`, which hands it to `HTTP()`. The defaults of port and IP come from the config keys `default_port`, `default_ip` and `default_unixsocket` (see [Configuration](../../guides/configuration/)). `ip: 'auto'` listens on `0.0.0.0`.\n\nExample: In the start script\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nThe Node.js HTTP or HTTPS server of the application.\n\nReturns: `http.Server`\n\nCreated when the server starts. You can use it to read the address or to attach listeners of Node.js.\n\nExample: Listen to connections\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nThe port the server listens on.\n\nReturns: `Number`\n\nSet when the server starts, from `options.port`, the command line, `default_port` or `8000`.\n\nExample: Print the address\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nThe IP address the server listens on.\n\nReturns: `String`\n\nSet when the server starts, from `options.ip`, `default_ip` or `0.0.0.0`.\n\nExample: Read it\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nTunes sockets of the HTTP server for many connections.\n\nReturns: `Boolean`\n\nWith `true`, each incoming socket gets `setNoDelay(true)` and keep-alive, and the global HTTP agent of Node.js can open up to 9999 sockets. Default: `false`.\n\nExample: In the config file\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nAllows cross-origin requests to a path.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | The path, for example `/api/*`, or a list of origins. |\n| `flags` | `Array` | no |  | Origins, methods, max age and `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Sends `Access-Control-Allow-Credentials: true`. `flags` can be `true` for the same effect. |\n\nReturns: `Object` The rule, with `remove()` to delete it.\n\nRegisters a CORS rule. The framework answers preflight `OPTIONS` requests with `200` and adds the `Access-Control-*` headers to the other requests. A `url` that ends with `*` or contains `{` covers all paths below it. In `flags`, origins are `'https://host'`, `'http://host'` or `'//host'`; HTTP methods are `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (default: all); a number is the max age in seconds; `true` or `'credentials'` allows credentials. Without origins, the config key `default_cors` is used, and without it every origin is allowed. A request from another origin gets an empty `404`. Calling `CORS()` again with the same URL extends the existing rule.\n\nWithout arguments, every path and every origin is allowed. A first argument that starts with `http://` or `https://` is a comma-separated list of origins allowed on every path.\n\nExample: API for one origin\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Everything\n```js\nCORS();\n```\n\nExample: Origins for the whole app\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Remove later\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nHow long browsers can cache a CORS preflight answer.\n\nReturns: `Number`\n\nThe value of `Access-Control-Max-Age` in seconds for `CORS()` rules without their own number flag. Default: `120`.\n\nExample: In the config file\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nForwards requests under a path to another server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The path prefix, ending with `/`. |\n| `target` | `String` | yes |  | The target address or Unix socket path. `null` removes the proxy. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` or `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)` called before the request is sent; change `uri.headers` or `uri.path` here. |\n| `after` | `Function` | no |  | `function(response)` called with the response of the target before it is sent to the client. |\n| `check` | `Function` | no |  | `function(req, res)`; return `false` to skip the proxy for this request. |\n| `timeout` | `Number` | no | `10000` | Timeout in milliseconds. |\n\nReturns: `Object` The proxy, with `remove()` to delete it.\n\nEvery request whose path starts with `url` (lower case, ending with `/`) is sent to `target` and the answer is streamed back. The target is an `http://` or `https://` address or a Unix socket path. Proxies are checked before redirects, middleware and routes, and WebSocket connections are forwarded too. The request gets the headers `X-Forwarded-For`, `X-Forwarded-Url` and `X-Forwarded-Host`. When the target fails, the client gets the error page `503`.\n\n`copypath`: not set appends the whole request path to the path of the target; `'replace'` and `'extend'` remove the `url` prefix; `true` removes it only when the target has a path; `false` always uses only the path of the target. When `copypath` is a function, it is `before`, and the next argument is `after`. When `check` is a number, it is `timeout`. `PROXY(url, null)` removes the proxy.\n\nExample: Forward an API\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Add a header\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Unix socket\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nRedirects a host or a URL to another address.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | A full address (`protocol://host`) or a path. |\n| `to` | `String` | yes |  | The new address or path. |\n| `path` | `Boolean` | no | `false` | For hosts: keep the path and query. For paths: make the redirect permanent. |\n| `permanent` | `Boolean` | no | `false` | For hosts: answer `301`. |\n\nReturns: `undefined`\n\nWith a full address in `from` (`http://example.com`), every request to that protocol and host is redirected before routing; `path` keeps the path and query, `permanent` answers `301` instead of `302`.\n\nWith a path in `from`, a `GET` route is created that redirects to `to` and keeps the query string. In this form the third argument makes the redirect permanent, and an array in the third or fourth position is passed as route flags. A path to a static file (`/docs.pdf`) creates a file route instead.\n\nExample: Move to HTTPS and www\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: An old page\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nAnswers a request with a redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The target address. |\n| `permanent` | `Boolean` | no | `false` | Sends `301 Moved Permanently`. |\n\nReturns: `Response` The response.\n\nSends `302`, or `301` when `permanent` is `true`, with the `Location` header. Useful in middleware and file handlers, where there is no controller.\n\nExample: In a middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDeclares the page for an error status.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | The status, for example `#404`. |\n| `action` | `Function` | yes |  | The action that answers. |\n\nReturns: `undefined`\n\nA status route runs when the request ends with that status: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` or `#503`. The controller has the problem or error in `this.exception`; set `this.status` yourself. Without a status route, the framework answers with its built-in HTML error page, or with JSON errors when `default_errorbuilder_errors` is on or the request is XHR (`default_errorbuilder_forxhr`). A timeout answers `503`, a body over the size limit `431`.\n\nExample: Custom 404 and 500\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nAnswers XHR requests with JSON errors instead of the HTML error page.\n\nReturns: `Boolean`\n\nWhen a request with `X-Requested-With: XMLHttpRequest` ends with an error status and there is no status route, the answer is an `ErrorBuilder` JSON array. Default: `true`.\n\nExample: In the config file\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nAnswers with the error status 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |\n\nReturns: `Response` The response.\n\nRuns the status route `#400` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error400`. Use it in middleware and file handlers; in actions use `controller.throw400()`.\n\nExample: In a middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nAnswers with the error status 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |\n\nReturns: `Response` The response.\n\nRuns the status route `#401` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error401`. Use it in middleware and file handlers; in actions use `controller.throw401()`.\n\nExample: In a middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nAnswers with the error status 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |\n\nReturns: `Response` The response.\n\nRuns the status route `#403` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error403`. Use it in middleware and file handlers; in actions use `controller.throw403()`.\n\nExample: In a middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nAnswers with the error status 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | A description passed to `this.exception` of the status route. |\n\nReturns: `Response` The response.\n\nRuns the status route `#404` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error404`. Use it in middleware and file handlers; in actions use `controller.throw404()`.\n\nExample: In a middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nAnswers with the error status 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | The error; it is logged with `F.error()`. |\n\nReturns: `Response` The response.\n\nRuns the status route `#500` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error500`. Use it in middleware and file handlers; in actions use `controller.throw500()`.\n\nExample: On an error\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nAnswers with the error status 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | The error; it is logged with `F.error()`. |\n\nReturns: `Response` The response.\n\nRuns the status route `#503` or the built-in error page. For a `HEAD` request only the status is sent. It also emits the event `error503`. Use it in middleware and file handlers; in actions use `controller.throw503()`.\n\nExample: On an error\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nLogs an error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | The error. Nothing happens when it is empty. |\n| `name` | `String` | no |  | Where it happened, printed with the error. |\n| `uri` | `String|Object` | no |  | The URL of the request. |\n\nReturns: `undefined`\n\nCalls `DEF.onError`. The default handler prints the error to the console, keeps it in `F.errors` and emits the event `error`. Without arguments it returns a callback `function(err)` that logs errors.\n\nExample: Log an error\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nReturns a callback that logs its error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | A label printed with the error. |\n\nReturns: `Function` `function(err)`.\n\nThe callback `function(err)` calls `F.error(err, name)` when `err` is not empty. Use it where you need a callback but do not care about the result.\n\nExample: Ignore the result, log the error\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nThe function that handles every error logged by the framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | The error. |\n| `name` | `String` | yes |  | The place where it happened. |\n| `uri` | `Object|String` | yes |  | The URL of the request, when there is one. |\n\n`F.error()`, errors in actions and `throw500()` all end here. The default prints `ERROR ======= date: name ---> error (url)` and the stack, keeps the last five errors in `F.errors` and emits `ON('error')`. Replace it to send errors elsewhere; you can call the original one from yours.\n\nExample: Send errors to a service\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nThe last five logged errors.\n\nReturns: `Array`\n\nEach item is `{ error, name, url, date }`. Filled by the default `DEF.onError`.\n\nExample: Show them\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nReturns the `{ success, value, error }` answer object.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | The result, an error, or a callback to wrap. |\n| `value` | `Object` | no |  | A value for the `value` property. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` gives `{ success: true }`. `SUCCESS(true, value)` adds `value` (a schema instance is cleaned first). An `Error` or an `ErrorBuilder` with errors gives `success: false` and the text of the error in `error`. With a function, it returns a callback `(err, value)` that calls your function with `SUCCESS(err, value)` as the second argument. The function returns one shared object, so read or send it at once and do not keep it.\n\nExample: In an action\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: With a value\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nCalls a function when a request, a response or a stream ends.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | What to watch. |\n| `callback` | `Function` | yes |  | Called once at the end. |\n\nReturns: `undefined`\n\nFor a request or a response, the callback runs when its socket closes or fails, also when the client goes away. For other streams it runs when they end. Several callbacks can wait on one stream.\n\nExample: Clean up after a response\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nDestroys a stream and closes its file descriptor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | The stream. |\n\nReturns: `Stream` The same stream.\n\nA file read stream is destroyed and closed even if it is still opening. Other Node.js streams are destroyed with `destroy()`.\n\nExample: Stop reading\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nA controller without a request.\n\nReturns: `Controller`\n\nThe framework uses it for `VIEW()` and `MAIL()`, where there is no HTTP request. Its `req` has an empty URL, query, body and files. You can use it to call controller helpers outside a request; do not answer with it.\n\nExample: A sitemap URL outside a request\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmHV5ai61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"HTTP-Server","summary":"Funktionen zum Starten des Servers, für CORS, Proxies, Weiterleitungen und die Fehlerbehandlung.","markdown":"---\ntitle: HTTP-Server\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# HTTP-Server\n\n> Funktionen zum Starten des Servers, für CORS, Proxies, Weiterleitungen und die Fehlerbehandlung.\n\nFunktionen und Einstellungen des HTTP-Servers, die keine Routen sind: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, Fehlerseiten und Fehler-Hilfsfunktionen. Der Leitfaden [HTTP-Server: CORS, Proxy und Fehler](../../guides/http-server/) erklärt sie mit Beispielen; diese Seite ist die genaue Referenz. Die Sitemap hat eine eigene Seite: [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nStartet den HTTP-Server und lädt die Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` oder `'release'`. |\n| `options` | `Object` | no |  | Startoptionen, siehe [HTTP-Optionen](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)`; der Server lauscht erst, wenn du `listen()` aufrufst. Dasselbe wie `options.middleware`. |\n\nReturns: `undefined`\n\nLädt die Konfiguration, die Sitemap und alle Dateien der Anwendung und lauscht dann. `mode` ist `'debug'` oder `'release'`. Kommandozeilenargumente werden ebenfalls gelesen: Eine Zahl setzt den Port, wenn `options.port` leer ist, und jedes andere Argument, das keine URL ist und nicht mit `--` beginnt, wird zu `unixsocket`. Normalerweise ruft das Startskript diese Funktion für dich auf.\n\nExample: Auf einem Port starten\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Später starten\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nStartet die Anwendung mit einem HTTPS-Server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` oder `'release'`. |\n| `options` | `Object` | yes |  | Startoptionen mit `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, wie bei `HTTP()`. |\n\nReturns: `undefined`\n\nFunktioniert wie `HTTP()`, erzeugt aber einen Node.js-`https`-Server. `options.https` wird an `https.createServer()` übergeben: Ein `key`- oder `cert`-String mit einem Punkt wird als Datei gelesen, andere Strings werden aus Base64 dekodiert. Weitere TLS-Optionen von Node.js können demselben Objekt hinzugefügt werden.\n\nExample: Zertifikate aus Dateien\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nDas Optionsobjekt von `HTTP()` und `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | Der Port. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | Die IP-Adresse. |\n| `unixsocket` | `String` | no |  | Ein Unix-Socket-Pfad, auf dem statt eines Ports gelauscht wird. |\n| `unixsocket777` | `Boolean` | no | `false` | Setzt die Berechtigungen der Socket-Datei auf `0777`. |\n| `config` | `Object` | no |  | Werte, die in `CONF` kopiert werden, bevor die Konfiguration verwendet wird. |\n| `https` | `Object` | no |  | `{ key, cert }` und weitere TLS-Optionen für `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)`, die das Lauschen startet. |\n| `id` | `String` | no |  | Die Kennung der Instanz, gespeichert in `F.id`. |\n\nDasselbe Objekt wird an das Startskript `require('total4/release')(options)` oder `require('total4/debug')(options)` übergeben, das es an `HTTP()` weiterreicht. Die Standardwerte für Port und IP kommen aus den Konfigurationsschlüsseln `default_port`, `default_ip` und `default_unixsocket` (siehe [Konfiguration](../../guides/configuration/)). `ip: 'auto'` lauscht auf `0.0.0.0`.\n\nExample: Im Startskript\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nDer Node.js-HTTP- oder -HTTPS-Server der Anwendung.\n\nReturns: `http.Server`\n\nWird beim Start des Servers erzeugt. Du kannst ihn verwenden, um die Adresse zu lesen oder Node.js-Listener anzuhängen.\n\nExample: Auf Verbindungen hören\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nDer Port, auf dem der Server lauscht.\n\nReturns: `Number`\n\nWird beim Start des Servers gesetzt, aus `options.port`, der Kommandozeile, `default_port` oder `8000`.\n\nExample: Die Adresse ausgeben\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nDie IP-Adresse, auf der der Server lauscht.\n\nReturns: `String`\n\nWird beim Start des Servers gesetzt, aus `options.ip`, `default_ip` oder `0.0.0.0`.\n\nExample: Auslesen\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nOptimiert die Sockets des HTTP-Servers für viele Verbindungen.\n\nReturns: `Boolean`\n\nMit `true` bekommt jeder eingehende Socket `setNoDelay(true)` und Keep-Alive, und der globale HTTP-Agent von Node.js kann bis zu 9999 Sockets öffnen. Standard: `false`.\n\nExample: In der Konfigurationsdatei\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nErlaubt Cross-Origin-Requests auf einen Pfad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Der Pfad, zum Beispiel `/api/*`, oder eine Liste von Origins. |\n| `flags` | `Array` | no |  | Origins, Methoden, Max-Age und `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Sendet `Access-Control-Allow-Credentials: true`. `flags` kann für denselben Effekt `true` sein. |\n\nReturns: `Object` Die Regel, mit `remove()` zum Löschen.\n\nRegistriert eine CORS-Regel. Das Framework beantwortet Preflight-Requests `OPTIONS` mit `200` und fügt den anderen Requests die Header `Access-Control-*` hinzu. Eine `url`, die mit `*` endet oder `{` enthält, deckt alle Pfade darunter ab. In `flags` sind Origins `'https://host'`, `'http://host'` oder `'//host'`; HTTP-Methoden sind `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (Standard: alle); eine Zahl ist das Max-Age in Sekunden; `true` oder `'credentials'` erlaubt Credentials. Ohne Origins wird der Konfigurationsschlüssel `default_cors` verwendet, und ohne diesen ist jeder Origin erlaubt. Ein Request von einem anderen Origin bekommt eine leere `404`. Ein erneuter Aufruf von `CORS()` mit derselben URL erweitert die bestehende Regel.\n\nOhne Argumente sind jeder Pfad und jeder Origin erlaubt. Ein erstes Argument, das mit `http://` oder `https://` beginnt, ist eine kommagetrennte Liste von Origins, die auf jedem Pfad erlaubt sind.\n\nExample: API für einen Origin\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Alles\n```js\nCORS();\n```\n\nExample: Origins für die ganze App\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Später entfernen\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nWie lange Browser eine CORS-Preflight-Antwort zwischenspeichern dürfen.\n\nReturns: `Number`\n\nDer Wert von `Access-Control-Max-Age` in Sekunden für `CORS()`-Regeln ohne eigenes Zahlen-Flag. Standard: `120`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nLeitet Requests unter einem Pfad an einen anderen Server weiter.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Das Pfadpräfix, endet mit `/`. |\n| `target` | `String` | yes |  | Die Zieladresse oder der Unix-Socket-Pfad. `null` entfernt den Proxy. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` oder `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)`, wird vor dem Senden des Requests aufgerufen; ändere hier `uri.headers` oder `uri.path`. |\n| `after` | `Function` | no |  | `function(response)`, wird mit der Response des Ziels aufgerufen, bevor sie an den Client geht. |\n| `check` | `Function` | no |  | `function(req, res)`; gib `false` zurück, um den Proxy für diesen Request zu überspringen. |\n| `timeout` | `Number` | no | `10000` | Timeout in Millisekunden. |\n\nReturns: `Object` Der Proxy, mit `remove()` zum Löschen.\n\nJeder Request, dessen Pfad mit `url` beginnt (kleingeschrieben, endet mit `/`), wird an `target` gesendet, und die Antwort wird zurückgestreamt. Das Ziel ist eine `http://`- oder `https://`-Adresse oder ein Unix-Socket-Pfad. Proxies werden vor Weiterleitungen, Middleware und Routen geprüft, und auch WebSocket-Verbindungen werden weitergeleitet. Der Request bekommt die Header `X-Forwarded-For`, `X-Forwarded-Url` und `X-Forwarded-Host`. Wenn das Ziel fehlschlägt, bekommt der Client die Fehlerseite `503`.\n\n`copypath`: nicht gesetzt hängt den ganzen Request-Pfad an den Pfad des Ziels an; `'replace'` und `'extend'` entfernen das Präfix `url`; `true` entfernt es nur, wenn das Ziel einen Pfad hat; `false` verwendet immer nur den Pfad des Ziels. Ist `copypath` eine Funktion, ist es `before`, und das nächste Argument ist `after`. Ist `check` eine Zahl, ist es `timeout`. `PROXY(url, null)` entfernt den Proxy.\n\nExample: Eine API weiterleiten\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Einen Header hinzufügen\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Unix-Socket\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nLeitet einen Host oder eine URL auf eine andere Adresse um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Eine vollständige Adresse (`protocol://host`) oder ein Pfad. |\n| `to` | `String` | yes |  | Die neue Adresse oder der neue Pfad. |\n| `path` | `Boolean` | no | `false` | Bei Hosts: Pfad und Query behalten. Bei Pfaden: die Weiterleitung permanent machen. |\n| `permanent` | `Boolean` | no | `false` | Bei Hosts: mit `301` antworten. |\n\nReturns: `undefined`\n\nMit einer vollständigen Adresse in `from` (`http://example.com`) wird jeder Request an dieses Protokoll und diesen Host noch vor dem Routing umgeleitet; `path` behält Pfad und Query, `permanent` antwortet mit `301` statt `302`.\n\nMit einem Pfad in `from` wird eine `GET`-Route erzeugt, die auf `to` umleitet und den Query-String behält. In dieser Form macht das dritte Argument die Weiterleitung permanent, und ein Array an dritter oder vierter Stelle wird als Routen-Flags übergeben. Ein Pfad zu einer statischen Datei (`/docs.pdf`) erzeugt stattdessen eine Datei-Route.\n\nExample: Auf HTTPS und www umziehen\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: Eine alte Seite\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nBeantwortet einen Request mit einer Weiterleitung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Zieladresse. |\n| `permanent` | `Boolean` | no | `false` | Sendet `301 Moved Permanently`. |\n\nReturns: `Response` Die Antwort.\n\nSendet `302`, oder `301`, wenn `permanent` gleich `true` ist, mit dem Header `Location`. Nützlich in Middleware und Datei-Handlern, wo es keinen Controller gibt.\n\nExample: In einer Middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDeklariert die Seite für einen Fehlerstatus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Der Status, zum Beispiel `#404`. |\n| `action` | `Function` | yes |  | Die Action, die antwortet. |\n\nReturns: `undefined`\n\nEine Status-Route läuft, wenn der Request mit diesem Status endet: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` oder `#503`. Der Controller hat das Problem oder den Fehler in `this.exception`; setze `this.status` selbst. Ohne Status-Route antwortet das Framework mit seiner eingebauten HTML-Fehlerseite oder mit JSON-Fehlern, wenn `default_errorbuilder_errors` aktiv ist oder der Request ein XHR ist (`default_errorbuilder_forxhr`). Ein Timeout antwortet mit `503`, ein Body über dem Größenlimit mit `431`.\n\nExample: Eigene 404 und 500\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nBeantwortet XHR-Requests mit JSON-Fehlern statt mit der HTML-Fehlerseite.\n\nReturns: `Boolean`\n\nWenn ein Request mit `X-Requested-With: XMLHttpRequest` mit einem Fehlerstatus endet und es keine Status-Route gibt, ist die Antwort ein `ErrorBuilder`-JSON-Array. Standard: `true`.\n\nExample: In der Konfigurationsdatei\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung, die an `this.exception` der Status-Route übergeben wird. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#400` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error400` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw400()`.\n\nExample: In einer Middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung, die an `this.exception` der Status-Route übergeben wird. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#401` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error401` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw401()`.\n\nExample: In einer Middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung, die an `this.exception` der Status-Route übergeben wird. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#403` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error403` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw403()`.\n\nExample: In einer Middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Eine Beschreibung, die an `this.exception` der Status-Route übergeben wird. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#404` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error404` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw404()`.\n\nExample: In einer Middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Der Fehler; er wird mit `F.error()` protokolliert. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#500` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error500` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw500()`.\n\nExample: Bei einem Fehler\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nAntwortet mit dem Fehlerstatus 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Der Fehler; er wird mit `F.error()` protokolliert. |\n\nReturns: `Response` Die Antwort.\n\nFührt die Status-Route `#503` oder die eingebaute Fehlerseite aus. Bei einem `HEAD`-Request wird nur der Status gesendet. Es löst außerdem das Event `error503` aus. Verwende es in Middleware und Datei-Handlern; in Actions verwendest du `controller.throw503()`.\n\nExample: Bei einem Fehler\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nProtokolliert einen Fehler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Der Fehler. Ist er leer, passiert nichts. |\n| `name` | `String` | no |  | Wo er aufgetreten ist, wird mit dem Fehler ausgegeben. |\n| `uri` | `String|Object` | no |  | Die URL des Requests. |\n\nReturns: `undefined`\n\nRuft `DEF.onError` auf. Der Standard-Handler gibt den Fehler in der Konsole aus, speichert ihn in `F.errors` und löst das Event `error` aus. Ohne Argumente gibt es einen Callback `function(err)` zurück, der Fehler protokolliert.\n\nExample: Einen Fehler protokollieren\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nGibt einen Callback zurück, der seinen Fehler protokolliert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Eine Bezeichnung, die mit dem Fehler ausgegeben wird. |\n\nReturns: `Function` `function(err)`.\n\nDer Callback `function(err)` ruft `F.error(err, name)` auf, wenn `err` nicht leer ist. Verwende ihn dort, wo du einen Callback brauchst, dich das Ergebnis aber nicht interessiert.\n\nExample: Ergebnis ignorieren, Fehler protokollieren\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nDie Funktion, die jeden vom Framework protokollierten Fehler behandelt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Der Fehler. |\n| `name` | `String` | yes |  | Der Ort, an dem er aufgetreten ist. |\n| `uri` | `Object|String` | yes |  | Die URL des Requests, falls es einen gibt. |\n\n`F.error()`, Fehler in Actions und `throw500()` landen alle hier. Der Standard gibt `ERROR ======= date: name ---> error (url)` und den Stack aus, behält die letzten fünf Fehler in `F.errors` und löst `ON('error')` aus. Ersetze sie, um Fehler woanders hinzuschicken; du kannst die ursprüngliche Funktion aus deiner aufrufen.\n\nExample: Fehler an einen Dienst senden\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nDie letzten fünf protokollierten Fehler.\n\nReturns: `Array`\n\nJeder Eintrag ist `{ error, name, url, date }`. Wird vom Standard-`DEF.onError` gefüllt.\n\nExample: Anzeigen\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nGibt das Antwortobjekt `{ success, value, error }` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | Das Ergebnis, ein Fehler oder ein Callback, der umhüllt wird. |\n| `value` | `Object` | no |  | Ein Wert für die Eigenschaft `value`. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` ergibt `{ success: true }`. `SUCCESS(true, value)` fügt `value` hinzu (eine Schema-Instanz wird vorher bereinigt). Ein `Error` oder ein `ErrorBuilder` mit Fehlern ergibt `success: false` und den Fehlertext in `error`. Mit einer Funktion gibt es einen Callback `(err, value)` zurück, der deine Funktion mit `SUCCESS(err, value)` als zweitem Argument aufruft. Die Funktion gibt ein einziges gemeinsames Objekt zurück, also lies oder sende es sofort und behalte es nicht.\n\nExample: In einer Action\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: Mit einem Wert\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nRuft eine Funktion auf, wenn ein Request, eine Response oder ein Stream endet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | Was überwacht werden soll. |\n| `callback` | `Function` | yes |  | Wird am Ende einmal aufgerufen. |\n\nReturns: `undefined`\n\nBei einem Request oder einer Response läuft der Callback, wenn sein Socket geschlossen wird oder fehlschlägt, auch wenn der Client weggeht. Bei anderen Streams läuft er, wenn sie enden. Mehrere Callbacks können auf einen Stream warten.\n\nExample: Nach einer Response aufräumen\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nZerstört einen Stream und schließt seinen Dateideskriptor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Der Stream. |\n\nReturns: `Stream` Derselbe Stream.\n\nEin Datei-Lesestream wird zerstört und geschlossen, auch wenn er sich noch öffnet. Andere Node.js-Streams werden mit `destroy()` zerstört.\n\nExample: Das Lesen beenden\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nEin Controller ohne Request.\n\nReturns: `Controller`\n\nDas Framework verwendet ihn für `VIEW()` und `MAIL()`, wo es keinen HTTP-Request gibt. Sein `req` hat eine leere URL, Query, Body und Dateien. Du kannst ihn verwenden, um Controller-Hilfsfunktionen außerhalb eines Requests aufzurufen; antworte nicht damit.\n\nExample: Eine Sitemap-URL außerhalb eines Requests\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmHV5ai61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Servidor HTTP","summary":"Funciones para iniciar el servidor, CORS, proxies, redirecciones y la gestión de errores.","markdown":"---\ntitle: Servidor HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Servidor HTTP\n\n> Funciones para iniciar el servidor, CORS, proxies, redirecciones y la gestión de errores.\n\nFunciones y ajustes del servidor HTTP que no son rutas: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, las páginas de error y los helpers de errores. La guía [Servidor HTTP: CORS, proxy y errores](../../guides/http-server/) los explica con ejemplos; esta página es la referencia exacta. El sitemap tiene su propia página: [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nInicia el servidor HTTP y carga la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no |  | Opciones de inicio; consulta [opciones de HTTP](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)`; el servidor solo escucha cuando llamas a `listen()`. Igual que `options.middleware`. |\n\nReturns: `undefined`\n\nCarga la configuración, el sitemap y todos los archivos de la aplicación, y después escucha. `mode` es `'debug'` o `'release'`. También se leen los argumentos de línea de comandos: un número define el puerto cuando `options.port` está vacío, y cualquier otro argumento que no sea una URL y no empiece por `--` se convierte en `unixsocket`. Normalmente el script de inicio llama a esta función por ti.\n\nExample: Iniciar en un puerto\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Iniciar más tarde\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nInicia la aplicación con un servidor HTTPS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | yes |  | Opciones de inicio con `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, como en `HTTP()`. |\n\nReturns: `undefined`\n\nFunciona como `HTTP()`, pero crea un servidor `https` de Node.js. `options.https` se pasa a `https.createServer()`: una cadena `key` o `cert` que contiene un punto se lee como archivo; las demás cadenas se decodifican desde base64. Se pueden añadir otras opciones TLS de Node.js al mismo objeto.\n\nExample: Certificados desde archivos\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nEl objeto de opciones de `HTTP()` y `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | El puerto. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | La dirección IP. |\n| `unixsocket` | `String` | no |  | Una ruta de socket Unix en la que escuchar en lugar de un puerto. |\n| `unixsocket777` | `Boolean` | no | `false` | Establece los permisos del archivo del socket a `0777`. |\n| `config` | `Object` | no |  | Valores copiados en `CONF` antes de que se use la configuración. |\n| `https` | `Object` | no |  | `{ key, cert }` y otras opciones TLS para `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)` que empieza a escuchar. |\n| `id` | `String` | no |  | El identificador de la instancia, guardado en `F.id`. |\n\nEl mismo objeto se pasa al script de inicio `require('total4/release')(options)` o `require('total4/debug')(options)`, que se lo entrega a `HTTP()`. Los valores por defecto del puerto y de la IP vienen de las claves de configuración `default_port`, `default_ip` y `default_unixsocket` (consulta [Configuración](../../guides/configuration/)). `ip: 'auto'` escucha en `0.0.0.0`.\n\nExample: En el script de inicio\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nEl servidor HTTP o HTTPS de Node.js de la aplicación.\n\nReturns: `http.Server`\n\nSe crea cuando se inicia el servidor. Puedes usarlo para leer la dirección o para añadir listeners de Node.js.\n\nExample: Escuchar las conexiones\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nEl puerto en el que escucha el servidor.\n\nReturns: `Number`\n\nSe define cuando se inicia el servidor, a partir de `options.port`, la línea de comandos, `default_port` o `8000`.\n\nExample: Imprimir la dirección\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nLa dirección IP en la que escucha el servidor.\n\nReturns: `String`\n\nSe define cuando se inicia el servidor, a partir de `options.ip`, `default_ip` o `0.0.0.0`.\n\nExample: Leerla\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nAjusta los sockets del servidor HTTP para muchas conexiones.\n\nReturns: `Boolean`\n\nCon `true`, cada socket entrante recibe `setNoDelay(true)` y keep-alive, y el agente HTTP global de Node.js puede abrir hasta 9999 sockets. Por defecto: `false`.\n\nExample: En el archivo de configuración\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nPermite peticiones de otros orígenes a una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | La ruta, por ejemplo `/api/*`, o una lista de orígenes. |\n| `flags` | `Array` | no |  | Orígenes, métodos, duración máxima y `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Envía `Access-Control-Allow-Credentials: true`. `flags` puede ser `true` con el mismo efecto. |\n\nReturns: `Object` La regla, con `remove()` para eliminarla.\n\nRegistra una regla CORS. El framework responde a las peticiones preflight `OPTIONS` con `200` y añade las cabeceras `Access-Control-*` a las demás peticiones. Una `url` que termina en `*` o contiene `{` cubre todas las rutas por debajo. En `flags`, los orígenes son `'https://host'`, `'http://host'` o `'//host'`; los métodos HTTP son `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (por defecto: todos); un número es la duración máxima en segundos; `true` o `'credentials'` permite credenciales. Sin orígenes, se usa la clave de configuración `default_cors`, y sin ella se permite cualquier origen. Una petición de otro origen recibe un `404` vacío. Volver a llamar a `CORS()` con la misma URL amplía la regla existente.\n\nSin argumentos, se permiten todas las rutas y todos los orígenes. Un primer argumento que empieza por `http://` o `https://` es una lista de orígenes separados por comas permitidos en todas las rutas.\n\nExample: API para un origen\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Todo\n```js\nCORS();\n```\n\nExample: Orígenes para toda la app\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Eliminar más tarde\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nCuánto tiempo pueden guardar en caché los navegadores una respuesta preflight de CORS.\n\nReturns: `Number`\n\nEl valor de `Access-Control-Max-Age` en segundos para las reglas `CORS()` sin su propio flag numérico. Por defecto: `120`.\n\nExample: En el archivo de configuración\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nReenvía a otro servidor las peticiones bajo una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | El prefijo de la ruta, terminado en `/`. |\n| `target` | `String` | yes |  | La dirección de destino o la ruta del socket Unix. `null` elimina el proxy. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` o `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)` que se llama antes de enviar la petición; cambia aquí `uri.headers` o `uri.path`. |\n| `after` | `Function` | no |  | `function(response)` que se llama con la respuesta del destino antes de enviarla al cliente. |\n| `check` | `Function` | no |  | `function(req, res)`; devuelve `false` para omitir el proxy en esta petición. |\n| `timeout` | `Number` | no | `10000` | Tiempo de espera en milisegundos. |\n\nReturns: `Object` El proxy, con `remove()` para eliminarlo.\n\nCada petición cuya ruta empieza por `url` (en minúsculas, terminada en `/`) se envía a `target` y la respuesta se devuelve en streaming. El destino es una dirección `http://` o `https://` o una ruta de socket Unix. Los proxies se comprueban antes que las redirecciones, el middleware y las rutas, y también se reenvían las conexiones WebSocket. La petición recibe las cabeceras `X-Forwarded-For`, `X-Forwarded-Url` y `X-Forwarded-Host`. Cuando el destino falla, el cliente recibe la página de error `503`.\n\n`copypath`: sin definir, añade toda la ruta de la petición a la ruta del destino; `'replace'` y `'extend'` quitan el prefijo `url`; `true` lo quita solo cuando el destino tiene ruta; `false` usa siempre solo la ruta del destino. Cuando `copypath` es una función, es `before`, y el argumento siguiente es `after`. Cuando `check` es un número, es `timeout`. `PROXY(url, null)` elimina el proxy.\n\nExample: Reenviar una API\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Añadir una cabecera\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Socket Unix\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nRedirige un host o una URL a otra dirección.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Una dirección completa (`protocol://host`) o una ruta. |\n| `to` | `String` | yes |  | La nueva dirección o ruta. |\n| `path` | `Boolean` | no | `false` | Para hosts: conserva la ruta y la query. Para rutas: hace que la redirección sea permanente. |\n| `permanent` | `Boolean` | no | `false` | Para hosts: responde `301`. |\n\nReturns: `undefined`\n\nCon una dirección completa en `from` (`http://example.com`), cada petición a ese protocolo y host se redirige antes del enrutamiento; `path` conserva la ruta y la query, `permanent` responde `301` en lugar de `302`.\n\nCon una ruta en `from`, se crea una ruta `GET` que redirige a `to` y conserva el query string. En esta forma el tercer argumento hace que la redirección sea permanente, y un array en la tercera o cuarta posición se pasa como flags de la ruta. Una ruta a un archivo estático (`/docs.pdf`) crea en su lugar una ruta de archivo.\n\nExample: Pasar a HTTPS y www\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: Una página antigua\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nResponde a una petición con una redirección.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La dirección de destino. |\n| `permanent` | `Boolean` | no | `false` | Envía `301 Moved Permanently`. |\n\nReturns: `Response` La respuesta.\n\nEnvía `302`, o `301` cuando `permanent` es `true`, con la cabecera `Location`. Útil en el middleware y en los manejadores de archivos, donde no hay controlador.\n\nExample: En un middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDeclara la página de un estado de error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | El estado, por ejemplo `#404`. |\n| `action` | `Function` | yes |  | La acción que responde. |\n\nReturns: `undefined`\n\nUna ruta de estado se ejecuta cuando la petición termina con ese estado: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` o `#503`. El controlador tiene el problema o el error en `this.exception`; define tú mismo `this.status`. Sin una ruta de estado, el framework responde con su página de error HTML integrada, o con errores JSON cuando `default_errorbuilder_errors` está activado o la petición es XHR (`default_errorbuilder_forxhr`). Un tiempo de espera agotado responde `503`, un cuerpo que supera el límite de tamaño `431`.\n\nExample: 404 y 500 personalizados\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nResponde a las peticiones XHR con errores JSON en lugar de la página de error HTML.\n\nReturns: `Boolean`\n\nCuando una petición con `X-Requested-With: XMLHttpRequest` termina con un estado de error y no hay ruta de estado, la respuesta es un array JSON de `ErrorBuilder`. Por defecto: `true`.\n\nExample: En el archivo de configuración\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nResponde con el estado de error 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción que se pasa a `this.exception` de la ruta de estado. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#400` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error400`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw400()`.\n\nExample: En un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nResponde con el estado de error 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción que se pasa a `this.exception` de la ruta de estado. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#401` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error401`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw401()`.\n\nExample: En un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nResponde con el estado de error 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción que se pasa a `this.exception` de la ruta de estado. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#403` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error403`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw403()`.\n\nExample: En un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nResponde con el estado de error 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descripción que se pasa a `this.exception` de la ruta de estado. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#404` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error404`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw404()`.\n\nExample: En un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nResponde con el estado de error 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | El error; se registra con `F.error()`. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#500` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error500`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw500()`.\n\nExample: Ante un error\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nResponde con el estado de error 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | El error; se registra con `F.error()`. |\n\nReturns: `Response` La respuesta.\n\nEjecuta la ruta de estado `#503` o la página de error integrada. En una petición `HEAD` solo se envía el estado. También emite el evento `error503`. Úsalo en el middleware y en los manejadores de archivos; en las acciones usa `controller.throw503()`.\n\nExample: Ante un error\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nRegistra un error en el log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | El error. Si está vacío, no pasa nada. |\n| `name` | `String` | no |  | Dónde ocurrió; se imprime con el error. |\n| `uri` | `String|Object` | no |  | La URL de la petición. |\n\nReturns: `undefined`\n\nLlama a `DEF.onError`. El manejador por defecto imprime el error en la consola, lo guarda en `F.errors` y emite el evento `error`. Sin argumentos devuelve un callback `function(err)` que registra los errores.\n\nExample: Registrar un error\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nDevuelve un callback que registra su error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Una etiqueta que se imprime con el error. |\n\nReturns: `Function` `function(err)`.\n\nEl callback `function(err)` llama a `F.error(err, name)` cuando `err` no está vacío. Úsalo donde necesitas un callback pero no te importa el resultado.\n\nExample: Ignorar el resultado, registrar el error\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nLa función que gestiona cada error registrado por el framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | El error. |\n| `name` | `String` | yes |  | El lugar donde ocurrió. |\n| `uri` | `Object|String` | yes |  | La URL de la petición, cuando la hay. |\n\n`F.error()`, los errores en las acciones y `throw500()` terminan todos aquí. La función por defecto imprime `ERROR ======= date: name ---> error (url)` y la pila, guarda los cinco últimos errores en `F.errors` y emite `ON('error')`. Sustitúyela para enviar los errores a otro sitio; puedes llamar a la original desde la tuya.\n\nExample: Enviar los errores a un servicio\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nLos cinco últimos errores registrados.\n\nReturns: `Array`\n\nCada elemento es `{ error, name, url, date }`. Lo rellena el `DEF.onError` por defecto.\n\nExample: Mostrarlos\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nDevuelve el objeto de respuesta `{ success, value, error }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | El resultado, un error o un callback que envolver. |\n| `value` | `Object` | no |  | Un valor para la propiedad `value`. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` da `{ success: true }`. `SUCCESS(true, value)` añade `value` (una instancia de esquema se limpia antes). Un `Error` o un `ErrorBuilder` con errores da `success: false` y el texto del error en `error`. Con una función, devuelve un callback `(err, value)` que llama a tu función con `SUCCESS(err, value)` como segundo argumento. La función devuelve un único objeto compartido, así que léelo o envíalo en el momento y no lo guardes.\n\nExample: En una acción\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: Con un valor\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nLlama a una función cuando termina una petición, una respuesta o un stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | Qué vigilar. |\n| `callback` | `Function` | yes |  | Se llama una vez al final. |\n\nReturns: `undefined`\n\nPara una petición o una respuesta, el callback se ejecuta cuando su socket se cierra o falla, también cuando el cliente se va. Para otros streams se ejecuta cuando terminan. Varios callbacks pueden esperar a un mismo stream.\n\nExample: Limpiar después de una respuesta\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nDestruye un stream y cierra su descriptor de archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | El stream. |\n\nReturns: `Stream` El mismo stream.\n\nUn stream de lectura de archivo se destruye y se cierra aunque aún se esté abriendo. Los demás streams de Node.js se destruyen con `destroy()`.\n\nExample: Dejar de leer\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nUn controlador sin petición.\n\nReturns: `Controller`\n\nEl framework lo usa para `VIEW()` y `MAIL()`, donde no hay petición HTTP. Su `req` tiene URL, query, cuerpo y archivos vacíos. Puedes usarlo para llamar a helpers del controlador fuera de una petición; no respondas con él.\n\nExample: Una URL del sitemap fuera de una petición\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmHV5ai61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Serveur HTTP","summary":"Fonctions pour démarrer le serveur, CORS, les proxies, les redirections et la gestion des erreurs.","markdown":"---\ntitle: Serveur HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Serveur HTTP\n\n> Fonctions pour démarrer le serveur, CORS, les proxies, les redirections et la gestion des erreurs.\n\nFonctions et paramètres du serveur HTTP qui ne sont pas des routes : `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, les pages d'erreur et les utilitaires d'erreur. Le guide [Serveur HTTP : CORS, proxy et erreurs](../../guides/http-server/) les explique avec des exemples ; cette page en est la référence exacte. Le sitemap a sa propre page : [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nDémarre le serveur HTTP et charge l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` ou `'release'`. |\n| `options` | `Object` | no |  | Options de démarrage, voir [Options HTTP](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)` ; le serveur n'écoute que lorsque tu appelles `listen()`. Identique à `options.middleware`. |\n\nReturns: `undefined`\n\nCharge la configuration, le sitemap et tous les fichiers de l'application, puis commence l'écoute. `mode` vaut `'debug'` ou `'release'`. Les arguments de ligne de commande sont aussi lus : un nombre définit le port lorsque `options.port` est vide, et tout autre argument qui n'est pas une URL et ne commence pas par `--` devient `unixsocket`. Le script de démarrage appelle normalement cette fonction pour toi.\n\nExample: Démarrer sur un port\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Démarrer plus tard\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nDémarre l'application avec un serveur HTTPS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` ou `'release'`. |\n| `options` | `Object` | yes |  | Options de démarrage avec `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, comme dans `HTTP()`. |\n\nReturns: `undefined`\n\nFonctionne comme `HTTP()` mais crée un serveur `https` de Node.js. `options.https` est passé à `https.createServer()` : une chaîne `key` ou `cert` qui contient un point est lue comme un fichier, les autres chaînes sont décodées depuis le base64. D'autres options TLS de Node.js peuvent être ajoutées au même objet.\n\nExample: Certificats depuis des fichiers\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nL'objet d'options de `HTTP()` et `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | Le port. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | L'adresse IP. |\n| `unixsocket` | `String` | no |  | Un chemin de socket Unix sur lequel écouter au lieu d'un port. |\n| `unixsocket777` | `Boolean` | no | `false` | Règle les permissions du fichier socket sur `0777`. |\n| `config` | `Object` | no |  | Des valeurs copiées dans `CONF` avant l'utilisation de la configuration. |\n| `https` | `Object` | no |  | `{ key, cert }` et d'autres options TLS pour `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)` qui démarre l'écoute. |\n| `id` | `String` | no |  | L'identifiant de l'instance, conservé dans `F.id`. |\n\nLe même objet est passé au script de démarrage `require('total4/release')(options)` ou `require('total4/debug')(options)`, qui le transmet à `HTTP()`. Les valeurs par défaut du port et de l'IP proviennent des clés de configuration `default_port`, `default_ip` et `default_unixsocket` (voir [Configuration](../../guides/configuration/)). `ip: 'auto'` écoute sur `0.0.0.0`.\n\nExample: Dans le script de démarrage\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nLe serveur HTTP ou HTTPS Node.js de l'application.\n\nReturns: `http.Server`\n\nCréé au démarrage du serveur. Tu peux l'utiliser pour lire l'adresse ou pour attacher des écouteurs de Node.js.\n\nExample: Écouter les connexions\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nLe port sur lequel le serveur écoute.\n\nReturns: `Number`\n\nDéfini au démarrage du serveur, à partir de `options.port`, de la ligne de commande, de `default_port` ou de `8000`.\n\nExample: Afficher l'adresse\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nL'adresse IP sur laquelle le serveur écoute.\n\nReturns: `String`\n\nDéfinie au démarrage du serveur, à partir de `options.ip`, de `default_ip` ou de `0.0.0.0`.\n\nExample: La lire\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nOptimise les sockets du serveur HTTP pour de nombreuses connexions.\n\nReturns: `Boolean`\n\nAvec `true`, chaque socket entrant reçoit `setNoDelay(true)` et le keep-alive, et l'agent HTTP global de Node.js peut ouvrir jusqu'à 9999 sockets. Par défaut : `false`.\n\nExample: Dans le fichier de configuration\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nAutorise les requêtes cross-origin vers un chemin.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Le chemin, par exemple `/api/*`, ou une liste d'origines. |\n| `flags` | `Array` | no |  | Origines, méthodes, durée maximale et `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Envoie `Access-Control-Allow-Credentials: true`. `flags` peut valoir `true` pour le même effet. |\n\nReturns: `Object` La règle, avec `remove()` pour la supprimer.\n\nEnregistre une règle CORS. Le framework répond aux requêtes préliminaires `OPTIONS` avec `200` et ajoute les en-têtes `Access-Control-*` aux autres requêtes. Une `url` qui se termine par `*` ou contient `{` couvre tous les chemins en dessous. Dans `flags`, les origines sont `'https://host'`, `'http://host'` ou `'//host'` ; les méthodes HTTP sont `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (par défaut : toutes) ; un nombre est la durée maximale en secondes ; `true` ou `'credentials'` autorise les identifiants. Sans origines, la clé de configuration `default_cors` est utilisée, et sans elle toute origine est autorisée. Une requête provenant d'une autre origine reçoit une `404` vide. Appeler à nouveau `CORS()` avec la même URL étend la règle existante.\n\nSans arguments, tous les chemins et toutes les origines sont autorisés. Un premier argument qui commence par `http://` ou `https://` est une liste d'origines séparées par des virgules, autorisées sur tous les chemins.\n\nExample: API pour une seule origine\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Tout\n```js\nCORS();\n```\n\nExample: Origines pour toute l'application\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Supprimer plus tard\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nCombien de temps les navigateurs peuvent mettre en cache une réponse CORS préliminaire.\n\nReturns: `Number`\n\nLa valeur de `Access-Control-Max-Age` en secondes pour les règles `CORS()` sans leur propre flag numérique. Par défaut : `120`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nTransmet les requêtes situées sous un chemin à un autre serveur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Le préfixe de chemin, se terminant par `/`. |\n| `target` | `String` | yes |  | L'adresse cible ou le chemin du socket Unix. `null` supprime le proxy. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` ou `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)` appelée avant l'envoi de la requête ; modifie ici `uri.headers` ou `uri.path`. |\n| `after` | `Function` | no |  | `function(response)` appelée avec la réponse de la cible avant qu'elle ne soit envoyée au client. |\n| `check` | `Function` | no |  | `function(req, res)` ; renvoie `false` pour ignorer le proxy pour cette requête. |\n| `timeout` | `Number` | no | `10000` | Délai d'expiration en millisecondes. |\n\nReturns: `Object` Le proxy, avec `remove()` pour le supprimer.\n\nChaque requête dont le chemin commence par `url` (en minuscules, se terminant par `/`) est envoyée à `target` et la réponse est renvoyée en flux. La cible est une adresse `http://` ou `https://` ou un chemin de socket Unix. Les proxies sont vérifiés avant les redirections, le middleware et les routes, et les connexions WebSocket sont aussi transmises. La requête reçoit les en-têtes `X-Forwarded-For`, `X-Forwarded-Url` et `X-Forwarded-Host`. Lorsque la cible échoue, le client reçoit la page d'erreur `503`.\n\n`copypath` : non défini, il ajoute le chemin complet de la requête au chemin de la cible ; `'replace'` et `'extend'` retirent le préfixe `url` ; `true` ne le retire que lorsque la cible a un chemin ; `false` utilise toujours uniquement le chemin de la cible. Lorsque `copypath` est une fonction, c'est `before`, et l'argument suivant est `after`. Lorsque `check` est un nombre, c'est `timeout`. `PROXY(url, null)` supprime le proxy.\n\nExample: Transmettre une API\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Ajouter un en-tête\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Socket Unix\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nRedirige un hôte ou une URL vers une autre adresse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Une adresse complète (`protocol://host`) ou un chemin. |\n| `to` | `String` | yes |  | La nouvelle adresse ou le nouveau chemin. |\n| `path` | `Boolean` | no | `false` | Pour les hôtes : conserver le chemin et la query. Pour les chemins : rendre la redirection permanente. |\n| `permanent` | `Boolean` | no | `false` | Pour les hôtes : répondre `301`. |\n\nReturns: `undefined`\n\nAvec une adresse complète dans `from` (`http://example.com`), chaque requête vers ce protocole et cet hôte est redirigée avant le routage ; `path` conserve le chemin et la query, `permanent` répond `301` au lieu de `302`.\n\nAvec un chemin dans `from`, une route `GET` est créée, qui redirige vers `to` et conserve la query string. Sous cette forme, le troisième argument rend la redirection permanente, et un tableau en troisième ou quatrième position est passé comme flags de route. Un chemin vers un fichier statique (`/docs.pdf`) crée plutôt une route de fichier.\n\nExample: Passer à HTTPS et www\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: Une ancienne page\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nRépond à une requête par une redirection.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'adresse cible. |\n| `permanent` | `Boolean` | no | `false` | Envoie `301 Moved Permanently`. |\n\nReturns: `Response` La réponse.\n\nEnvoie `302`, ou `301` lorsque `permanent` vaut `true`, avec l'en-tête `Location`. Utile dans le middleware et les gestionnaires de fichiers, où il n'y a pas de contrôleur.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDéclare la page d'un statut d'erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Le statut, par exemple `#404`. |\n| `action` | `Function` | yes |  | L'action qui répond. |\n\nReturns: `undefined`\n\nUne route de statut s'exécute lorsque la requête se termine avec ce statut : `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` ou `#503`. Le contrôleur contient le problème ou l'erreur dans `this.exception` ; définis toi-même `this.status`. Sans route de statut, le framework répond avec sa page d'erreur HTML intégrée, ou avec des erreurs JSON lorsque `default_errorbuilder_errors` est activé ou que la requête est XHR (`default_errorbuilder_forxhr`). Un dépassement de délai répond `503`, un corps dépassant la taille limite `431`.\n\nExample: 404 et 500 personnalisées\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nRépond aux requêtes XHR avec des erreurs JSON au lieu de la page d'erreur HTML.\n\nReturns: `Boolean`\n\nLorsqu'une requête avec `X-Requested-With: XMLHttpRequest` se termine avec un statut d'erreur et qu'il n'y a pas de route de statut, la réponse est un tableau JSON `ErrorBuilder`. Par défaut : `true`.\n\nExample: Dans le fichier de configuration\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nRépond avec le statut d'erreur 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description passée à `this.exception` de la route de statut. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#400` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error400`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw400()`.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nRépond avec le statut d'erreur 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description passée à `this.exception` de la route de statut. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#401` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error401`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw401()`.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nRépond avec le statut d'erreur 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description passée à `this.exception` de la route de statut. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#403` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error403`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw403()`.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nRépond avec le statut d'erreur 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Une description passée à `this.exception` de la route de statut. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#404` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error404`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw404()`.\n\nExample: Dans un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nRépond avec le statut d'erreur 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'erreur ; elle est journalisée avec `F.error()`. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#500` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error500`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw500()`.\n\nExample: En cas d'erreur\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nRépond avec le statut d'erreur 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'erreur ; elle est journalisée avec `F.error()`. |\n\nReturns: `Response` La réponse.\n\nExécute la route de statut `#503` ou la page d'erreur intégrée. Pour une requête `HEAD`, seul le statut est envoyé. Elle émet aussi l'événement `error503`. Utilise-la dans le middleware et les gestionnaires de fichiers ; dans les actions, utilise `controller.throw503()`.\n\nExample: En cas d'erreur\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nJournalise une erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'erreur. Rien ne se passe lorsqu'elle est vide. |\n| `name` | `String` | no |  | L'endroit où elle s'est produite, affiché avec l'erreur. |\n| `uri` | `String|Object` | no |  | L'URL de la requête. |\n\nReturns: `undefined`\n\nAppelle `DEF.onError`. Le gestionnaire par défaut affiche l'erreur dans la console, la conserve dans `F.errors` et émet l'événement `error`. Sans arguments, elle renvoie un callback `function(err)` qui journalise les erreurs.\n\nExample: Journaliser une erreur\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nRenvoie un callback qui journalise son erreur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Un libellé affiché avec l'erreur. |\n\nReturns: `Function` `function(err)`.\n\nLe callback `function(err)` appelle `F.error(err, name)` lorsque `err` n'est pas vide. Utilise-le lorsque tu as besoin d'un callback mais que le résultat ne t'importe pas.\n\nExample: Ignorer le résultat, journaliser l'erreur\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nLa fonction qui gère chaque erreur journalisée par le framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'erreur. |\n| `name` | `String` | yes |  | L'endroit où elle s'est produite. |\n| `uri` | `Object|String` | yes |  | L'URL de la requête, s'il y en a une. |\n\n`F.error()`, les erreurs dans les actions et `throw500()` aboutissent tous ici. Par défaut, elle affiche `ERROR ======= date: name ---> error (url)` et la pile, conserve les cinq dernières erreurs dans `F.errors` et émet `ON('error')`. Remplace-la pour envoyer les erreurs ailleurs ; tu peux appeler l'originale depuis la tienne.\n\nExample: Envoyer les erreurs à un service\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nLes cinq dernières erreurs journalisées.\n\nReturns: `Array`\n\nChaque élément est `{ error, name, url, date }`. Rempli par le `DEF.onError` par défaut.\n\nExample: Les afficher\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nRenvoie l'objet de réponse `{ success, value, error }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | Le résultat, une erreur, ou un callback à envelopper. |\n| `value` | `Object` | no |  | Une valeur pour la propriété `value`. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` donne `{ success: true }`. `SUCCESS(true, value)` ajoute `value` (une instance de schéma est d'abord nettoyée). Une `Error` ou un `ErrorBuilder` contenant des erreurs donne `success: false` et le texte de l'erreur dans `error`. Avec une fonction, elle renvoie un callback `(err, value)` qui appelle ta fonction avec `SUCCESS(err, value)` comme deuxième argument. La fonction renvoie un objet partagé unique : lis-le ou envoie-le immédiatement et ne le conserve pas.\n\nExample: Dans une action\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: Avec une valeur\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nAppelle une fonction quand une requête, une réponse ou un flux se termine.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | Ce qu'il faut surveiller. |\n| `callback` | `Function` | yes |  | Appelé une seule fois, à la fin. |\n\nReturns: `undefined`\n\nPour une requête ou une réponse, le callback s'exécute quand son socket se ferme ou échoue, y compris quand le client s'en va. Pour les autres flux, il s'exécute quand ils se terminent. Plusieurs callbacks peuvent attendre le même flux.\n\nExample: Nettoyer après une réponse\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nDétruit un flux et ferme son descripteur de fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Le flux. |\n\nReturns: `Stream` Le même flux.\n\nUn flux de lecture de fichier est détruit et fermé même s'il est encore en cours d'ouverture. Les autres flux Node.js sont détruits avec `destroy()`.\n\nExample: Arrêter la lecture\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nUn contrôleur sans requête.\n\nReturns: `Controller`\n\nLe framework l'utilise pour `VIEW()` et `MAIL()`, où il n'y a pas de requête HTTP. Son `req` a une URL, une query, un corps et des fichiers vides. Tu peux l'utiliser pour appeler des utilitaires de contrôleur hors d'une requête ; ne réponds pas avec lui.\n\nExample: Une URL du sitemap hors d'une requête\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmHV5ai61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Server HTTP","summary":"Funzioni per l'avvio del server, CORS, proxy, redirect e la gestione degli errori.","markdown":"---\ntitle: Server HTTP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# Server HTTP\n\n> Funzioni per l'avvio del server, CORS, proxy, redirect e la gestione degli errori.\n\nFunzioni e impostazioni del server HTTP che non sono route: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, le pagine di errore e gli helper per gli errori. La guida [Server HTTP: CORS, proxy ed errori](../../guides/http-server/) li spiega con esempi; questa pagina è il riferimento esatto. La sitemap ha una pagina propria: [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nAvvia il server HTTP e carica l'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no |  | Opzioni di avvio, vedi [Opzioni HTTP](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)`; il server si mette in ascolto solo quando chiami `listen()`. Equivale a `options.middleware`. |\n\nReturns: `undefined`\n\nCarica la configurazione, la sitemap e tutti i file dell'applicazione, poi si mette in ascolto. `mode` è `'debug'` o `'release'`. Vengono letti anche gli argomenti della riga di comando: un numero imposta la porta quando `options.port` è vuoto, e qualsiasi altro argomento che non è un URL e non inizia con `--` diventa `unixsocket`. Di solito è lo script di avvio a chiamare questa funzione per te.\n\nExample: Avviare su una porta\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Avviare più tardi\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nAvvia l'applicazione con un server HTTPS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | yes |  | Opzioni di avvio con `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, come in `HTTP()`. |\n\nReturns: `undefined`\n\nFunziona come `HTTP()` ma crea un server `https` di Node.js. `options.https` viene passato a `https.createServer()`: una stringa `key` o `cert` che contiene un punto viene letta come file, le altre stringhe vengono decodificate da base64. Altre opzioni TLS di Node.js possono essere aggiunte allo stesso oggetto.\n\nExample: Certificati da file\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nL'oggetto delle opzioni di `HTTP()` e `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | La porta. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | L'indirizzo IP. |\n| `unixsocket` | `String` | no |  | Il percorso di un socket Unix su cui ascoltare invece che su una porta. |\n| `unixsocket777` | `Boolean` | no | `false` | Imposta i permessi del file del socket a `0777`. |\n| `config` | `Object` | no |  | Valori copiati in `CONF` prima che la configurazione venga usata. |\n| `https` | `Object` | no |  | `{ key, cert }` e altre opzioni TLS per `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)` che avvia l'ascolto. |\n| `id` | `String` | no |  | L'identificatore dell'istanza, conservato in `F.id`. |\n\nLo stesso oggetto viene passato allo script di avvio `require('total4/release')(options)` o `require('total4/debug')(options)`, che lo consegna a `HTTP()`. I valori predefiniti di porta e IP provengono dalle chiavi di configurazione `default_port`, `default_ip` e `default_unixsocket` (vedi [Configurazione](../../guides/configuration/)). `ip: 'auto'` si mette in ascolto su `0.0.0.0`.\n\nExample: Nello script di avvio\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nIl server HTTP o HTTPS di Node.js dell'applicazione.\n\nReturns: `http.Server`\n\nViene creato all'avvio del server. Puoi usarlo per leggere l'indirizzo o per collegare listener di Node.js.\n\nExample: Ascoltare le connessioni\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nLa porta su cui il server è in ascolto.\n\nReturns: `Number`\n\nImpostata all'avvio del server, da `options.port`, dalla riga di comando, da `default_port` o `8000`.\n\nExample: Stampare l'indirizzo\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nL'indirizzo IP su cui il server è in ascolto.\n\nReturns: `String`\n\nImpostato all'avvio del server, da `options.ip`, `default_ip` o `0.0.0.0`.\n\nExample: Leggerlo\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nOttimizza i socket del server HTTP per molte connessioni.\n\nReturns: `Boolean`\n\nCon `true`, ogni socket in entrata riceve `setNoDelay(true)` e keep-alive, e l'agent HTTP globale di Node.js può aprire fino a 9999 socket. Predefinito: `false`.\n\nExample: Nel file di configurazione\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nConsente richieste cross-origin verso un percorso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Il percorso, per esempio `/api/*`, oppure un elenco di origini. |\n| `flags` | `Array` | no |  | Origini, metodi, max age e `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Invia `Access-Control-Allow-Credentials: true`. `flags` può essere `true` per lo stesso effetto. |\n\nReturns: `Object` La regola, con `remove()` per eliminarla.\n\nRegistra una regola CORS. Il framework risponde alle richieste preflight `OPTIONS` con `200` e aggiunge gli header `Access-Control-*` alle altre richieste. Un `url` che termina con `*` o contiene `{` copre tutti i percorsi sottostanti. In `flags`, le origini sono `'https://host'`, `'http://host'` o `'//host'`; i metodi HTTP sono `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (predefinito: tutti); un numero è il max age in secondi; `true` o `'credentials'` consente le credenziali. Senza origini si usa la chiave di configurazione `default_cors` e, senza di essa, ogni origine è consentita. Una richiesta da un'altra origine riceve un `404` vuoto. Chiamare di nuovo `CORS()` con lo stesso URL estende la regola esistente.\n\nSenza argomenti, ogni percorso e ogni origine sono consentiti. Un primo argomento che inizia con `http://` o `https://` è un elenco di origini separate da virgole, consentite su ogni percorso.\n\nExample: API per una sola origine\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Tutto\n```js\nCORS();\n```\n\nExample: Origini per l'intera app\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Rimuovere in seguito\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nPer quanto tempo i browser possono mettere in cache una risposta preflight CORS.\n\nReturns: `Number`\n\nIl valore di `Access-Control-Max-Age` in secondi per le regole `CORS()` senza un proprio flag numerico. Predefinito: `120`.\n\nExample: Nel file di configurazione\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nInoltra le richieste sotto un percorso a un altro server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Il prefisso del percorso, terminato da `/`. |\n| `target` | `String` | yes |  | L'indirizzo di destinazione o il percorso del socket Unix. `null` rimuove il proxy. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` o `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)` chiamata prima dell'invio della richiesta; qui puoi modificare `uri.headers` o `uri.path`. |\n| `after` | `Function` | no |  | `function(response)` chiamata con la risposta della destinazione prima che venga inviata al client. |\n| `check` | `Function` | no |  | `function(req, res)`; restituisci `false` per saltare il proxy per questa richiesta. |\n| `timeout` | `Number` | no | `10000` | Timeout in millisecondi. |\n\nReturns: `Object` Il proxy, con `remove()` per eliminarlo.\n\nOgni richiesta il cui percorso inizia con `url` (in minuscolo, terminato da `/`) viene inviata a `target` e la risposta viene restituita in streaming. La destinazione è un indirizzo `http://` o `https://` o il percorso di un socket Unix. I proxy vengono controllati prima di redirect, middleware e route, e anche le connessioni WebSocket vengono inoltrate. La richiesta riceve gli header `X-Forwarded-For`, `X-Forwarded-Url` e `X-Forwarded-Host`. Quando la destinazione fallisce, il client riceve la pagina di errore `503`.\n\n`copypath`: se non è impostato, l'intero percorso della richiesta viene accodato al percorso della destinazione; `'replace'` ed `'extend'` rimuovono il prefisso `url`; `true` lo rimuove solo quando la destinazione ha un percorso; `false` usa sempre solo il percorso della destinazione. Quando `copypath` è una funzione, si tratta di `before`, e l'argomento successivo è `after`. Quando `check` è un numero, si tratta di `timeout`. `PROXY(url, null)` rimuove il proxy.\n\nExample: Inoltrare un'API\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Aggiungere un header\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Socket Unix\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nReindirizza un host o un URL a un altro indirizzo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Un indirizzo completo (`protocol://host`) o un percorso. |\n| `to` | `String` | yes |  | Il nuovo indirizzo o percorso. |\n| `path` | `Boolean` | no | `false` | Per gli host: mantiene il percorso e la query. Per i percorsi: rende il redirect permanente. |\n| `permanent` | `Boolean` | no | `false` | Per gli host: risponde `301`. |\n\nReturns: `undefined`\n\nCon un indirizzo completo in `from` (`http://example.com`), ogni richiesta a quel protocollo e host viene reindirizzata prima del routing; `path` mantiene il percorso e la query, `permanent` risponde `301` invece di `302`.\n\nCon un percorso in `from`, viene creata una route `GET` che reindirizza a `to` e mantiene la query string. In questa forma il terzo argomento rende il redirect permanente, e un array in terza o quarta posizione viene passato come flag della route. Un percorso verso un file statico (`/docs.pdf`) crea invece una route per file.\n\nExample: Passare a HTTPS e www\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: Una vecchia pagina\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nRisponde a una richiesta con un redirect.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'indirizzo di destinazione. |\n| `permanent` | `Boolean` | no | `false` | Invia `301 Moved Permanently`. |\n\nReturns: `Response` La risposta.\n\nInvia `302`, oppure `301` quando `permanent` è `true`, con l'header `Location`. Utile nei middleware e nei gestori di file, dove non c'è un controller.\n\nExample: In un middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDichiara la pagina per uno stato di errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Lo stato, per esempio `#404`. |\n| `action` | `Function` | yes |  | L'azione che risponde. |\n\nReturns: `undefined`\n\nUna route di stato viene eseguita quando la richiesta termina con quello stato: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` o `#503`. Il controller ha il problema o l'errore in `this.exception`; imposta tu `this.status`. Senza una route di stato, il framework risponde con la sua pagina di errore HTML integrata, oppure con errori JSON quando `default_errorbuilder_errors` è attivo o la richiesta è XHR (`default_errorbuilder_forxhr`). Un timeout risponde `503`, un body oltre il limite di dimensione `431`.\n\nExample: 404 e 500 personalizzati\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nRisponde alle richieste XHR con errori JSON invece della pagina di errore HTML.\n\nReturns: `Boolean`\n\nQuando una richiesta con `X-Requested-With: XMLHttpRequest` termina con uno stato di errore e non c'è una route di stato, la risposta è un array JSON di `ErrorBuilder`. Predefinito: `true`.\n\nExample: Nel file di configurazione\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nRisponde con lo stato di errore 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione passata a `this.exception` della route di stato. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#400` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error400`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw400()`.\n\nExample: In un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nRisponde con lo stato di errore 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione passata a `this.exception` della route di stato. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#401` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error401`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw401()`.\n\nExample: In un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nRisponde con lo stato di errore 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione passata a `this.exception` della route di stato. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#403` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error403`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw403()`.\n\nExample: In un middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nRisponde con lo stato di errore 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Una descrizione passata a `this.exception` della route di stato. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#404` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error404`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw404()`.\n\nExample: In un middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nRisponde con lo stato di errore 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'errore; viene registrato nel log con `F.error()`. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#500` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error500`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw500()`.\n\nExample: In caso di errore\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nRisponde con lo stato di errore 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | L'errore; viene registrato nel log con `F.error()`. |\n\nReturns: `Response` La risposta.\n\nEsegue la route di stato `#503` o la pagina di errore integrata. Per una richiesta `HEAD` viene inviato solo lo stato. Emette anche l'evento `error503`. Usalo nei middleware e nei gestori di file; nelle azioni usa `controller.throw503()`.\n\nExample: In caso di errore\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nRegistra un errore nel log.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'errore. Non succede nulla quando è vuoto. |\n| `name` | `String` | no |  | Dove si è verificato, stampato insieme all'errore. |\n| `uri` | `String|Object` | no |  | L'URL della richiesta. |\n\nReturns: `undefined`\n\nChiama `DEF.onError`. Il gestore predefinito stampa l'errore nella console, lo conserva in `F.errors` ed emette l'evento `error`. Senza argomenti restituisce una callback `function(err)` che registra gli errori.\n\nExample: Registrare un errore\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nRestituisce una callback che registra il suo errore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Un'etichetta stampata insieme all'errore. |\n\nReturns: `Function` `function(err)`.\n\nLa callback `function(err)` chiama `F.error(err, name)` quando `err` non è vuoto. Usala dove ti serve una callback ma il risultato non ti interessa.\n\nExample: Ignorare il risultato, registrare l'errore\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nLa funzione che gestisce ogni errore registrato dal framework.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | L'errore. |\n| `name` | `String` | yes |  | Il punto in cui si è verificato. |\n| `uri` | `Object|String` | yes |  | L'URL della richiesta, quando c'è. |\n\n`F.error()`, gli errori nelle azioni e `throw500()` finiscono tutti qui. La funzione predefinita stampa `ERROR ======= date: name ---> error (url)` e lo stack, conserva gli ultimi cinque errori in `F.errors` ed emette `ON('error')`. Sostituiscila per inviare gli errori altrove; dalla tua puoi chiamare quella originale.\n\nExample: Inviare gli errori a un servizio\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nGli ultimi cinque errori registrati.\n\nReturns: `Array`\n\nOgni elemento è `{ error, name, url, date }`. Viene riempito dal `DEF.onError` predefinito.\n\nExample: Mostrarli\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nRestituisce l'oggetto di risposta `{ success, value, error }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | Il risultato, un errore o una callback da avvolgere. |\n| `value` | `Object` | no |  | Un valore per la proprietà `value`. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` restituisce `{ success: true }`. `SUCCESS(true, value)` aggiunge `value` (un'istanza di schema viene prima ripulita). Un `Error` o un `ErrorBuilder` con errori dà `success: false` e il testo dell'errore in `error`. Con una funzione, restituisce una callback `(err, value)` che chiama la tua funzione con `SUCCESS(err, value)` come secondo argomento. La funzione restituisce un unico oggetto condiviso, quindi leggilo o invialo subito e non conservarlo.\n\nExample: In un'azione\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: Con un valore\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nChiama una funzione quando una richiesta, una risposta o uno stream termina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | Cosa osservare. |\n| `callback` | `Function` | yes |  | Chiamata una sola volta alla fine. |\n\nReturns: `undefined`\n\nPer una richiesta o una risposta, la callback viene eseguita quando il suo socket si chiude o fallisce, anche quando il client se ne va. Per gli altri stream viene eseguita quando terminano. Più callback possono attendere lo stesso stream.\n\nExample: Fare pulizia dopo una risposta\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nDistrugge uno stream e chiude il suo file descriptor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Lo stream. |\n\nReturns: `Stream` Lo stesso stream.\n\nUno stream di lettura di file viene distrutto e chiuso anche se è ancora in fase di apertura. Gli altri stream di Node.js vengono distrutti con `destroy()`.\n\nExample: Interrompere la lettura\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nUn controller senza richiesta.\n\nReturns: `Controller`\n\nIl framework lo usa per `VIEW()` e `MAIL()`, dove non c'è una richiesta HTTP. Il suo `req` ha URL, query, body e file vuoti. Puoi usarlo per chiamare gli helper del controller fuori da una richiesta; non usarlo per rispondere.\n\nExample: Un URL della sitemap fuori da una richiesta\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"JabmHV5ai61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/http-server/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"HTTP server","summary":"Funkcie na spustenie servera, CORS, proxy, presmerovania a spracovanie chýb.","markdown":"---\ntitle: HTTP server\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/http-server/\nupdated: 2026-11-16T15:41:15.818Z\n---\n\n# HTTP server\n\n> Funkcie na spustenie servera, CORS, proxy, presmerovania a spracovanie chýb.\n\nFunkcie a nastavenia HTTP servera, ktoré nie sú trasy: `HTTP()`, `CORS()`, `PROXY()`, `REDIRECT()`, chybové stránky a pomocníci pre chyby. Príručka [HTTP server: CORS, proxy a chyby](../../guides/http-server/) ich vysvetľuje s príkladmi; táto stránka je presná referencia. Sitemap má vlastnú stránku: [Sitemap](../sitemap/).\n\n## API\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nSpustí HTTP server a načíta aplikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` alebo `'release'`. |\n| `options` | `Object` | no |  | Štartovacie možnosti, pozri [Možnosti HTTP](#http-options). |\n| `middleware` | `Function` | no |  | `function(listen)`; server začne počúvať, až keď zavoláš `listen()`. To isté ako `options.middleware`. |\n\nReturns: `undefined`\n\nNačíta konfiguráciu, sitemapu a všetky súbory aplikácie a potom začne počúvať. `mode` je `'debug'` alebo `'release'`. Čítajú sa aj argumenty príkazového riadku: číslo nastaví port, keď je `options.port` prázdne, a akýkoľvek iný argument, ktorý nie je URL a nezačína `--`, sa stane `unixsocket`. Štartovací skript túto funkciu zvyčajne volá za teba.\n\nExample: Spustenie na porte\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 });\n```\n\nExample: Neskoršie spustenie\n```js\nrequire('total4');\n\nHTTP('release', { port: 8000 }, function(listen) {\n\t// prepare something, then:\n\tlisten();\n});\n```\n\n### HTTPS(mode, options, [middleware])\n\nType: `method`\n\nSpustí aplikáciu s HTTPS serverom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` alebo `'release'`. |\n| `options` | `Object` | yes |  | Štartovacie možnosti s `https: { key, cert }`. |\n| `middleware` | `Function` | no |  | `function(listen)`, ako v `HTTP()`. |\n\nReturns: `undefined`\n\nFunguje ako `HTTP()`, ale vytvorí server Node.js `https`. `options.https` sa odovzdá do `https.createServer()`: reťazec `key` alebo `cert`, ktorý obsahuje bodku, sa načíta ako súbor, ostatné reťazce sa dekódujú z base64. Do toho istého objektu môžeš pridať aj ďalšie TLS možnosti Node.js.\n\nExample: Certifikáty zo súborov\n```js\nrequire('total4');\n\nHTTPS('release', {\n\tport: 443,\n\thttps: {\n\t\tkey: 'keys/server.key',\n\t\tcert: 'keys/server.crt'\n\t}\n});\n```\n\n### { port, ip, unixsocket, unixsocket777, config, https, middleware, id }\n\nType: `type`\n\nObjekt možností pre `HTTP()` a `HTTPS()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | no | `CONF.default_port or 8000` | Port. |\n| `ip` | `String` | no | `CONF.default_ip or '0.0.0.0'` | IP adresa. |\n| `unixsocket` | `String` | no |  | Cesta k Unix socketu, na ktorom sa počúva namiesto portu. |\n| `unixsocket777` | `Boolean` | no | `false` | Nastaví oprávnenia súboru socketu na `0777`. |\n| `config` | `Object` | no |  | Hodnoty skopírované do `CONF` predtým, ako sa konfigurácia použije. |\n| `https` | `Object` | no |  | `{ key, cert }` a ďalšie TLS možnosti pre `HTTPS()`. |\n| `middleware` | `Function` | no |  | `function(listen)`, ktorá spustí počúvanie. |\n| `id` | `String` | no |  | Identifikátor inštancie, uložený v `F.id`. |\n\nTen istý objekt sa odovzdáva štartovaciemu skriptu `require('total4/release')(options)` alebo `require('total4/debug')(options)`, ktorý ho posunie do `HTTP()`. Predvolené hodnoty portu a IP pochádzajú z konfiguračných kľúčov `default_port`, `default_ip` a `default_unixsocket` (pozri [Konfigurácia](../../guides/configuration/)). `ip: 'auto'` počúva na `0.0.0.0`.\n\nExample: V štartovacom skripte\n```js\n// index.js\nconst options = {};\noptions.port = 8000;\noptions.ip = '127.0.0.1';\noptions.config = { name: 'Shop' };\nrequire('total4/release')(options);\n```\n\n### F.server\n\nType: `property`\n\nHTTP alebo HTTPS server Node.js aplikácie.\n\nReturns: `http.Server`\n\nVytvorí sa pri štarte servera. Môžeš ho použiť na čítanie adresy alebo na pripojenie poslucháčov Node.js.\n\nExample: Počúvanie spojení\n```js\nON('ready', function() {\n\tF.server.on('connection', function(socket) {\n\t\tsocket.setTimeout(60000);\n\t});\n});\n```\n\n### F.port\n\nType: `property`\n\nPort, na ktorom server počúva.\n\nReturns: `Number`\n\nNastaví sa pri štarte servera z `options.port`, z príkazového riadku, z `default_port` alebo na `8000`.\n\nExample: Výpis adresy\n```js\nON('ready', function() {\n\tconsole.log('Listening on ' + F.ip + ':' + F.port);\n});\n```\n\n### F.ip\n\nType: `property`\n\nIP adresa, na ktorej server počúva.\n\nReturns: `String`\n\nNastaví sa pri štarte servera z `options.ip`, z `default_ip` alebo na `0.0.0.0`.\n\nExample: Čítanie\n```js\nON('ready', function() {\n\tconsole.log(F.ip);\n});\n```\n\n### allow_performance : true\n\nType: `config`\n\nVyladí sockety HTTP servera pre veľa spojení.\n\nReturns: `Boolean`\n\nPri `true` dostane každý prichádzajúci socket `setNoDelay(true)` a keep-alive a globálny HTTP agent Node.js môže otvoriť až 9999 socketov. Predvolene: `false`.\n\nExample: V konfiguračnom súbore\n```text\nallow_performance : true\n```\n\n### CORS([url], [flags], [credentials])\n\nType: `method`\n\nPovolí požiadavky z iných originov na cestu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | no |  | Cesta, napríklad `/api/*`, alebo zoznam originov. |\n| `flags` | `Array` | no |  | Originy, metódy, max age a `credentials`. |\n| `credentials` | `Boolean` | no | `false` | Posiela `Access-Control-Allow-Credentials: true`. Rovnaký účinok má `flags` nastavené na `true`. |\n\nReturns: `Object` Pravidlo s `remove()` na jeho zmazanie.\n\nZaregistruje pravidlo CORS. Framework odpovedá na preflight požiadavky `OPTIONS` stavom `200` a k ostatným požiadavkám pridá hlavičky `Access-Control-*`. `url`, ktorá končí `*` alebo obsahuje `{`, pokrýva všetky cesty pod ňou. V `flags` sú originy `'https://host'`, `'http://host'` alebo `'//host'`; HTTP metódy sú `'get'`, `'post'`, `'put'`, `'patch'`, `'delete'`, `'head'`, `'options'` (predvolene: všetky); číslo je max age v sekundách; `true` alebo `'credentials'` povolí credentials. Bez originov sa použije konfiguračný kľúč `default_cors` a bez neho je povolený každý origin. Požiadavka z iného originu dostane prázdnu odpoveď `404`. Opätovné volanie `CORS()` s tou istou URL rozšíri existujúce pravidlo.\n\nBez argumentov je povolená každá cesta a každý origin. Prvý argument, ktorý začína `http://` alebo `https://`, je zoznam originov oddelených čiarkami, povolených na každej ceste.\n\nExample: API pre jeden origin\n```js\nexports.install = function() {\n\tCORS('/api/*', ['https://app.example.com', 'get', 'post', 'credentials']);\n};\n```\n\nExample: Všetko\n```js\nCORS();\n```\n\nExample: Originy pre celú aplikáciu\n```js\nCORS('https://app.example.com, https://admin.example.com');\n```\n\nExample: Neskoršie odstránenie\n```js\nvar rule = CORS('/public/*');\n// ...\nrule.remove();\n```\n\n### default_cors_maxage : 120\n\nType: `config`\n\nAko dlho môžu prehliadače uchovávať v cache odpoveď na preflight CORS.\n\nReturns: `Number`\n\nHodnota `Access-Control-Max-Age` v sekundách pre pravidlá `CORS()` bez vlastného číselného flagu. Predvolene: `120`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_cors_maxage : 600\n```\n\n### PROXY(url, target, [copypath], [before], [after], [check], [timeout])\n\nType: `method`\n\nPrepošle požiadavky pod cestou na iný server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Prefix cesty, končiaci `/`. |\n| `target` | `String` | yes |  | Cieľová adresa alebo cesta k Unix socketu. `null` proxy odstráni. |\n| `copypath` | `Boolean|String` | no |  | `true`, `false`, `'replace'` alebo `'extend'`. |\n| `before` | `Function` | no |  | `function(uri, req, res)` volaná pred odoslaním požiadavky; tu zmeň `uri.headers` alebo `uri.path`. |\n| `after` | `Function` | no |  | `function(response)` volaná s odpoveďou cieľa predtým, ako sa pošle klientovi. |\n| `check` | `Function` | no |  | `function(req, res)`; vráť `false`, ak chceš proxy pre túto požiadavku preskočiť. |\n| `timeout` | `Number` | no | `10000` | Timeout v milisekundách. |\n\nReturns: `Object` Proxy s `remove()` na jeho zmazanie.\n\nKaždá požiadavka, ktorej cesta začína na `url` (malými písmenami, končí `/`), sa pošle na `target` a odpoveď sa streamuje späť. Cieľ je adresa `http://` alebo `https://` alebo cesta k Unix socketu. Proxy sa kontrolujú pred presmerovaniami, middleware a trasami a preposielajú sa aj spojenia WebSocket. Požiadavka dostane hlavičky `X-Forwarded-For`, `X-Forwarded-Url` a `X-Forwarded-Host`. Keď cieľ zlyhá, klient dostane chybovú stránku `503`.\n\n`copypath`: nenastavené pripojí celú cestu požiadavky k ceste cieľa; `'replace'` a `'extend'` odstránia prefix `url`; `true` ho odstráni, len keď má cieľ cestu; `false` vždy použije len cestu cieľa. Keď je `copypath` funkcia, je to `before` a ďalší argument je `after`. Keď je `check` číslo, je to `timeout`. `PROXY(url, null)` proxy odstráni.\n\nExample: Preposlanie API\n```js\nexports.install = function() {\n\tPROXY('/api/', 'http://127.0.0.1:8001', 'replace');\n};\n```\n\nExample: Pridanie hlavičky\n```js\nPROXY('/files/', 'https://files.example.com', function(uri, req, res) {\n\turi.headers['x-token'] = CONF.filestoken;\n});\n```\n\nExample: Unix socket\n```js\nPROXY('/service/', '/tmp/service.socket', 'replace');\n```\n\n### REDIRECT(from, to, [path], [permanent])\n\nType: `method`\n\nPresmeruje host alebo URL na inú adresu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `from` | `String` | yes |  | Úplná adresa (`protocol://host`) alebo cesta. |\n| `to` | `String` | yes |  | Nová adresa alebo cesta. |\n| `path` | `Boolean` | no | `false` | Pre hosty: ponechá cestu a query. Pre cesty: urobí presmerovanie trvalým. |\n| `permanent` | `Boolean` | no | `false` | Pre hosty: odpovie `301`. |\n\nReturns: `undefined`\n\nS úplnou adresou vo `from` (`http://example.com`) sa každá požiadavka na tento protokol a host presmeruje pred smerovaním; `path` ponechá cestu a query, `permanent` odpovie `301` namiesto `302`.\n\nS cestou vo `from` sa vytvorí trasa `GET`, ktorá presmeruje na `to` a ponechá query string. V tejto forme tretí argument urobí presmerovanie trvalým a pole na treťom alebo štvrtom mieste sa odovzdá ako flagy trasy. Cesta k statickému súboru (`/docs.pdf`) namiesto toho vytvorí súborovú trasu.\n\nExample: Presun na HTTPS a www\n```js\nREDIRECT('http://example.com', 'https://www.example.com', true, true);\n```\n\nExample: Stará stránka\n```js\nexports.install = function() {\n\tREDIRECT('/old-shop/', '/shop/', true);\n};\n```\n\n### res.redirect(url, [permanent])\n\nType: `method`\n\nOdpovie na požiadavku presmerovaním.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Cieľová adresa. |\n| `permanent` | `Boolean` | no | `false` | Pošle `301 Moved Permanently`. |\n\nReturns: `Response` Odpoveď.\n\nPošle `302` alebo `301`, keď je `permanent` `true`, s hlavičkou `Location`. Užitočné v middleware a obsluhe súborov, kde nie je kontrolér.\n\nExample: V middleware\n```js\nMIDDLEWARE('signin', function($) {\n\tif ($.user)\n\t\t$.next();\n\telse\n\t\t$.res.redirect('/signin/');\n});\n```\n\n### ROUTE('#code', action)\n\nType: `method`\n\nDeklaruje stránku pre chybový stav.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `code` | `String` | yes |  | Stav, napríklad `#404`. |\n| `action` | `Function` | yes |  | Akcia, ktorá odpovedá. |\n\nReturns: `undefined`\n\nStavová trasa sa spustí, keď požiadavka skončí s daným stavom: `#400`, `#401`, `#403`, `#404`, `#408`, `#409`, `#431`, `#500`, `#501` alebo `#503`. Kontrolér má problém alebo chybu v `this.exception`; `this.status` nastav sám. Bez stavovej trasy framework odpovie svojou vstavanou HTML chybovou stránkou alebo chybami v JSON, keď je zapnuté `default_errorbuilder_errors` alebo je požiadavka XHR (`default_errorbuilder_forxhr`). Timeout odpovie `503`, telo nad limit veľkosti `431`.\n\nExample: Vlastné 404 a 500\n```js\nexports.install = function() {\n\tROUTE('#404', notfound);\n\tROUTE('#500', servererror);\n};\n\nfunction notfound() {\n\tthis.status = 404;\n\tthis.view('404');\n}\n\nfunction servererror() {\n\tthis.status = 500;\n\tthis.plain('Something went wrong');\n}\n```\n\n### default_errorbuilder_forxhr : true\n\nType: `config`\n\nOdpovedá na XHR požiadavky chybami v JSON namiesto HTML chybovej stránky.\n\nReturns: `Boolean`\n\nKeď požiadavka s `X-Requested-With: XMLHttpRequest` skončí s chybovým stavom a neexistuje stavová trasa, odpoveďou je JSON pole `ErrorBuilder`. Predvolene: `true`.\n\nExample: V konfiguračnom súbore\n```text\ndefault_errorbuilder_forxhr : false\n```\n\n### res.throw400([problem])\n\nType: `method`\n\nOdpovie chybovým stavom 400 Bad Request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis odovzdaný do `this.exception` stavovej trasy. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#400` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error400`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw400()`.\n\nExample: V middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw400('Invalid API key');\n});\n```\n\n### res.throw401([problem])\n\nType: `method`\n\nOdpovie chybovým stavom 401 Unauthorized.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis odovzdaný do `this.exception` stavovej trasy. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#401` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error401`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw401()`.\n\nExample: V middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw401();\n});\n```\n\n### res.throw403([problem])\n\nType: `method`\n\nOdpovie chybovým stavom 403 Forbidden.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis odovzdaný do `this.exception` stavovej trasy. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#403` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error403`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw403()`.\n\nExample: V middleware\n```js\nMIDDLEWARE('admin', function($) {\n\tif ($.user && $.user.sa)\n\t\t$.next();\n\telse\n\t\t$.res.throw403();\n});\n```\n\n### res.throw404([problem])\n\nType: `method`\n\nOdpovie chybovým stavom 404 Not Found.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `problem` | `String` | no |  | Popis odovzdaný do `this.exception` stavovej trasy. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#404` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error404`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw404()`.\n\nExample: V middleware\n```js\nMIDDLEWARE('apikey', function($) {\n\tif ($.headers['x-api-key'] === CONF.apikey)\n\t\t$.next();\n\telse\n\t\t$.res.throw404('Invalid API key');\n});\n```\n\n### res.throw500([error])\n\nType: `method`\n\nOdpovie chybovým stavom 500 Internal Server Error.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Chyba; zaloguje sa cez `F.error()`. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#500` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error500`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw500()`.\n\nExample: Pri chybe\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw500(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### res.throw503([error])\n\nType: `method`\n\nOdpovie chybovým stavom 503 Service Unavailable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `error` | `Error` | no |  | Chyba; zaloguje sa cez `F.error()`. |\n\nReturns: `Response` Odpoveď.\n\nSpustí stavovú trasu `#503` alebo vstavanú chybovú stránku. Pri požiadavke `HEAD` sa pošle len stav. Emituje aj udalosť `error503`. Použi ju v middleware a obsluhe súborov; v akciách použi `controller.throw503()`.\n\nExample: Pri chybe\n```js\nFILE('/report.pdf', function(req, res) {\n\tmakereport(function(err, filename) {\n\t\tif (err)\n\t\t\tres.throw503(err);\n\t\telse\n\t\t\tres.file(filename);\n\t});\n});\n```\n\n### F.error(err, [name], [uri])\n\nType: `method`\n\nZaloguje chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Chyba. Keď je prázdna, nič sa nestane. |\n| `name` | `String` | no |  | Kde sa stala, vypíše sa spolu s chybou. |\n| `uri` | `String|Object` | no |  | URL požiadavky. |\n\nReturns: `undefined`\n\nVolá `DEF.onError`. Predvolený handler vypíše chybu do konzoly, uloží ju do `F.errors` a emituje udalosť `error`. Bez argumentov vráti callback `function(err)`, ktorý loguje chyby.\n\nExample: Zalogovanie chyby\n```js\nFs.readFile(filename, function(err, data) {\n\tif (err) {\n\t\tF.error(err, 'readconfig');\n\t\treturn;\n\t}\n\t// ...\n});\n```\n\n### ERROR([name])\n\nType: `method`\n\nVráti callback, ktorý zaloguje svoju chybu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no |  | Označenie vypísané spolu s chybou. |\n\nReturns: `Function` `function(err)`.\n\nCallback `function(err)` zavolá `F.error(err, name)`, keď `err` nie je prázdne. Použi ho tam, kde potrebuješ callback, ale nezaujíma ťa výsledok.\n\nExample: Ignorovanie výsledku, zalogovanie chyby\n```js\nF.Fs.unlink(PATH.temp('export.csv'), ERROR('unlink export'));\n```\n\n### DEF.onError = function(err, name, uri)\n\nType: `delegate`\n\nFunkcia, ktorá spracúva každú chybu zalogovanú frameworkom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `err` | `Error|String` | yes |  | Chyba. |\n| `name` | `String` | yes |  | Miesto, kde sa stala. |\n| `uri` | `Object|String` | yes |  | URL požiadavky, ak nejaká je. |\n\n`F.error()`, chyby v akciách aj `throw500()` končia tu. Predvolená funkcia vypíše `ERROR ======= date: name ---> error (url)` a stack, uchová posledných päť chýb v `F.errors` a emituje `ON('error')`. Nahraď ju, ak chceš posielať chyby inam; z vlastnej funkcie môžeš zavolať pôvodnú.\n\nExample: Posielanie chýb do služby\n```js\nvar onerror = DEF.onError;\n\nDEF.onError = function(err, name, uri) {\n\tonerror(err, name, uri);\n\tRESTBuilder.POST('https://logs.example.com/', { error: err + '', name: name }).callback(NOOP);\n};\n```\n\n### F.errors\n\nType: `property`\n\nPosledných päť zalogovaných chýb.\n\nReturns: `Array`\n\nKaždá položka je `{ error, name, url, date }`. Plní ju predvolený `DEF.onError`.\n\nExample: Zobrazenie\n```js\nexports.install = function() {\n\tROUTE('GET /api/errors/', function() {\n\t\tthis.json(F.errors);\n\t});\n};\n```\n\n### SUCCESS([success], [value])\n\nType: `method`\n\nVráti objekt odpovede `{ success, value, error }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `success` | `Boolean|Error|ErrorBuilder|Function` | no | `true` | Výsledok, chyba alebo callback na obalenie. |\n| `value` | `Object` | no |  | Hodnota pre vlastnosť `value`. |\n\nReturns: `Object` `{ success, value, error }`.\n\n`SUCCESS()` dá `{ success: true }`. `SUCCESS(true, value)` pridá `value` (inštancia schémy sa najprv vyčistí). `Error` alebo `ErrorBuilder` s chybami dá `success: false` a text chyby v `error`. S funkciou vráti callback `(err, value)`, ktorý zavolá tvoju funkciu so `SUCCESS(err, value)` ako druhým argumentom. Funkcia vracia jeden zdieľaný objekt, preto ho hneď prečítaj alebo odošli a neuchovávaj ho.\n\nExample: V akcii\n```js\nfunction save() {\n\tvar self = this;\n\tNOSQL('orders').insert(self.body).callback(function(err) {\n\t\tself.json(SUCCESS(err ? false : true));\n\t});\n}\n```\n\nExample: S hodnotou\n```js\nthis.json(SUCCESS(true, { id: UID() }));\n```\n\n### FINISHED(stream, callback)\n\nType: `method`\n\nZavolá funkciu, keď skončí požiadavka, odpoveď alebo stream.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream|Request|Response` | yes |  | Čo sa má sledovať. |\n| `callback` | `Function` | yes |  | Zavolá sa raz na konci. |\n\nReturns: `undefined`\n\nPri požiadavke alebo odpovedi sa callback spustí, keď sa jej socket zatvorí alebo zlyhá, aj keď klient odíde. Pri iných streamoch sa spustí, keď skončia. Na jeden stream môže čakať viac callbackov.\n\nExample: Upratovanie po odpovedi\n```js\nfunction report() {\n\tvar self = this;\n\tvar filename = PATH.temp(UID() + '.pdf');\n\tmakepdf(filename, function() {\n\t\tFINISHED(self.res, () => F.Fs.unlink(filename, NOOP));\n\t\tself.res.file(filename, 'report.pdf');\n\t});\n}\n```\n\n### DESTROY(stream)\n\nType: `method`\n\nZničí stream a zatvorí jeho file deskriptor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `stream` | `Stream` | yes |  | Stream. |\n\nReturns: `Stream` Ten istý stream.\n\nStream na čítanie súboru sa zničí a zatvorí, aj keď sa ešte otvára. Ostatné streamy Node.js sa zničia cez `destroy()`.\n\nExample: Zastavenie čítania\n```js\nvar stream = F.Fs.createReadStream(filename);\nFINISHED(this.res, () => DESTROY(stream));\nstream.pipe(this.res);\n```\n\n### EMPTYCONTROLLER\n\nType: `property`\n\nKontrolér bez požiadavky.\n\nReturns: `Controller`\n\nFramework ho používa pre `VIEW()` a `MAIL()`, kde nie je žiadna HTTP požiadavka. Jeho `req` má prázdnu URL, query, telo a súbory. Môžeš ho použiť na volanie pomocných metód kontroléra mimo požiadavky; neodpovedaj ním.\n\nExample: URL zo sitemapy mimo požiadavky\n```js\nvar url = EMPTYCONTROLLER.sitemap_url('detail', 'book');\n```\n","entries":[{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, options, [middleware])","since":"","deprecated":false},{"type":"type","name":"HTTP options","signature":"{ port, ip, unixsocket, unixsocket777, config, https, middleware, id }","since":"","deprecated":false},{"type":"property","name":"F.server","signature":"F.server","since":"","deprecated":false},{"type":"property","name":"F.port","signature":"F.port","since":"","deprecated":false},{"type":"property","name":"F.ip","signature":"F.ip","since":"","deprecated":false},{"type":"config","name":"allow_performance","signature":"allow_performance : true","since":"","deprecated":false},{"type":"method","name":"CORS()","signature":"CORS([url], [flags], [credentials])","since":"","deprecated":false},{"type":"config","name":"default_cors_maxage","signature":"default_cors_maxage : 120","since":"","deprecated":false},{"type":"method","name":"PROXY()","signature":"PROXY(url, target, [copypath], [before], [after], [check], [timeout])","since":"","deprecated":false},{"type":"method","name":"REDIRECT()","signature":"REDIRECT(from, to, [path], [permanent])","since":"","deprecated":false},{"type":"method","name":"res.redirect()","signature":"res.redirect(url, [permanent])","since":"","deprecated":false},{"type":"method","name":"ROUTE('#404')","signature":"ROUTE('#code', action)","since":"","deprecated":false},{"type":"config","name":"default_errorbuilder_forxhr","signature":"default_errorbuilder_forxhr : true","since":"","deprecated":false},{"type":"method","name":"res.throw400()","signature":"res.throw400([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw401()","signature":"res.throw401([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw403()","signature":"res.throw403([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw404()","signature":"res.throw404([problem])","since":"","deprecated":false},{"type":"method","name":"res.throw500()","signature":"res.throw500([error])","since":"","deprecated":false},{"type":"method","name":"res.throw503()","signature":"res.throw503([error])","since":"","deprecated":false},{"type":"method","name":"F.error()","signature":"F.error(err, [name], [uri])","since":"","deprecated":false},{"type":"method","name":"ERROR()","signature":"ERROR([name])","since":"","deprecated":false},{"type":"delegate","name":"DEF.onError","signature":"DEF.onError = function(err, name, uri)","since":"","deprecated":false},{"type":"property","name":"F.errors","signature":"F.errors","since":"","deprecated":false},{"type":"method","name":"SUCCESS()","signature":"SUCCESS([success], [value])","since":"","deprecated":false},{"type":"method","name":"FINISHED()","signature":"FINISHED(stream, callback)","since":"","deprecated":false},{"type":"method","name":"DESTROY()","signature":"DESTROY(stream)","since":"","deprecated":false},{"type":"property","name":"EMPTYCONTROLLER","signature":"EMPTYCONTROLLER","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:15.818Z"}
{"id":"Jafjrg3zX60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Sitemap","summary":"The sitemap file, SITEMAP(), the F.sitemap functions, the controller methods and @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> The sitemap file, SITEMAP(), the F.sitemap functions, the controller methods and @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nThe file that describes the pages of a website.\n\nThe file `sitemap` in the root of the application is loaded at start. Each line is an item: the ID, ` :` (or a tab and `:`), the title, `-->`, the URL and optionally `-->` and the ID of the parent. Lines that start with `#` or `// ` are comments. A title or URL in `@(...)` is translated with the resources. `{0}`…`{5}` are placeholders filled by `sitemap_url()`, `sitemap_name()` or `sitemap_change()`. A URL that ends with `*` covers all paths below it.\n\nExample: A shop\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDeclares a route by a sitemap ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The sitemap ID with `#`, optionally with an HTTP method before it. |\n| `action` | `Function|String` | no |  | An action or a view name. |\n| `flags` | `Array` | no |  | Route flags. |\n\nReturns: `undefined`\n\nThe URL comes from the sitemap item. A path after the ID is appended (`#detail/{id}/`), and a wildcard item gets `*`. Without an action, the view with the name of the ID is rendered (`index` for the URL `/`); with a string, that view. In both cases the breadcrumb and the page title are set from the sitemap. In your own action call `this.sitemap()` to do it. An item with a localized URL creates a route for each language. An unknown ID throws `Sitemap item \"id\" not found.`\n\nExample: Pages from the sitemap\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nReturns the breadcrumb of a sitemap item, or the item itself.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The sitemap ID. |\n| `first` | `Boolean` | no | `false` | Returns only the item. |\n| `language` | `String` | no |  | Translates localized titles and URLs. |\n\nReturns: `Array|Object` The breadcrumb, or one item.\n\nWithout `first`, returns the items from the root to `id`. Each item has `id`, `name`, `url`, `sitemap` (the requested ID), `index` (`0` for the requested item), `first` (a root item), `last` and `selected` (the requested item), `wildcard`, `formatname` and `formaturl` (the text has placeholders). With `first: true`, returns only the item; an unknown ID gives an item with an empty `url`. A string as the second argument is the language. Results are cached. Alias: `F.sitemap()`.\n\nExample: Breadcrumb\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: One URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nReturns the sitemap items with one parent, for a menu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | The ID of the parent. |\n| `language` | `String` | no |  | Translates localized titles and URLs. |\n\nReturns: `Array`\n\nWithout `parent`, returns the top-level items. Each item has `name`, `url`, `wildcard`, `formatname` and `formaturl`. The list is sorted by name and cached.\n\nExample: Main menu\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nAdds items to the sitemap from code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | One line or an array of lines. |\n\nReturns: `undefined`\n\nEach line has the format of the sitemap file. Existing IDs are replaced. Add items before you declare routes that use them.\n\nExample: From a module\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nLoads the breadcrumb of the page into the controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | A sitemap ID, or your own breadcrumb. |\n\nReturns: `Array` The breadcrumb.\n\nWith an ID, copies the breadcrumb `SITEMAP(id)` into the repository, where views read it as `sitemap`, and sets the title to the name of the last item when there is no title yet. Without an argument, returns the current breadcrumb and loads the one of the route's sitemap ID on the first call. With an array, uses that array as the breadcrumb and returns the controller.\n\nExample: In an action\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nThe sitemap ID of the current page.\n\nReturns: `String`\n\nThe ID set by `controller.sitemap(id)`, otherwise the ID of the route (`ROUTE('#id')`), or an empty string.\n\nExample: Read it\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nReturns the sitemap items with one parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | The ID of the parent. |\n| `language` | `String` | no | `controller.language` | The language. |\n\nReturns: `Array`\n\nCalls `F.sitemap_navigation()`. The default parent is the current sitemap ID, so it lists the sub-pages of the current page. The default language is the language of the request.\n\nExample: In a view\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nReturns the URL of a sitemap item.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | The sitemap ID. |\n| `a` | `Object` | no |  | The value for `{0}`, then `b` for `{1}` and so on. |\n\nReturns: `String`\n\nThe URL is translated to the language of the request and its placeholders `{0}`…`{5}` are filled with the other arguments. The default ID is the current one. Returns an empty string for an unknown ID. Also available in views as `@{sitemap_url(...)}`.\n\nExample: In a view\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nReturns the URL of a sitemap item in another language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | The language. |\n| `id` | `String` | yes |  | The sitemap ID. Empty means the current one. |\n| `a` | `Object` | no |  | The value for `{0}` and so on. |\n\nReturns: `String`\n\nWorks as `sitemap_url()` with the language as the first argument, for example for links to other language versions.\n\nExample: Language switch\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nReturns the title of a sitemap item.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | The sitemap ID. |\n| `a` | `Object` | no |  | The value for `{0}`, then `b` for `{1}` and so on. |\n\nReturns: `String`\n\nThe title is translated to the language of the request and its placeholders `{0}`…`{5}` are filled with the other arguments. The default ID is the current one. Returns an empty string for an unknown ID. Also available in views as `@{sitemap_name(...)}`.\n\nExample: In a view\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nReturns the title of a sitemap item in another language.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | The language. |\n| `id` | `String` | yes |  | The sitemap ID. Empty means the current one. |\n| `a` | `Object` | no |  | The value for `{0}` and so on. |\n\nReturns: `String`\n\nWorks as `sitemap_name()` with the language as the first argument, for example for links to other language versions.\n\nExample: Language switch\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nChanges one property of an item in the current breadcrumb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the item in the breadcrumb. |\n| `property` | `String` | yes |  | Usually `name` or `url`. |\n| `value` | `Object|Function` | yes |  | The new value, the first placeholder value, or a function. |\n| `b` | `Object` | no |  | Values for `{1}` and so on. |\n\nReturns: `Array` The breadcrumb.\n\nWorks on a copy for this request only. For `name` and `url` with placeholders, `value` and the next arguments fill `{0}`…`{5}`; otherwise the property gets `value`. A function receives the current value and returns the new one. When the changed name was the page title, the title changes too. In a view: `@{sitemap_change(...)}`.\n\nExample: Product detail\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nReplaces the title and the URL of an item in the current breadcrumb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The ID of the item. |\n| `title` | `String|Function` | yes |  | The new title. |\n| `url` | `String|Function` | yes |  | The new URL. |\n\nReturns: `Array` The breadcrumb.\n\nEach of `title` and `url` can be a string or a function that receives the current value. A string fills the placeholder `{0}` when the item has one. Empty values are not changed. The page title follows the change. In a view: `@{sitemap_replace(...)}`.\n\nExample: Both at once\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nInserts an item into the current breadcrumb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | The ID of the item after which the new one goes. |\n| `name` | `String` | yes |  | The title. |\n| `url` | `String` | yes |  | The URL. |\n\nReturns: `Array` The breadcrumb.\n\nThe new item is placed after the item with the ID `parent`. Nothing changes when `parent` is not in the breadcrumb. In a view: `@{sitemap_add(...)}`.\n\nExample: A category level\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nThe breadcrumb in a view.\n\n`sitemap` in a view is the breadcrumb loaded by `controller.sitemap()` or by an ID route. `@{sitemap('id')}` loads another one from the view and prints nothing. The controller methods `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` and `sitemap_add()` are available with the same names. See [Views](../../guides/views/).\n\nExample: Breadcrumb in a layout\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jafjrg3zX60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Sitemap","summary":"Die Datei sitemap, SITEMAP(), die Funktionen F.sitemap, die Methoden des Controllers und @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> Die Datei sitemap, SITEMAP(), die Funktionen F.sitemap, die Methoden des Controllers und @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nDie Datei, die die Seiten einer Website beschreibt.\n\nDie Datei `sitemap` im Wurzelverzeichnis der Anwendung wird beim Start geladen. Jede Zeile ist ein Eintrag: die ID, ` :` (oder ein Tab und `:`), der Titel, `-->`, die URL und optional `-->` und die ID des Elternelements. Zeilen, die mit `#` oder `// ` beginnen, sind Kommentare. Ein Titel oder eine URL in `@(...)` wird mit den Ressourcen übersetzt. `{0}`…`{5}` sind Platzhalter, die von `sitemap_url()`, `sitemap_name()` oder `sitemap_change()` gefüllt werden. Eine URL, die mit `*` endet, deckt alle Pfade darunter ab.\n\nExample: Ein Shop\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDeklariert eine Route über eine Sitemap-ID.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die Sitemap-ID mit `#`, optional mit einer HTTP-Methode davor. |\n| `action` | `Function|String` | no |  | Eine Action oder ein View-Name. |\n| `flags` | `Array` | no |  | Routen-Flags. |\n\nReturns: `undefined`\n\nDie URL kommt aus dem Sitemap-Eintrag. Ein Pfad nach der ID wird angehängt (`#detail/{id}/`), und ein Wildcard-Eintrag bekommt `*`. Ohne Action wird die View mit dem Namen der ID gerendert (`index` für die URL `/`); mit einem String diese View. In beiden Fällen werden der Breadcrumb und der Seitentitel aus der Sitemap gesetzt. In deiner eigenen Action rufst du dafür `this.sitemap()` auf. Ein Eintrag mit einer lokalisierten URL erzeugt eine Route für jede Sprache. Eine unbekannte ID wirft `Sitemap item \"id\" not found.`\n\nExample: Seiten aus der Sitemap\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nGibt den Breadcrumb eines Sitemap-Eintrags oder den Eintrag selbst zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die Sitemap-ID. |\n| `first` | `Boolean` | no | `false` | Gibt nur den Eintrag zurück. |\n| `language` | `String` | no |  | Übersetzt lokalisierte Titel und URLs. |\n\nReturns: `Array|Object` Der Breadcrumb oder ein einzelner Eintrag.\n\nOhne `first` gibt es die Einträge von der Wurzel bis `id` zurück. Jeder Eintrag hat `id`, `name`, `url`, `sitemap` (die angefragte ID), `index` (`0` für den angefragten Eintrag), `first` (ein Wurzeleintrag), `last` und `selected` (der angefragte Eintrag), `wildcard`, `formatname` und `formaturl` (der Text hat Platzhalter). Mit `first: true` gibt es nur den Eintrag zurück; eine unbekannte ID ergibt einen Eintrag mit leerer `url`. Ein String als zweites Argument ist die Sprache. Ergebnisse werden zwischengespeichert. Alias: `F.sitemap()`.\n\nExample: Breadcrumb\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: Eine URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nGibt die Sitemap-Einträge mit einem bestimmten Elternelement zurück, für ein Menü.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | Die ID des Elternelements. |\n| `language` | `String` | no |  | Übersetzt lokalisierte Titel und URLs. |\n\nReturns: `Array`\n\nOhne `parent` gibt es die Einträge der obersten Ebene zurück. Jeder Eintrag hat `name`, `url`, `wildcard`, `formatname` und `formaturl`. Die Liste wird nach Namen sortiert und zwischengespeichert.\n\nExample: Hauptmenü\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nFügt der Sitemap Einträge aus Code hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | Eine Zeile oder ein Array von Zeilen. |\n\nReturns: `undefined`\n\nJede Zeile hat das Format der Sitemap-Datei. Vorhandene IDs werden ersetzt. Füge Einträge hinzu, bevor du Routen deklarierst, die sie verwenden.\n\nExample: Aus einem Modul\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nLädt den Breadcrumb der Seite in den Controller.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Eine Sitemap-ID oder dein eigener Breadcrumb. |\n\nReturns: `Array` Der Breadcrumb.\n\nMit einer ID kopiert es den Breadcrumb `SITEMAP(id)` in das Repository, wo Views ihn als `sitemap` lesen, und setzt den Titel auf den Namen des letzten Eintrags, wenn es noch keinen Titel gibt. Ohne Argument gibt es den aktuellen Breadcrumb zurück und lädt beim ersten Aufruf den der Sitemap-ID der Route. Mit einem Array verwendet es dieses Array als Breadcrumb und gibt den Controller zurück.\n\nExample: In einer Action\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nDie Sitemap-ID der aktuellen Seite.\n\nReturns: `String`\n\nDie von `controller.sitemap(id)` gesetzte ID, sonst die ID der Route (`ROUTE('#id')`) oder ein leerer String.\n\nExample: Auslesen\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nGibt die Sitemap-Einträge mit einem bestimmten Elternelement zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | Die ID des Elternelements. |\n| `language` | `String` | no | `controller.language` | Die Sprache. |\n\nReturns: `Array`\n\nRuft `F.sitemap_navigation()` auf. Das Standard-Elternelement ist die aktuelle Sitemap-ID, also listet es die Unterseiten der aktuellen Seite auf. Die Standardsprache ist die Sprache des Requests.\n\nExample: In einer View\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nGibt die URL eines Sitemap-Eintrags zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | Die Sitemap-ID. |\n| `a` | `Object` | no |  | Der Wert für `{0}`, dann `b` für `{1}` und so weiter. |\n\nReturns: `String`\n\nDie URL wird in die Sprache des Requests übersetzt, und ihre Platzhalter `{0}`…`{5}` werden mit den übrigen Argumenten gefüllt. Die Standard-ID ist die aktuelle. Gibt für eine unbekannte ID einen leeren String zurück. In Views auch als `@{sitemap_url(...)}` verfügbar.\n\nExample: In einer View\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nGibt die URL eines Sitemap-Eintrags in einer anderen Sprache zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Die Sprache. |\n| `id` | `String` | yes |  | Die Sitemap-ID. Leer bedeutet die aktuelle. |\n| `a` | `Object` | no |  | Der Wert für `{0}` und so weiter. |\n\nReturns: `String`\n\nFunktioniert wie `sitemap_url()` mit der Sprache als erstem Argument, zum Beispiel für Links zu anderen Sprachversionen.\n\nExample: Sprachumschalter\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nGibt den Titel eines Sitemap-Eintrags zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | Die Sitemap-ID. |\n| `a` | `Object` | no |  | Der Wert für `{0}`, dann `b` für `{1}` und so weiter. |\n\nReturns: `String`\n\nDer Titel wird in die Sprache des Requests übersetzt, und seine Platzhalter `{0}`…`{5}` werden mit den übrigen Argumenten gefüllt. Die Standard-ID ist die aktuelle. Gibt für eine unbekannte ID einen leeren String zurück. In Views auch als `@{sitemap_name(...)}` verfügbar.\n\nExample: In einer View\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nGibt den Titel eines Sitemap-Eintrags in einer anderen Sprache zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Die Sprache. |\n| `id` | `String` | yes |  | Die Sitemap-ID. Leer bedeutet die aktuelle. |\n| `a` | `Object` | no |  | Der Wert für `{0}` und so weiter. |\n\nReturns: `String`\n\nFunktioniert wie `sitemap_name()` mit der Sprache als erstem Argument, zum Beispiel für Links zu anderen Sprachversionen.\n\nExample: Sprachumschalter\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nÄndert eine Eigenschaft eines Eintrags im aktuellen Breadcrumb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Eintrags im Breadcrumb. |\n| `property` | `String` | yes |  | Meist `name` oder `url`. |\n| `value` | `Object|Function` | yes |  | Der neue Wert, der erste Platzhalterwert oder eine Funktion. |\n| `b` | `Object` | no |  | Werte für `{1}` und so weiter. |\n\nReturns: `Array` Der Breadcrumb.\n\nArbeitet auf einer Kopie, nur für diesen Request. Bei `name` und `url` mit Platzhaltern füllen `value` und die folgenden Argumente `{0}`…`{5}`; sonst bekommt die Eigenschaft `value`. Eine Funktion erhält den aktuellen Wert und gibt den neuen zurück. War der geänderte Name der Seitentitel, ändert sich auch der Titel. In einer View: `@{sitemap_change(...)}`.\n\nExample: Produktdetail\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nErsetzt den Titel und die URL eines Eintrags im aktuellen Breadcrumb.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Eintrags. |\n| `title` | `String|Function` | yes |  | Der neue Titel. |\n| `url` | `String|Function` | yes |  | Die neue URL. |\n\nReturns: `Array` Der Breadcrumb.\n\n`title` und `url` können jeweils ein String oder eine Funktion sein, die den aktuellen Wert erhält. Ein String füllt den Platzhalter `{0}`, wenn der Eintrag einen hat. Leere Werte werden nicht geändert. Der Seitentitel folgt der Änderung. In einer View: `@{sitemap_replace(...)}`.\n\nExample: Beides auf einmal\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nFügt einen Eintrag in den aktuellen Breadcrumb ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | Die ID des Eintrags, nach dem der neue eingefügt wird. |\n| `name` | `String` | yes |  | Der Titel. |\n| `url` | `String` | yes |  | Die URL. |\n\nReturns: `Array` Der Breadcrumb.\n\nDer neue Eintrag wird nach dem Eintrag mit der ID `parent` platziert. Nichts ändert sich, wenn `parent` nicht im Breadcrumb ist. In einer View: `@{sitemap_add(...)}`.\n\nExample: Eine Kategorieebene\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nDer Breadcrumb in einer View.\n\n`sitemap` in einer View ist der Breadcrumb, der von `controller.sitemap()` oder von einer ID-Route geladen wurde. `@{sitemap('id')}` lädt einen anderen aus der View und gibt nichts aus. Die Controller-Methoden `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` und `sitemap_add()` sind unter denselben Namen verfügbar. Siehe [Views](../../guides/views/).\n\nExample: Breadcrumb in einem Layout\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jafjrg3zX60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Sitemap","summary":"El archivo sitemap, SITEMAP(), las funciones F.sitemap, los métodos del controlador y @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> El archivo sitemap, SITEMAP(), las funciones F.sitemap, los métodos del controlador y @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nEl archivo que describe las páginas de un sitio web.\n\nEl archivo `sitemap` de la raíz de la aplicación se carga al iniciar. Cada línea es un elemento: el ID, ` :` (o un tabulador y `:`), el título, `-->`, la URL y, opcionalmente, `-->` y el ID del padre. Las líneas que empiezan por `#` o `// ` son comentarios. Un título o una URL entre `@(...)` se traduce con los recursos. `{0}`…`{5}` son marcadores que rellenan `sitemap_url()`, `sitemap_name()` o `sitemap_change()`. Una URL que termina en `*` cubre todas las rutas por debajo.\n\nExample: Una tienda\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDeclara una ruta por un ID del sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del sitemap con `#`, opcionalmente precedido por un método HTTP. |\n| `action` | `Function|String` | no |  | Una acción o un nombre de vista. |\n| `flags` | `Array` | no |  | Flags de la ruta. |\n\nReturns: `undefined`\n\nLa URL viene del elemento del sitemap. Una ruta después del ID se añade al final (`#detail/{id}/`), y un elemento comodín recibe `*`. Sin acción, se renderiza la vista con el nombre del ID (`index` para la URL `/`); con una cadena, esa vista. En ambos casos el breadcrumb y el título de la página se definen a partir del sitemap. En tu propia acción, llama a `this.sitemap()` para hacerlo. Un elemento con una URL localizada crea una ruta para cada idioma. Un ID desconocido lanza `Sitemap item \"id\" not found.`\n\nExample: Páginas desde el sitemap\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nDevuelve el breadcrumb de un elemento del sitemap, o el propio elemento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del sitemap. |\n| `first` | `Boolean` | no | `false` | Devuelve solo el elemento. |\n| `language` | `String` | no |  | Traduce los títulos y las URLs localizados. |\n\nReturns: `Array|Object` El breadcrumb, o un elemento.\n\nSin `first`, devuelve los elementos desde la raíz hasta `id`. Cada elemento tiene `id`, `name`, `url`, `sitemap` (el ID pedido), `index` (`0` para el elemento pedido), `first` (un elemento raíz), `last` y `selected` (el elemento pedido), `wildcard`, `formatname` y `formaturl` (el texto tiene marcadores). Con `first: true`, devuelve solo el elemento; un ID desconocido da un elemento con `url` vacía. Una cadena como segundo argumento es el idioma. Los resultados se guardan en caché. Alias: `F.sitemap()`.\n\nExample: Breadcrumb\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: Una URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nDevuelve los elementos del sitemap con un mismo padre, para un menú.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | El ID del padre. |\n| `language` | `String` | no |  | Traduce los títulos y las URLs localizados. |\n\nReturns: `Array`\n\nSin `parent`, devuelve los elementos de nivel superior. Cada elemento tiene `name`, `url`, `wildcard`, `formatname` y `formaturl`. La lista se ordena por nombre y se guarda en caché.\n\nExample: Menú principal\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nAñade elementos al sitemap desde el código.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | Una línea o un array de líneas. |\n\nReturns: `undefined`\n\nCada línea tiene el formato del archivo sitemap. Los IDs existentes se sustituyen. Añade los elementos antes de declarar las rutas que los usan.\n\nExample: Desde un módulo\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nCarga en el controlador el breadcrumb de la página.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un ID del sitemap, o tu propio breadcrumb. |\n\nReturns: `Array` El breadcrumb.\n\nCon un ID, copia el breadcrumb `SITEMAP(id)` en el repositorio, donde las vistas lo leen como `sitemap`, y establece el título con el nombre del último elemento cuando aún no hay título. Sin argumento, devuelve el breadcrumb actual y carga el del ID del sitemap de la ruta en la primera llamada. Con un array, usa ese array como breadcrumb y devuelve el controlador.\n\nExample: En una acción\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nEl ID del sitemap de la página actual.\n\nReturns: `String`\n\nEl ID definido por `controller.sitemap(id)`; si no, el ID de la ruta (`ROUTE('#id')`), o una cadena vacía.\n\nExample: Leerlo\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nDevuelve los elementos del sitemap con un mismo padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | El ID del padre. |\n| `language` | `String` | no | `controller.language` | El idioma. |\n\nReturns: `Array`\n\nLlama a `F.sitemap_navigation()`. El padre por defecto es el ID del sitemap actual, así que lista las subpáginas de la página actual. El idioma por defecto es el idioma de la petición.\n\nExample: En una vista\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nDevuelve la URL de un elemento del sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | El ID del sitemap. |\n| `a` | `Object` | no |  | El valor para `{0}`; después `b` para `{1}`, y así sucesivamente. |\n\nReturns: `String`\n\nLa URL se traduce al idioma de la petición y sus marcadores `{0}`…`{5}` se rellenan con los demás argumentos. El ID por defecto es el actual. Devuelve una cadena vacía para un ID desconocido. También está disponible en las vistas como `@{sitemap_url(...)}`.\n\nExample: En una vista\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nDevuelve la URL de un elemento del sitemap en otro idioma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | El idioma. |\n| `id` | `String` | yes |  | El ID del sitemap. Vacío significa el actual. |\n| `a` | `Object` | no |  | El valor para `{0}`, y así sucesivamente. |\n\nReturns: `String`\n\nFunciona como `sitemap_url()` con el idioma como primer argumento, por ejemplo para enlaces a otras versiones de idioma.\n\nExample: Cambio de idioma\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nDevuelve el título de un elemento del sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | El ID del sitemap. |\n| `a` | `Object` | no |  | El valor para `{0}`; después `b` para `{1}`, y así sucesivamente. |\n\nReturns: `String`\n\nEl título se traduce al idioma de la petición y sus marcadores `{0}`…`{5}` se rellenan con los demás argumentos. El ID por defecto es el actual. Devuelve una cadena vacía para un ID desconocido. También está disponible en las vistas como `@{sitemap_name(...)}`.\n\nExample: En una vista\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nDevuelve el título de un elemento del sitemap en otro idioma.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | El idioma. |\n| `id` | `String` | yes |  | El ID del sitemap. Vacío significa el actual. |\n| `a` | `Object` | no |  | El valor para `{0}`, y así sucesivamente. |\n\nReturns: `String`\n\nFunciona como `sitemap_name()` con el idioma como primer argumento, por ejemplo para enlaces a otras versiones de idioma.\n\nExample: Cambio de idioma\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nCambia una propiedad de un elemento del breadcrumb actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del elemento en el breadcrumb. |\n| `property` | `String` | yes |  | Normalmente `name` o `url`. |\n| `value` | `Object|Function` | yes |  | El nuevo valor, el valor del primer marcador o una función. |\n| `b` | `Object` | no |  | Valores para `{1}`, y así sucesivamente. |\n\nReturns: `Array` El breadcrumb.\n\nTrabaja sobre una copia solo para esta petición. Para `name` y `url` con marcadores, `value` y los argumentos siguientes rellenan `{0}`…`{5}`; si no, la propiedad recibe `value`. Una función recibe el valor actual y devuelve el nuevo. Cuando el nombre cambiado era el título de la página, el título también cambia. En una vista: `@{sitemap_change(...)}`.\n\nExample: Detalle de producto\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nSustituye el título y la URL de un elemento del breadcrumb actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El ID del elemento. |\n| `title` | `String|Function` | yes |  | El nuevo título. |\n| `url` | `String|Function` | yes |  | La nueva URL. |\n\nReturns: `Array` El breadcrumb.\n\nTanto `title` como `url` pueden ser una cadena o una función que recibe el valor actual. Una cadena rellena el marcador `{0}` cuando el elemento lo tiene. Los valores vacíos no se cambian. El título de la página sigue el cambio. En una vista: `@{sitemap_replace(...)}`.\n\nExample: Ambos a la vez\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nInserta un elemento en el breadcrumb actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | El ID del elemento tras el que va el nuevo. |\n| `name` | `String` | yes |  | El título. |\n| `url` | `String` | yes |  | La URL. |\n\nReturns: `Array` El breadcrumb.\n\nEl nuevo elemento se coloca después del elemento con el ID `parent`. No cambia nada cuando `parent` no está en el breadcrumb. En una vista: `@{sitemap_add(...)}`.\n\nExample: Un nivel de categoría\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nEl breadcrumb en una vista.\n\n`sitemap` en una vista es el breadcrumb cargado por `controller.sitemap()` o por una ruta con ID. `@{sitemap('id')}` carga otro desde la vista y no imprime nada. Los métodos del controlador `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` y `sitemap_add()` están disponibles con los mismos nombres. Consulta [Vistas](../../guides/views/).\n\nExample: Breadcrumb en una plantilla (layout)\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jafjrg3zX60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Sitemap","summary":"Le fichier sitemap, SITEMAP(), les fonctions F.sitemap, les méthodes du contrôleur et @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> Le fichier sitemap, SITEMAP(), les fonctions F.sitemap, les méthodes du contrôleur et @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nLe fichier qui décrit les pages d'un site web.\n\nLe fichier `sitemap` à la racine de l'application est chargé au démarrage. Chaque ligne est un élément : l'ID, ` :` (ou une tabulation et `:`), le titre, `-->`, l'URL et éventuellement `-->` et l'ID du parent. Les lignes qui commencent par `#` ou `// ` sont des commentaires. Un titre ou une URL dans `@(...)` est traduit avec les ressources. `{0}`…`{5}` sont des placeholders remplis par `sitemap_url()`, `sitemap_name()` ou `sitemap_change()`. Une URL qui se termine par `*` couvre tous les chemins en dessous.\n\nExample: Une boutique\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDéclare une route par un ID du sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du sitemap avec `#`, éventuellement précédé d'une méthode HTTP. |\n| `action` | `Function|String` | no |  | Une action ou un nom de vue. |\n| `flags` | `Array` | no |  | Flags de route. |\n\nReturns: `undefined`\n\nL'URL provient de l'élément du sitemap. Un chemin après l'ID est ajouté (`#detail/{id}/`), et un élément joker reçoit `*`. Sans action, la vue portant le nom de l'ID est rendue (`index` pour l'URL `/`) ; avec une chaîne, cette vue. Dans les deux cas, le fil d'Ariane et le titre de la page sont définis à partir du sitemap. Dans ta propre action, appelle `this.sitemap()` pour le faire. Un élément avec une URL localisée crée une route pour chaque langue. Un ID inconnu lève `Sitemap item \"id\" not found.`\n\nExample: Pages issues du sitemap\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nRenvoie le fil d'Ariane d'un élément du sitemap, ou l'élément lui-même.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID du sitemap. |\n| `first` | `Boolean` | no | `false` | Renvoie uniquement l'élément. |\n| `language` | `String` | no |  | Traduit les titres et URL localisés. |\n\nReturns: `Array|Object` Le fil d'Ariane, ou un seul élément.\n\nSans `first`, renvoie les éléments de la racine jusqu'à `id`. Chaque élément a `id`, `name`, `url`, `sitemap` (l'ID demandé), `index` (`0` pour l'élément demandé), `first` (un élément racine), `last` et `selected` (l'élément demandé), `wildcard`, `formatname` et `formaturl` (le texte contient des placeholders). Avec `first: true`, renvoie uniquement l'élément ; un ID inconnu donne un élément avec une `url` vide. Une chaîne en deuxième argument est la langue. Les résultats sont mis en cache. Alias : `F.sitemap()`.\n\nExample: Fil d'Ariane\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: Une seule URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nRenvoie les éléments du sitemap ayant un même parent, pour un menu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | L'ID du parent. |\n| `language` | `String` | no |  | Traduit les titres et URL localisés. |\n\nReturns: `Array`\n\nSans `parent`, renvoie les éléments de premier niveau. Chaque élément a `name`, `url`, `wildcard`, `formatname` et `formaturl`. La liste est triée par nom et mise en cache.\n\nExample: Menu principal\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nAjoute des éléments au sitemap depuis le code.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | Une ligne ou un tableau de lignes. |\n\nReturns: `undefined`\n\nChaque ligne a le format du fichier sitemap. Les ID existants sont remplacés. Ajoute les éléments avant de déclarer les routes qui les utilisent.\n\nExample: Depuis un module\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nCharge le fil d'Ariane de la page dans le contrôleur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un ID du sitemap, ou ton propre fil d'Ariane. |\n\nReturns: `Array` Le fil d'Ariane.\n\nAvec un ID, copie le fil d'Ariane `SITEMAP(id)` dans le repository, où les vues le lisent sous le nom `sitemap`, et définit le titre avec le nom du dernier élément lorsqu'il n'y a pas encore de titre. Sans argument, renvoie le fil d'Ariane courant et charge, au premier appel, celui de l'ID de sitemap de la route. Avec un tableau, utilise ce tableau comme fil d'Ariane et renvoie le contrôleur.\n\nExample: Dans une action\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nL'ID du sitemap de la page courante.\n\nReturns: `String`\n\nL'ID défini par `controller.sitemap(id)`, sinon l'ID de la route (`ROUTE('#id')`), ou une chaîne vide.\n\nExample: Le lire\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nRenvoie les éléments du sitemap ayant un même parent.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | L'ID du parent. |\n| `language` | `String` | no | `controller.language` | La langue. |\n\nReturns: `Array`\n\nAppelle `F.sitemap_navigation()`. Le parent par défaut est l'ID de sitemap courant, elle liste donc les sous-pages de la page courante. La langue par défaut est celle de la requête.\n\nExample: Dans une vue\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRenvoie l'URL d'un élément du sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | L'ID du sitemap. |\n| `a` | `Object` | no |  | La valeur pour `{0}`, puis `b` pour `{1}` et ainsi de suite. |\n\nReturns: `String`\n\nL'URL est traduite dans la langue de la requête et ses placeholders `{0}`…`{5}` sont remplis avec les autres arguments. L'ID par défaut est l'ID courant. Renvoie une chaîne vide pour un ID inconnu. Également disponible dans les vues sous la forme `@{sitemap_url(...)}`.\n\nExample: Dans une vue\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRenvoie l'URL d'un élément du sitemap dans une autre langue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | La langue. |\n| `id` | `String` | yes |  | L'ID du sitemap. Vide signifie l'ID courant. |\n| `a` | `Object` | no |  | La valeur pour `{0}` et ainsi de suite. |\n\nReturns: `String`\n\nFonctionne comme `sitemap_url()` avec la langue en premier argument, par exemple pour les liens vers d'autres versions linguistiques.\n\nExample: Sélecteur de langue\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRenvoie le titre d'un élément du sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | L'ID du sitemap. |\n| `a` | `Object` | no |  | La valeur pour `{0}`, puis `b` pour `{1}` et ainsi de suite. |\n\nReturns: `String`\n\nLe titre est traduit dans la langue de la requête et ses placeholders `{0}`…`{5}` sont remplis avec les autres arguments. L'ID par défaut est l'ID courant. Renvoie une chaîne vide pour un ID inconnu. Également disponible dans les vues sous la forme `@{sitemap_name(...)}`.\n\nExample: Dans une vue\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRenvoie le titre d'un élément du sitemap dans une autre langue.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | La langue. |\n| `id` | `String` | yes |  | L'ID du sitemap. Vide signifie l'ID courant. |\n| `a` | `Object` | no |  | La valeur pour `{0}` et ainsi de suite. |\n\nReturns: `String`\n\nFonctionne comme `sitemap_name()` avec la langue en premier argument, par exemple pour les liens vers d'autres versions linguistiques.\n\nExample: Sélecteur de langue\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nModifie une propriété d'un élément du fil d'Ariane courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID de l'élément dans le fil d'Ariane. |\n| `property` | `String` | yes |  | Généralement `name` ou `url`. |\n| `value` | `Object|Function` | yes |  | La nouvelle valeur, la première valeur de placeholder, ou une fonction. |\n| `b` | `Object` | no |  | Valeurs pour `{1}` et ainsi de suite. |\n\nReturns: `Array` Le fil d'Ariane.\n\nTravaille sur une copie, pour cette requête uniquement. Pour `name` et `url` avec des placeholders, `value` et les arguments suivants remplissent `{0}`…`{5}` ; sinon la propriété reçoit `value`. Une fonction reçoit la valeur courante et renvoie la nouvelle. Lorsque le nom modifié était le titre de la page, le titre change aussi. Dans une vue : `@{sitemap_change(...)}`.\n\nExample: Détail d'un produit\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nRemplace le titre et l'URL d'un élément du fil d'Ariane courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID de l'élément. |\n| `title` | `String|Function` | yes |  | Le nouveau titre. |\n| `url` | `String|Function` | yes |  | La nouvelle URL. |\n\nReturns: `Array` Le fil d'Ariane.\n\n`title` et `url` peuvent chacun être une chaîne ou une fonction qui reçoit la valeur courante. Une chaîne remplit le placeholder `{0}` lorsque l'élément en a un. Les valeurs vides ne sont pas modifiées. Le titre de la page suit la modification. Dans une vue : `@{sitemap_replace(...)}`.\n\nExample: Les deux à la fois\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nInsère un élément dans le fil d'Ariane courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | L'ID de l'élément après lequel se place le nouveau. |\n| `name` | `String` | yes |  | Le titre. |\n| `url` | `String` | yes |  | L'URL. |\n\nReturns: `Array` Le fil d'Ariane.\n\nLe nouvel élément est placé après l'élément d'ID `parent`. Rien ne change lorsque `parent` n'est pas dans le fil d'Ariane. Dans une vue : `@{sitemap_add(...)}`.\n\nExample: Un niveau de catégorie\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nLe fil d'Ariane dans une vue.\n\nDans une vue, `sitemap` est le fil d'Ariane chargé par `controller.sitemap()` ou par une route à ID. `@{sitemap('id')}` en charge un autre depuis la vue et n'affiche rien. Les méthodes de contrôleur `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` et `sitemap_add()` sont disponibles sous les mêmes noms. Voir [Vues](../../guides/views/).\n\nExample: Fil d'Ariane dans un layout\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jafjrg3zX60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Sitemap","summary":"Il file sitemap, SITEMAP(), le funzioni F.sitemap, i metodi del controller e @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> Il file sitemap, SITEMAP(), le funzioni F.sitemap, i metodi del controller e @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nIl file che descrive le pagine di un sito web.\n\nIl file `sitemap` nella radice dell'applicazione viene caricato all'avvio. Ogni riga è un elemento: l'ID, ` :` (o un tab e `:`), il titolo, `-->`, l'URL e facoltativamente `-->` e l'ID del padre. Le righe che iniziano con `#` o `// ` sono commenti. Un titolo o un URL in `@(...)` viene tradotto con le risorse. `{0}`…`{5}` sono segnaposto compilati da `sitemap_url()`, `sitemap_name()` o `sitemap_change()`. Un URL che termina con `*` copre tutti i percorsi sottostanti.\n\nExample: Un negozio\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDichiara una route tramite un ID della sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID della sitemap con `#`, facoltativamente preceduto da un metodo HTTP. |\n| `action` | `Function|String` | no |  | Un'azione o il nome di una vista. |\n| `flags` | `Array` | no |  | Flag della route. |\n\nReturns: `undefined`\n\nL'URL proviene dall'elemento della sitemap. Un percorso dopo l'ID viene accodato (`#detail/{id}/`), e un elemento jolly riceve `*`. Senza un'azione, viene eseguito il rendering della vista con il nome dell'ID (`index` per l'URL `/`); con una stringa, di quella vista. In entrambi i casi il breadcrumb e il titolo della pagina vengono impostati dalla sitemap. Nella tua azione chiama `this.sitemap()` per farlo. Un elemento con un URL localizzato crea una route per ogni lingua. Un ID sconosciuto lancia `Sitemap item \"id\" not found.`\n\nExample: Pagine dalla sitemap\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nRestituisce il breadcrumb di un elemento della sitemap, oppure l'elemento stesso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID della sitemap. |\n| `first` | `Boolean` | no | `false` | Restituisce solo l'elemento. |\n| `language` | `String` | no |  | Traduce titoli e URL localizzati. |\n\nReturns: `Array|Object` Il breadcrumb, oppure un singolo elemento.\n\nSenza `first`, restituisce gli elementi dalla radice fino a `id`. Ogni elemento ha `id`, `name`, `url`, `sitemap` (l'ID richiesto), `index` (`0` per l'elemento richiesto), `first` (un elemento radice), `last` e `selected` (l'elemento richiesto), `wildcard`, `formatname` e `formaturl` (il testo contiene segnaposto). Con `first: true`, restituisce solo l'elemento; un ID sconosciuto dà un elemento con `url` vuoto. Una stringa come secondo argomento è la lingua. I risultati vengono messi in cache. Alias: `F.sitemap()`.\n\nExample: Breadcrumb\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: Un singolo URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nRestituisce gli elementi della sitemap con un dato padre, per un menu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | L'ID del padre. |\n| `language` | `String` | no |  | Traduce titoli e URL localizzati. |\n\nReturns: `Array`\n\nSenza `parent`, restituisce gli elementi di primo livello. Ogni elemento ha `name`, `url`, `wildcard`, `formatname` e `formaturl`. L'elenco è ordinato per nome e messo in cache.\n\nExample: Menu principale\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nAggiunge elementi alla sitemap dal codice.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | Una riga o un array di righe. |\n\nReturns: `undefined`\n\nOgni riga ha il formato del file sitemap. Gli ID esistenti vengono sostituiti. Aggiungi gli elementi prima di dichiarare le route che li usano.\n\nExample: Da un modulo\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nCarica nel controller il breadcrumb della pagina.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un ID della sitemap, oppure il tuo breadcrumb. |\n\nReturns: `Array` Il breadcrumb.\n\nCon un ID, copia il breadcrumb `SITEMAP(id)` nel repository, dove le viste lo leggono come `sitemap`, e imposta il titolo sul nome dell'ultimo elemento quando non c'è ancora un titolo. Senza argomenti, restituisce il breadcrumb corrente e alla prima chiamata carica quello dell'ID della sitemap della route. Con un array, usa quell'array come breadcrumb e restituisce il controller.\n\nExample: In un'azione\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nL'ID della sitemap della pagina corrente.\n\nReturns: `String`\n\nL'ID impostato da `controller.sitemap(id)`, altrimenti l'ID della route (`ROUTE('#id')`), oppure una stringa vuota.\n\nExample: Leggerlo\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nRestituisce gli elementi della sitemap con un dato padre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | L'ID del padre. |\n| `language` | `String` | no | `controller.language` | La lingua. |\n\nReturns: `Array`\n\nChiama `F.sitemap_navigation()`. Il padre predefinito è l'ID della sitemap corrente, quindi elenca le sottopagine della pagina corrente. La lingua predefinita è quella della richiesta.\n\nExample: In una vista\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRestituisce l'URL di un elemento della sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | L'ID della sitemap. |\n| `a` | `Object` | no |  | Il valore per `{0}`, poi `b` per `{1}` e così via. |\n\nReturns: `String`\n\nL'URL viene tradotto nella lingua della richiesta e i suoi segnaposto `{0}`…`{5}` vengono compilati con gli altri argomenti. L'ID predefinito è quello corrente. Restituisce una stringa vuota per un ID sconosciuto. Disponibile anche nelle viste come `@{sitemap_url(...)}`.\n\nExample: In una vista\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRestituisce l'URL di un elemento della sitemap in un'altra lingua.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | La lingua. |\n| `id` | `String` | yes |  | L'ID della sitemap. Vuoto indica quello corrente. |\n| `a` | `Object` | no |  | Il valore per `{0}` e così via. |\n\nReturns: `String`\n\nFunziona come `sitemap_url()` con la lingua come primo argomento, per esempio per i link alle altre versioni linguistiche.\n\nExample: Cambio lingua\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRestituisce il titolo di un elemento della sitemap.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | L'ID della sitemap. |\n| `a` | `Object` | no |  | Il valore per `{0}`, poi `b` per `{1}` e così via. |\n\nReturns: `String`\n\nIl titolo viene tradotto nella lingua della richiesta e i suoi segnaposto `{0}`…`{5}` vengono compilati con gli altri argomenti. L'ID predefinito è quello corrente. Restituisce una stringa vuota per un ID sconosciuto. Disponibile anche nelle viste come `@{sitemap_name(...)}`.\n\nExample: In una vista\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nRestituisce il titolo di un elemento della sitemap in un'altra lingua.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | La lingua. |\n| `id` | `String` | yes |  | L'ID della sitemap. Vuoto indica quello corrente. |\n| `a` | `Object` | no |  | Il valore per `{0}` e così via. |\n\nReturns: `String`\n\nFunziona come `sitemap_name()` con la lingua come primo argomento, per esempio per i link alle altre versioni linguistiche.\n\nExample: Cambio lingua\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nModifica una proprietà di un elemento nel breadcrumb corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID dell'elemento nel breadcrumb. |\n| `property` | `String` | yes |  | Di solito `name` o `url`. |\n| `value` | `Object|Function` | yes |  | Il nuovo valore, il valore del primo segnaposto o una funzione. |\n| `b` | `Object` | no |  | Valori per `{1}` e così via. |\n\nReturns: `Array` Il breadcrumb.\n\nLavora su una copia valida solo per questa richiesta. Per `name` e `url` con segnaposto, `value` e gli argomenti successivi compilano `{0}`…`{5}`; altrimenti la proprietà riceve `value`. Una funzione riceve il valore corrente e restituisce quello nuovo. Quando il nome modificato era il titolo della pagina, cambia anche il titolo. In una vista: `@{sitemap_change(...)}`.\n\nExample: Dettaglio del prodotto\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nSostituisce il titolo e l'URL di un elemento nel breadcrumb corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'ID dell'elemento. |\n| `title` | `String|Function` | yes |  | Il nuovo titolo. |\n| `url` | `String|Function` | yes |  | Il nuovo URL. |\n\nReturns: `Array` Il breadcrumb.\n\nSia `title` sia `url` possono essere una stringa o una funzione che riceve il valore corrente. Una stringa compila il segnaposto `{0}` quando l'elemento ne ha uno. I valori vuoti non vengono modificati. Il titolo della pagina segue la modifica. In una vista: `@{sitemap_replace(...)}`.\n\nExample: Entrambi insieme\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nInserisce un elemento nel breadcrumb corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | L'ID dell'elemento dopo il quale va inserito quello nuovo. |\n| `name` | `String` | yes |  | Il titolo. |\n| `url` | `String` | yes |  | L'URL. |\n\nReturns: `Array` Il breadcrumb.\n\nIl nuovo elemento viene posizionato dopo l'elemento con l'ID `parent`. Non cambia nulla quando `parent` non è nel breadcrumb. In una vista: `@{sitemap_add(...)}`.\n\nExample: Un livello di categoria\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nIl breadcrumb in una vista.\n\n`sitemap` in una vista è il breadcrumb caricato da `controller.sitemap()` o da una route con ID. `@{sitemap('id')}` ne carica un altro dalla vista e non stampa nulla. I metodi del controller `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` e `sitemap_add()` sono disponibili con gli stessi nomi. Vedi [Viste](../../guides/views/).\n\nExample: Breadcrumb in un layout\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jafjrg3zX60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/sitemap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Sitemap","summary":"Súbor sitemap, SITEMAP(), funkcie F.sitemap, metódy controllera a @{sitemap}.","markdown":"---\ntitle: Sitemap\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/sitemap/\nupdated: 2026-11-18T16:57:39.578Z\n---\n\n# Sitemap\n\n> Súbor sitemap, SITEMAP(), funkcie F.sitemap, metódy controllera a @{sitemap}.\n\n## API\n\n### id : title --> url --> [parent]\n\nType: `type`\n\nSúbor, ktorý opisuje stránky webu.\n\nSúbor `sitemap` v koreni aplikácie sa načíta pri štarte. Každý riadok je položka: ID, ` :` (alebo tabulátor a `:`), titulok, `-->`, URL a voliteľne `-->` a ID rodiča. Riadky, ktoré začínajú `#` alebo `// `, sú komentáre. Titulok alebo URL v `@(...)` sa preloží pomocou zdrojov. `{0}`…`{5}` sú zástupné symboly, ktoré vyplnia `sitemap_url()`, `sitemap_name()` alebo `sitemap_change()`. URL, ktorá končí `*`, pokrýva všetky cesty pod ňou.\n\nExample: Obchod\n```text\nhomepage : Homepage     --> /\nproducts : @(Products)  --> /products/       --> homepage\ndetail   : {0}          --> /products/{0}/   --> products\ndocs     : Docs         --> /docs/*          --> homepage\n```\n\n### ROUTE('[METHOD] #id[/path]', [action], [flags])\n\nType: `method`\n\nDeklaruje trasu podľa ID zo sitemapy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID zo sitemapy s `#`, voliteľne s HTTP metódou pred ním. |\n| `action` | `Function|String` | no |  | Akcia alebo názov view. |\n| `flags` | `Array` | no |  | Flagy trasy. |\n\nReturns: `undefined`\n\nURL pochádza z položky sitemapy. Cesta za ID sa pripojí (`#detail/{id}/`) a položka so zástupným znakom dostane `*`. Bez akcie sa vykreslí view s názvom ID (`index` pre URL `/`); s reťazcom tento view. V oboch prípadoch sa navigačná cesta a titulok stránky nastavia zo sitemapy. Vo vlastnej akcii na to zavolaj `this.sitemap()`. Položka s lokalizovanou URL vytvorí trasu pre každý jazyk. Neznáme ID vyhodí `Sitemap item \"id\" not found.`\n\nExample: Stránky zo sitemapy\n```js\nexports.install = function() {\n\tROUTE('#homepage');\n\tROUTE('#products', 'products/list');\n\tROUTE('GET #detail', detail);\n};\n\nfunction detail(id) {\n\tthis.sitemap();\n\tthis.sitemap_change('detail', 'name', id);\n\tthis.sitemap_change('detail', 'url', id);\n\tthis.view('products/detail');\n}\n```\n\n### SITEMAP(id, [first], [language])\n\nType: `method`\n\nVráti navigačnú cestu položky sitemapy alebo samotnú položku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID zo sitemapy. |\n| `first` | `Boolean` | no | `false` | Vráti len položku. |\n| `language` | `String` | no |  | Preloží lokalizované titulky a URL. |\n\nReturns: `Array|Object` Navigačná cesta alebo jedna položka.\n\nBez `first` vráti položky od koreňa po `id`. Každá položka má `id`, `name`, `url`, `sitemap` (požadované ID), `index` (`0` pre požadovanú položku), `first` (koreňová položka), `last` a `selected` (požadovaná položka), `wildcard`, `formatname` a `formaturl` (text má zástupné symboly). S `first: true` vráti len položku; neznáme ID dá položku s prázdnou `url`. Reťazec ako druhý argument je jazyk. Výsledky sa ukladajú do cache. Alias: `F.sitemap()`.\n\nExample: Navigačná cesta\n```js\nvar items = SITEMAP('detail');\n// [{ id: 'homepage', ... }, { id: 'products', ... }, { id: 'detail', ... }]\n```\n\nExample: Jedna URL\n```js\nvar url = SITEMAP('products', true).url; // '/products/'\n```\n\n### F.sitemap_navigation([parent], [language])\n\nType: `method`\n\nVráti položky sitemapy s jedným rodičom, pre menu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no |  | ID rodiča. |\n| `language` | `String` | no |  | Preloží lokalizované titulky a URL. |\n\nReturns: `Array`\n\nBez `parent` vráti položky najvyššej úrovne. Každá položka má `name`, `url`, `wildcard`, `formatname` a `formaturl`. Zoznam je zoradený podľa názvu a uložený v cache.\n\nExample: Hlavné menu\n```js\nvar menu = F.sitemap_navigation('homepage');\n```\n\n### F.sitemap_add(line)\n\nType: `method`\n\nPridá položky do sitemapy z kódu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String|Array` | yes |  | Jeden riadok alebo pole riadkov. |\n\nReturns: `undefined`\n\nKaždý riadok má formát súboru sitemap. Existujúce ID sa nahradia. Položky pridaj predtým, ako deklaruješ trasy, ktoré ich používajú.\n\nExample: Z modulu\n```js\nF.sitemap_add(['blog : Blog --> /blog/ --> homepage', 'post : {0} --> /blog/{0}/ --> blog']);\n```\n\n### controller.sitemap([id])\n\nType: `method`\n\nNačíta navigačnú cestu stránky do kontroléra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | ID zo sitemapy alebo vlastná navigačná cesta. |\n\nReturns: `Array` Navigačná cesta.\n\nS ID skopíruje navigačnú cestu `SITEMAP(id)` do repozitára, kde ju view čítajú ako `sitemap`, a nastaví titulok na názov poslednej položky, keď titulok ešte nie je. Bez argumentu vráti aktuálnu navigačnú cestu a pri prvom volaní načíta tú, ktorá patrí k ID trasy zo sitemapy. S poľom použije toto pole ako navigačnú cestu a vráti kontrolér.\n\nExample: V akcii\n```js\nfunction detail() {\n\tthis.sitemap('detail');\n\tthis.view('detail');\n}\n```\n\n### controller.sitemapid\n\nType: `property`\n\nID aktuálnej stránky zo sitemapy.\n\nReturns: `String`\n\nID nastavené cez `controller.sitemap(id)`, inak ID trasy (`ROUTE('#id')`) alebo prázdny reťazec.\n\nExample: Čítanie\n```js\nfunction page() {\n\tconsole.log(this.sitemapid);\n\tthis.view('page');\n}\n```\n\n### controller.sitemap_navigation([parent], [language])\n\nType: `method`\n\nVráti položky sitemapy s jedným rodičom.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | no | `controller.sitemapid` | ID rodiča. |\n| `language` | `String` | no | `controller.language` | Jazyk. |\n\nReturns: `Array`\n\nVolá `F.sitemap_navigation()`. Predvolený rodič je aktuálne ID zo sitemapy, takže vypíše podstránky aktuálnej stránky. Predvolený jazyk je jazyk požiadavky.\n\nExample: Vo view\n```html\n<ul>\n@{foreach m in sitemap_navigation('homepage')}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n@{end}\n</ul>\n```\n\n### controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nVráti URL položky sitemapy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | ID zo sitemapy. |\n| `a` | `Object` | no |  | Hodnota pre `{0}`, potom `b` pre `{1}` a tak ďalej. |\n\nReturns: `String`\n\nURL sa preloží do jazyka požiadavky a jej zástupné symboly `{0}`…`{5}` sa vyplnia ostatnými argumentmi. Predvolené ID je aktuálne. Pre neznáme ID vráti prázdny reťazec. Dostupné aj vo view ako `@{sitemap_url(...)}`.\n\nExample: Vo view\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nVráti URL položky sitemapy v inom jazyku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Jazyk. |\n| `id` | `String` | yes |  | ID zo sitemapy. Prázdne znamená aktuálne. |\n| `a` | `Object` | no |  | Hodnota pre `{0}` a tak ďalej. |\n\nReturns: `String`\n\nFunguje ako `sitemap_url()` s jazykom ako prvým argumentom, napríklad pre odkazy na iné jazykové verzie.\n\nExample: Prepínač jazyka\n```html\n<a href=\"@{sitemap_url2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nVráti titulok položky sitemapy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no | `controller.sitemapid` | ID zo sitemapy. |\n| `a` | `Object` | no |  | Hodnota pre `{0}`, potom `b` pre `{1}` a tak ďalej. |\n\nReturns: `String`\n\nTitulok sa preloží do jazyka požiadavky a jeho zástupné symboly `{0}`…`{5}` sa vyplnia ostatnými argumentmi. Predvolené ID je aktuálne. Pre neznáme ID vráti prázdny reťazec. Dostupné aj vo view ako `@{sitemap_name(...)}`.\n\nExample: Vo view\n```html\n<a href=\"@{sitemap_url('detail', m.id)}\">@{sitemap_name('detail', m.name)}</a>\n```\n\n### controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])\n\nType: `method`\n\nVráti titulok položky sitemapy v inom jazyku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `language` | `String` | yes |  | Jazyk. |\n| `id` | `String` | yes |  | ID zo sitemapy. Prázdne znamená aktuálne. |\n| `a` | `Object` | no |  | Hodnota pre `{0}` a tak ďalej. |\n\nReturns: `String`\n\nFunguje ako `sitemap_name()` s jazykom ako prvým argumentom, napríklad pre odkazy na iné jazykové verzie.\n\nExample: Prepínač jazyka\n```html\n<a href=\"@{sitemap_name2('de', '')}\">Deutsch</a>\n```\n\n### controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])\n\nType: `method`\n\nZmení jednu vlastnosť položky v aktuálnej navigačnej ceste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID položky v navigačnej ceste. |\n| `property` | `String` | yes |  | Zvyčajne `name` alebo `url`. |\n| `value` | `Object|Function` | yes |  | Nová hodnota, hodnota prvého zástupného symbolu alebo funkcia. |\n| `b` | `Object` | no |  | Hodnoty pre `{1}` a tak ďalej. |\n\nReturns: `Array` Navigačná cesta.\n\nPracuje s kópiou len pre túto požiadavku. Pri `name` a `url` so zástupnými symbolmi vyplnia `value` a ďalšie argumenty `{0}`…`{5}`; inak vlastnosť dostane `value`. Funkcia dostane aktuálnu hodnotu a vráti novú. Keď bol zmenený názov titulkom stránky, zmení sa aj titulok. Vo view: `@{sitemap_change(...)}`.\n\nExample: Detail produktu\n```js\nfunction detail(id) {\n\tvar self = this;\n\tself.sitemap('detail');\n\tself.sitemap_change('detail', 'name', 'Book ' + id);\n\tself.sitemap_change('detail', 'url', id);\n\tself.view('detail');\n}\n```\n\n### controller.sitemap_replace(id, title, url)\n\nType: `method`\n\nNahradí titulok a URL položky v aktuálnej navigačnej ceste.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | ID položky. |\n| `title` | `String|Function` | yes |  | Nový titulok. |\n| `url` | `String|Function` | yes |  | Nová URL. |\n\nReturns: `Array` Navigačná cesta.\n\n`title` aj `url` môžu byť reťazec alebo funkcia, ktorá dostane aktuálnu hodnotu. Reťazec vyplní zástupný symbol `{0}`, keď ho položka má. Prázdne hodnoty sa nemenia. Titulok stránky nasleduje zmenu. Vo view: `@{sitemap_replace(...)}`.\n\nExample: Oboje naraz\n```js\nthis.sitemap('detail');\nthis.sitemap_replace('detail', product.name, product.slug);\n```\n\n### controller.sitemap_add(parent, name, url)\n\nType: `method`\n\nVloží položku do aktuálnej navigačnej cesty.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `parent` | `String` | yes |  | ID položky, za ktorú ide nová položka. |\n| `name` | `String` | yes |  | Titulok. |\n| `url` | `String` | yes |  | URL. |\n\nReturns: `Array` Navigačná cesta.\n\nNová položka sa umiestni za položku s ID `parent`. Keď `parent` v navigačnej ceste nie je, nič sa nezmení. Vo view: `@{sitemap_add(...)}`.\n\nExample: Úroveň kategórie\n```js\nthis.sitemap('detail');\nthis.sitemap_add('products', category.name, '/products/?category=' + category.id);\n```\n\n### @{sitemap}  @{sitemap('id')}\n\nType: `command`\n\nNavigačná cesta vo view.\n\n`sitemap` vo view je navigačná cesta načítaná cez `controller.sitemap()` alebo ID trasou. `@{sitemap('id')}` načíta inú priamo z view a nič nevypíše. Metódy kontroléra `sitemap_url()`, `sitemap_name()`, `sitemap_url2()`, `sitemap_name2()`, `sitemap_navigation()`, `sitemap_change()`, `sitemap_replace()` a `sitemap_add()` sú dostupné pod rovnakými názvami. Pozri [View](../../guides/views/).\n\nExample: Navigačná cesta v layoute\n```html\n<ol class=\"breadcrumb\">\n@{foreach m in sitemap}\n\t@{if m.last}\n\t<li>@{m.name}</li>\n\t@{else}\n\t<li><a href=\"@{m.url}\">@{m.name}</a></li>\n\t@{fi}\n@{end}\n</ol>\n```\n","entries":[{"type":"type","name":"sitemap file","signature":"id : title --> url --> [parent]","since":"","deprecated":false},{"type":"method","name":"ROUTE('#id')","signature":"ROUTE('[METHOD] #id[/path]', [action], [flags])","since":"","deprecated":false},{"type":"method","name":"SITEMAP()","signature":"SITEMAP(id, [first], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_navigation()","signature":"F.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"F.sitemap_add()","signature":"F.sitemap_add(line)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap()","signature":"controller.sitemap([id])","since":"","deprecated":false},{"type":"property","name":"controller.sitemapid","signature":"controller.sitemapid","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_navigation()","signature":"controller.sitemap_navigation([parent], [language])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url()","signature":"controller.sitemap_url([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_url2()","signature":"controller.sitemap_url2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name()","signature":"controller.sitemap_name([id], [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_name2()","signature":"controller.sitemap_name2(language, id, [a], [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_change()","signature":"controller.sitemap_change(id, property, value, [b], [c], [d], [e], [f])","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_replace()","signature":"controller.sitemap_replace(id, title, url)","since":"","deprecated":false},{"type":"method","name":"controller.sitemap_add()","signature":"controller.sitemap_add(parent, name, url)","since":"","deprecated":false},{"type":"command","name":"@{sitemap}","signature":"@{sitemap}  @{sitemap('id')}","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:39.578Z"}
{"id":"Jabdps3Ul61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Cache, counters and small stores","summary":"Reference of CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() and RESTORE().","markdown":"---\ntitle: Cache, counters and small stores\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, counters and small stores\n\n> Reference of CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() and RESTORE().\n\nGlobal functions for small amounts of data: the in-memory cache (`CACHE()` and `F.cache`), file caches, preferences, persistent objects, counters, two extra NoSQL stores and backups of folders. In this reference `counter` is an instance returned by `COUNTER()`. The guide [Cache, counters and small stores](../../guides/caching-and-small-stores/) explains how to use them with examples.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nReads or saves a value in the in-memory cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `value` | `Object` | no |  | The value to save. Leave it out to read. |\n| `expire` | `String|Date` | no | `'5 minutes'` | A text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 5 minutes. |\n\nReturns: `Object` The cached value.\n\nWith one argument the function returns the cached value, or `undefined` when the key does not exist or has expired. With more arguments it saves the value and returns it. It is a short form of `F.cache.get2()` and `F.cache.set()`.\n\nThe cache lives in the memory of the process and is empty after a restart (unless `allow_cache_snapshot` is enabled).\n\nExample: Cache a list\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nThe in-memory cache of the app.\n\nReturns: `Object` The cache instance.\n\nThe object behind `CACHE()`. Its items are in `F.cache.items`, an object where each key holds `{ value, expire }`. Once a minute Total.js removes expired items and emits `cache_expired` for each of them.\n\nExample: Count cached keys\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nSaves a value to the cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `value` | `Object` | yes |  | The value to save. |\n| `expire` | `String|Date` | no | `'5 minutes'` | A text such as `'5 minutes'` or `'1 hour'`, or a `Date`. Without it the value expires in 5 minutes. |\n\nReturns: `Object` The saved value.\n\nReplaces an existing value with the same key and emits the event `cache_set`. `F.cache.add()` is the same method. With `allow_cache_cluster` the value is sent to the other processes of the cluster.\n\nExample: Save for one hour\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nReads a value from the cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `def` | `Object` | no | `undefined` | The value to return when nothing is cached. |\n\nReturns: `Object` The cached value or `def`.\n\nReturns `def` when the key does not exist or the value has expired. An expired value is removed and the event `cache_expired` is emitted. `F.cache.read()` is the same method.\n\nExample: Read with a default value\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nReads a value from the cache without updating the current time.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `def` | `Object` | no | `undefined` | The value to return when nothing is cached. |\n\nReturns: `Object` The cached value or `def`.\n\nWorks like `F.cache.get()`, but compares the expiration with the global `NOW`, which Total.js updates periodically, instead of a new `Date`. It is a little faster and an item can stay valid for a few seconds longer. `CACHE(key)` uses it. `F.cache.read2()` is the same method.\n\nExample: Read\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nRemoves one value from the cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n\nReturns: `Object` The removed item `{ value, expire }`, or `undefined`.\n\nWith `allow_cache_cluster` the removal is sent to the other processes of the cluster.\n\nExample: Remove after an update\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nRemoves all values whose key contains a text or matches a regular expression.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | A part of the key, or a regular expression. |\n\nReturns: `Number` The number of removed items.\n\nA text removes every key that contains it; a `RegExp` removes every key it matches. To remove everything use `F.cache.clear()`. `F.cache.reset()` is the same method.\n\nExample: Remove by prefix\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nRemoves every value from the cache.\n\nReturns: `Object` The cache, for chaining.\n\nWith `allow_cache_cluster` the other processes of the cluster are cleared too.\n\nExample: Clear the cache\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nChanges the expiration of a cached value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `expire` | `String|Date` | yes |  | A text such as `'1 hour'`, or a `Date`. |\n\nReturns: `Object` The cache, for chaining.\n\nDoes nothing when the key does not exist.\n\nExample: Extend a session\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nReturns a cached value or creates it with a function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | The key of the value. |\n| `maker` | `Function` | yes |  | `function(next, options)` that creates the value and calls `next(value, [expire])`. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | Any object, passed to both functions. |\n\nReturns: `Object` The cache, for chaining.\n\nWhen the key holds a value, `callback(value, true, options)` is called at once. Otherwise `maker(next, options)` runs; call `next(value, [expire])` to cache the value, and then `callback(value, false, options)` is called. A falsy value (`false`, `0`, `''`, `null`) is not considered cached.\n\nExample: Cache a query\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nReturns a value cached in a file, or creates it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The identifier of the cached value. |\n| `expire` | `String` | yes |  | How long the file is valid, for example `'1 hour'` or `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` that creates the value and calls `next(err, value, [load])`. |\n| `encoding` | `String` | no | `'json'` | `'json'`, or the encoding of a text value such as `'utf8'`. |\n\nThe value is stored in the `tmp/` folder in a file named after a hash of `id`. When the file does not exist or is older than `expire`, `maker(next, id)` runs. Call `next(err, value, [load])`: without an error the value is written to the file, and `callback(err, value)` is called unless `load` is `false`. Otherwise the file is read and passed to `callback(err, value)`.\n\nBy default the value is saved as JSON and parsed back (dates included). With another `encoding`, for example `'utf8'`, the value is written as it is and read as a text.\n\nExample: Cache a remote file for a day\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nReturns an object that is saved to a JSON file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | The name of the file. |\n| `delay` | `Number` | no | `10000` | Milliseconds between `save()` and the write. |\n| `skip` | `String|Array` | no |  | Keys that are not written to the file, as an array or a text separated by commas. |\n\nReturns: `Object` The stored object with a `save()` method.\n\nReads `databases/memorize_{name}.json` (or `databases/memorize.json` without a name) synchronously and returns its content as an object, or an empty object when the file does not exist. The object has a method `save()` that writes it back.\n\nEach call reads the file again and returns a new object, so call it once and keep the reference. The `delay` and `skip` arguments can be passed in any order. The `databases` folder must exist.\n\nExample: Remember the last run\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nWrites the object of MEMORIZE() to its file.\n\nThe write happens after the delay given to `MEMORIZE()` (10 seconds by default). Another `save()` within that time restarts the delay, so a burst of changes gives one write. The object is written as formatted JSON; functions and the keys in `skip` are left out.\n\nExample: Save after a change\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPreferences of the app that are saved to a file.\n\nReturns: `Object` The preferences.\n\nTotal.js loads `databases/preferences.json` at start and copies each value to `PREF`, so you read a preference as a property: `PREF.token`. In a thread the file is `databases/preferences_{thread}.json`. Change values only with `PREF.set()`, `PREF.inc()` and `PREF.rem()`; a value assigned directly is not saved. Do not use the names `set`, `inc` and `rem`.\n\nExample: Read a preference\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nSaves a preference or reads it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the preference. |\n| `value` | `Object` | no |  | The new value, or `null` to remove it. |\n\nReturns: `Object` The value.\n\nWithout `value` the function returns the current value. With a value it saves it to `PREF` and writes all preferences one second after the last change (through `DEF.onPrefSave`). `null` removes the preference, like `PREF.rem()`.\n\nExample: Save a token\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nAdds a number to a preference.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the preference. |\n| `value` | `Number` | no | `1` | The number to add. |\n\nReturns: `Number` The new value.\n\nStarts from `value` when the preference does not exist. The result is saved like `PREF.set()`.\n\nExample: Count imports\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nRemoves a preference from the saved file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the preference. |\n\nThe preference is removed from `PREF` and the file is written again.\n\nExample: Remove a token\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nLoads the preferences at start.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)` that receives the stored preferences. |\n\nThe default delegate reads `databases/preferences.json` and calls `next(object)`. Replace it to keep the preferences somewhere else; call `next(object)` with the stored values, or `next()` when there are none. Assign it in a definition file: when the delegate changes while the app starts, Total.js loads the preferences again with the new one.\n\nExample: Preferences in a database table\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nSaves the preferences.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | All preferences. |\n\nCalled one second after the last change of a preference, with an object of all preferences. The default delegate writes it as formatted JSON to `databases/preferences.json`. Replace it together with `DEF.onPrefLoad`.\n\nExample: Log every save\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nReturns a counter that keeps daily statistics.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the counter. |\n\nReturns: `Counter` The counter instance.\n\nThe data is stored in `databases/{name}.counter` as NoSQL documents, one per id and day: `{ id, sum, min, max, day, month, year, ts, date }`, where `ts` is the date as a number `yyyyMMdd`. The instance is created on the first call and then reused.\n\n`hit()` collects values in memory. On every fifth `service` event (about every five minutes) the counter writes them to the file. Values that are not written yet are lost when the process stops.\n\nThe reading methods return a NoSQL query builder: pass the callback as the last argument or call `.callback()` on the result.\n\nExample: Count visits\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nAdds a value to the counter of today.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | What you count, for example a page or a product. |\n| `value` | `Number` | no | `1` | The value to add. |\n\nReturns: `Counter` The counter, for chaining.\n\nThe value is added to the sum of `id` for the current day. The counter also keeps the smallest and the largest single value as `min` and `max`.\n\nExample: Count an amount\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nWrites the collected values to the file now.\n\nReturns: `Counter` The counter, for chaining.\n\nThe counter calls it periodically. Call it yourself before a planned stop so that no hits are lost.\n\nExample: Flush before exit\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nReturns the total sum of all stored values.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | An id or an array of ids. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nSums the `sum` field of all days, for one `id` or an array of ids, or for all ids. Values that are not flushed yet are not included.\n\nExample: Total visits\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nReturns the stored days of one id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nEach item is a stored document without `id`: `{ sum, min, max, day, month, year, ts, date }`. You can add conditions, sorting and paging to the returned builder.\n\nExample: The last 30 days\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nReturns the values of one id grouped by month.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nEach item is `{ date, year, month, ts, sum, min, max, count }`, where `date` is the month as text `yyyyMM`, `ts` the same as a number and `count` the number of stored days.\n\nExample: Monthly sales\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nReturns the values of one id grouped by year.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | The id of the counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nEach item is `{ date, year, ts, sum, min, max, count }`, where `date` is the year as text and `count` the number of stored days.\n\nExample: Yearly visits\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nReturns totals of all ids.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` or `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nWithout `type` you get one item per id: `{ id, sum, min, max, count }`. With `'monthly'` or `'yearly'` you get one item per id and month or year, with the fields `ts`, `date`, `year` and (for months) `month` added.\n\nExample: Top pages\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nReturns a query builder over the stored documents.\n\nReturns: `QueryBuilder` The query builder.\n\nUse it for reports that the other methods do not cover. The documents have the fields `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` and `date`.\n\nExample: One month of all ids\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nRemoves stored documents of one id, or all of them.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | The id of the counter. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` The query builder.\n\nWithout `id` every stored document is removed. Values that are not flushed yet stay in memory.\n\nExample: Remove one id\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nRemoves all stored data of the counter.\n\nReturns: `Counter` The counter, for chaining.\n\nEmpties the file. Values that are not flushed yet stay in memory.\n\nExample: Reset statistics\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nReturns a NoSQL database that keeps its documents in memory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the database. |\n\nReturns: `Database` The database instance.\n\nAll documents are loaded from `databases/{name}.inmemory` on the first operation and kept in memory. After a change the file is written in 5 seconds. The instance is created on the first call and then reused.\n\nIt supports `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` and `remove()` with the query builder of `NOSQL()`. Keep the collection small: every document is in memory.\n\nExample: A list of online users\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nReturns a NoSQL database stored in several files of a folder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the database, or `~` followed by an absolute path to the folder. |\n\nReturns: `Database` The database instance.\n\nThe documents are stored in the folder `databases/textdb-{name}/`. New documents go to a file until it has about 512 kB, then a new file is started. The methods and the query builder are the same as `NOSQL()`. A name that starts with `~` is an absolute path to the folder; such an instance is not cached.\n\nExample: Log of events\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nPacks the files of a folder into one backup file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The path of the backup file, or a writable stream. |\n| `path` | `String|Array` | yes |  | A folder, or an array of paths relative to the root of the app. |\n| `callback` | `Function` | no |  | `function(err, meta)` where `meta` is `{ filename, files, size }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)` that returns `true` to include the item. |\n\n`path` is a folder: all its files and subfolders are packed. It can also be an array of paths relative to the root of the app. An existing backup file is replaced. Each file is compressed with GZIP and stored as Base64 on one line, after its relative path.\n\nThe `filter(path, isdirectory)` function receives a relative path that starts with `/` (folders end with `/`). Return `true` to include the item. Sockets are skipped.\n\nExample: Back up uploaded files\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nUnpacks a backup file made by BACKUP() into a folder.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | The path of the backup file, or a readable stream. |\n| `target` | `String` | yes |  | The folder where the files are written. |\n| `callback` | `Function` | no |  | `function(err, meta)` where `meta` is `{ files, size, path }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nFolders that do not exist are created. Existing files with the same name are overwritten.\n\nThe `filter(path, isdirectory)` function receives the relative path from the backup. For a file return `false` to skip it, a new relative path (in an existing folder) to write it elsewhere, or nothing to keep it. For a folder return `false` to not create it.\n\nExample: Restore uploaded files\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdps3Ul61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Cache, Zähler und kleine Speicher","summary":"Referenz von CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() und RESTORE().","markdown":"---\ntitle: \"Cache, Zähler und kleine Speicher\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, Zähler und kleine Speicher\n\n> Referenz von CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() und RESTORE().\n\nGlobale Funktionen für kleine Datenmengen: der In-Memory-Cache (`CACHE()` und `F.cache`), Datei-Caches, Präferenzen, persistente Objekte, Zähler, zwei zusätzliche NoSQL-Speicher und Sicherungen von Ordnern. In dieser Referenz ist `counter` eine von `COUNTER()` zurückgegebene Instanz. Der Guide [Cache, Zähler und kleine Speicher](../../guides/caching-and-small-stores/) erklärt die Verwendung mit Beispielen.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nLiest oder speichert einen Wert im In-Memory-Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `value` | `Object` | no |  | Der zu speichernde Wert. Lass ihn weg, um zu lesen. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Ein Text wie `'5 minutes'` oder `'1 hour'` oder ein `Date`. Ohne ihn läuft der Wert nach 5 Minuten ab. |\n\nReturns: `Object` Der gecachte Wert.\n\nMit einem Argument gibt die Funktion den gecachten Wert zurück, oder `undefined`, wenn der Schlüssel nicht existiert oder abgelaufen ist. Mit mehr Argumenten speichert sie den Wert und gibt ihn zurück. Sie ist eine Kurzform von `F.cache.get2()` und `F.cache.set()`.\n\nDer Cache liegt im Speicher des Prozesses und ist nach einem Neustart leer (außer wenn `allow_cache_snapshot` aktiviert ist).\n\nExample: Eine Liste cachen\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nDer In-Memory-Cache der App.\n\nReturns: `Object` Die Cache-Instanz.\n\nDas Objekt hinter `CACHE()`. Seine Einträge liegen in `F.cache.items`, einem Objekt, in dem jeder Schlüssel `{ value, expire }` enthält. Einmal pro Minute entfernt Total.js abgelaufene Einträge und löst für jeden davon `cache_expired` aus.\n\nExample: Gecachte Schlüssel zählen\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nSpeichert einen Wert im Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `value` | `Object` | yes |  | Der zu speichernde Wert. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Ein Text wie `'5 minutes'` oder `'1 hour'` oder ein `Date`. Ohne ihn läuft der Wert nach 5 Minuten ab. |\n\nReturns: `Object` Der gespeicherte Wert.\n\nErsetzt einen vorhandenen Wert mit demselben Schlüssel und löst das Event `cache_set` aus. `F.cache.add()` ist dieselbe Methode. Mit `allow_cache_cluster` wird der Wert an die anderen Prozesse des Clusters gesendet.\n\nExample: Für eine Stunde speichern\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nLiest einen Wert aus dem Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `def` | `Object` | no | `undefined` | Der Wert, der zurückgegeben wird, wenn nichts gecacht ist. |\n\nReturns: `Object` Der gecachte Wert oder `def`.\n\nGibt `def` zurück, wenn der Schlüssel nicht existiert oder der Wert abgelaufen ist. Ein abgelaufener Wert wird entfernt und das Event `cache_expired` ausgelöst. `F.cache.read()` ist dieselbe Methode.\n\nExample: Mit Standardwert lesen\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nLiest einen Wert aus dem Cache, ohne die aktuelle Zeit zu aktualisieren.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `def` | `Object` | no | `undefined` | Der Wert, der zurückgegeben wird, wenn nichts gecacht ist. |\n\nReturns: `Object` Der gecachte Wert oder `def`.\n\nFunktioniert wie `F.cache.get()`, vergleicht den Ablauf aber mit dem globalen `NOW`, das Total.js periodisch aktualisiert, statt mit einem neuen `Date`. Es ist etwas schneller, und ein Eintrag kann ein paar Sekunden länger gültig bleiben. `CACHE(key)` verwendet es. `F.cache.read2()` ist dieselbe Methode.\n\nExample: Lesen\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nEntfernt einen Wert aus dem Cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n\nReturns: `Object` Der entfernte Eintrag `{ value, expire }` oder `undefined`.\n\nMit `allow_cache_cluster` wird das Entfernen an die anderen Prozesse des Clusters gesendet.\n\nExample: Nach einem Update entfernen\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nEntfernt alle Werte, deren Schlüssel einen Text enthält oder zu einem regulären Ausdruck passt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | Ein Teil des Schlüssels oder ein regulärer Ausdruck. |\n\nReturns: `Number` Die Anzahl der entfernten Einträge.\n\nEin Text entfernt jeden Schlüssel, der ihn enthält; ein `RegExp` entfernt jeden Schlüssel, auf den er passt. Um alles zu entfernen, nutze `F.cache.clear()`. `F.cache.reset()` ist dieselbe Methode.\n\nExample: Nach Präfix entfernen\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nEntfernt jeden Wert aus dem Cache.\n\nReturns: `Object` Der Cache, zum Verketten.\n\nMit `allow_cache_cluster` werden auch die anderen Prozesse des Clusters geleert.\n\nExample: Den Cache leeren\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nÄndert den Ablauf eines gecachten Werts.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `expire` | `String|Date` | yes |  | Ein Text wie `'1 hour'` oder ein `Date`. |\n\nReturns: `Object` Der Cache, zum Verketten.\n\nMacht nichts, wenn der Schlüssel nicht existiert.\n\nExample: Eine Sitzung verlängern\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nGibt einen gecachten Wert zurück oder erzeugt ihn mit einer Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Der Schlüssel des Werts. |\n| `maker` | `Function` | yes |  | `function(next, options)`, die den Wert erzeugt und `next(value, [expire])` aufruft. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | Ein beliebiges Objekt, das an beide Funktionen übergeben wird. |\n\nReturns: `Object` Der Cache, zum Verketten.\n\nEnthält der Schlüssel einen Wert, wird `callback(value, true, options)` sofort aufgerufen. Andernfalls läuft `maker(next, options)`; rufe `next(value, [expire])` auf, um den Wert zu cachen, und danach wird `callback(value, false, options)` aufgerufen. Ein falsy Wert (`false`, `0`, `''`, `null`) gilt nicht als gecacht.\n\nExample: Eine Abfrage cachen\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nGibt einen in einer Datei gecachten Wert zurück oder erzeugt ihn.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die Kennung des gecachten Werts. |\n| `expire` | `String` | yes |  | Wie lange die Datei gültig ist, zum Beispiel `'1 hour'` oder `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)`, die den Wert erzeugt und `next(err, value, [load])` aufruft. |\n| `encoding` | `String` | no | `'json'` | `'json'` oder die Kodierung eines Textwerts wie `'utf8'`. |\n\nDer Wert wird im Ordner `tmp/` in einer Datei gespeichert, die nach einem Hash von `id` benannt ist. Existiert die Datei nicht oder ist sie älter als `expire`, läuft `maker(next, id)`. Rufe `next(err, value, [load])` auf: Ohne Fehler wird der Wert in die Datei geschrieben, und `callback(err, value)` wird aufgerufen, außer `load` ist `false`. Andernfalls wird die Datei gelesen und an `callback(err, value)` übergeben.\n\nStandardmäßig wird der Wert als JSON gespeichert und zurückgeparst (inklusive Datumswerten). Mit einem anderen `encoding`, zum Beispiel `'utf8'`, wird der Wert unverändert geschrieben und als Text gelesen.\n\nExample: Eine entfernte Datei für einen Tag cachen\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nGibt ein Objekt zurück, das in einer JSON-Datei gespeichert wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | Der Name der Datei. |\n| `delay` | `Number` | no | `10000` | Millisekunden zwischen `save()` und dem Schreiben. |\n| `skip` | `String|Array` | no |  | Schlüssel, die nicht in die Datei geschrieben werden, als Array oder als kommagetrennter Text. |\n\nReturns: `Object` Das gespeicherte Objekt mit einer Methode `save()`.\n\nLiest `databases/memorize_{name}.json` (oder ohne Namen `databases/memorize.json`) synchron und gibt den Inhalt als Objekt zurück, oder ein leeres Objekt, wenn die Datei nicht existiert. Das Objekt hat eine Methode `save()`, die es zurückschreibt.\n\nJeder Aufruf liest die Datei erneut und gibt ein neues Objekt zurück, also rufe es einmal auf und behalte die Referenz. Die Argumente `delay` und `skip` können in beliebiger Reihenfolge übergeben werden. Der Ordner `databases` muss existieren.\n\nExample: Den letzten Lauf merken\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nSchreibt das Objekt von MEMORIZE() in seine Datei.\n\nDas Schreiben erfolgt nach der an `MEMORIZE()` übergebenen Verzögerung (standardmäßig 10 Sekunden). Ein weiteres `save()` innerhalb dieser Zeit startet die Verzögerung neu, sodass eine Reihe von Änderungen einen einzigen Schreibvorgang ergibt. Das Objekt wird als formatiertes JSON geschrieben; Funktionen und die Schlüssel in `skip` werden weggelassen.\n\nExample: Nach einer Änderung speichern\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPräferenzen der App, die in einer Datei gespeichert werden.\n\nReturns: `Object` Die Präferenzen.\n\nTotal.js lädt beim Start `databases/preferences.json` und kopiert jeden Wert nach `PREF`, sodass du eine Präferenz als Eigenschaft liest: `PREF.token`. In einem Thread ist die Datei `databases/preferences_{thread}.json`. Ändere Werte nur mit `PREF.set()`, `PREF.inc()` und `PREF.rem()`; ein direkt zugewiesener Wert wird nicht gespeichert. Verwende nicht die Namen `set`, `inc` und `rem`.\n\nExample: Eine Präferenz lesen\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nSpeichert eine Präferenz oder liest sie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Präferenz. |\n| `value` | `Object` | no |  | Der neue Wert oder `null`, um ihn zu entfernen. |\n\nReturns: `Object` Der Wert.\n\nOhne `value` gibt die Funktion den aktuellen Wert zurück. Mit einem Wert speichert sie ihn in `PREF` und schreibt alle Präferenzen eine Sekunde nach der letzten Änderung (über `DEF.onPrefSave`). `null` entfernt die Präferenz, wie `PREF.rem()`.\n\nExample: Ein Token speichern\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nAddiert eine Zahl zu einer Präferenz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Präferenz. |\n| `value` | `Number` | no | `1` | Die zu addierende Zahl. |\n\nReturns: `Number` Der neue Wert.\n\nBeginnt mit `value`, wenn die Präferenz nicht existiert. Das Ergebnis wird wie bei `PREF.set()` gespeichert.\n\nExample: Importe zählen\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nEntfernt eine Präferenz aus der gespeicherten Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Präferenz. |\n\nDie Präferenz wird aus `PREF` entfernt und die Datei neu geschrieben.\n\nExample: Ein Token entfernen\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nLädt die Präferenzen beim Start.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)`, die die gespeicherten Präferenzen erhält. |\n\nDer Standard-Delegate liest `databases/preferences.json` und ruft `next(object)` auf. Ersetze ihn, um die Präferenzen woanders zu halten; rufe `next(object)` mit den gespeicherten Werten auf, oder `next()`, wenn es keine gibt. Weise ihn in einer Definitionsdatei zu: Ändert sich der Delegate, während die App startet, lädt Total.js die Präferenzen mit dem neuen erneut.\n\nExample: Präferenzen in einer Datenbanktabelle\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nSpeichert die Präferenzen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Alle Präferenzen. |\n\nWird eine Sekunde nach der letzten Änderung einer Präferenz mit einem Objekt aller Präferenzen aufgerufen. Der Standard-Delegate schreibt es als formatiertes JSON nach `databases/preferences.json`. Ersetze ihn zusammen mit `DEF.onPrefLoad`.\n\nExample: Jedes Speichern protokollieren\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nGibt einen Zähler zurück, der tägliche Statistiken führt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Zählers. |\n\nReturns: `Counter` Die Zähler-Instanz.\n\nDie Daten werden in `databases/{name}.counter` als NoSQL-Dokumente gespeichert, eines pro ID und Tag: `{ id, sum, min, max, day, month, year, ts, date }`, wobei `ts` das Datum als Zahl `yyyyMMdd` ist. Die Instanz wird beim ersten Aufruf erstellt und danach wiederverwendet.\n\n`hit()` sammelt Werte im Speicher. Bei jedem fünften `service`-Event (etwa alle fünf Minuten) schreibt der Zähler sie in die Datei. Noch nicht geschriebene Werte gehen verloren, wenn der Prozess stoppt.\n\nDie Lesemethoden geben einen NoSQL-Query-Builder zurück: Übergib den Callback als letztes Argument oder rufe `.callback()` auf dem Ergebnis auf.\n\nExample: Besuche zählen\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nAddiert einen Wert zum heutigen Zähler.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Was du zählst, zum Beispiel eine Seite oder ein Produkt. |\n| `value` | `Number` | no | `1` | Der zu addierende Wert. |\n\nReturns: `Counter` Der Zähler, zum Verketten.\n\nDer Wert wird zur Summe von `id` für den aktuellen Tag addiert. Der Zähler speichert außerdem den kleinsten und den größten Einzelwert als `min` und `max`.\n\nExample: Einen Betrag zählen\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nSchreibt die gesammelten Werte jetzt in die Datei.\n\nReturns: `Counter` Der Zähler, zum Verketten.\n\nDer Zähler ruft es periodisch auf. Rufe es vor einem geplanten Stopp selbst auf, damit keine Aufrufe verloren gehen.\n\nExample: Vor dem Beenden schreiben\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nGibt die Gesamtsumme aller gespeicherten Werte zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Eine ID oder ein Array von IDs. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nSummiert das Feld `sum` aller Tage, für eine `id` oder ein Array von IDs, oder für alle IDs. Noch nicht geschriebene Werte sind nicht enthalten.\n\nExample: Besuche insgesamt\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nGibt die gespeicherten Tage einer ID zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Zählers. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nJedes Element ist ein gespeichertes Dokument ohne `id`: `{ sum, min, max, day, month, year, ts, date }`. Du kannst dem zurückgegebenen Builder Bedingungen, Sortierung und Paginierung hinzufügen.\n\nExample: Die letzten 30 Tage\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nGibt die Werte einer ID nach Monat gruppiert zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Zählers. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nJedes Element ist `{ date, year, month, ts, sum, min, max, count }`, wobei `date` der Monat als Text `yyyyMM` ist, `ts` derselbe Wert als Zahl und `count` die Anzahl der gespeicherten Tage.\n\nExample: Monatliche Verkäufe\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nGibt die Werte einer ID nach Jahr gruppiert zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Die ID des Zählers. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nJedes Element ist `{ date, year, ts, sum, min, max, count }`, wobei `date` das Jahr als Text ist und `count` die Anzahl der gespeicherten Tage.\n\nExample: Jährliche Besuche\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nGibt Summen aller IDs zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` oder `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nOhne `type` erhältst du ein Element pro ID: `{ id, sum, min, max, count }`. Mit `'monthly'` oder `'yearly'` erhältst du ein Element pro ID und Monat bzw. Jahr, ergänzt um die Felder `ts`, `date`, `year` und (bei Monaten) `month`.\n\nExample: Meistbesuchte Seiten\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nGibt einen Query-Builder über die gespeicherten Dokumente zurück.\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nNutze ihn für Berichte, die die anderen Methoden nicht abdecken. Die Dokumente haben die Felder `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` und `date`.\n\nExample: Ein Monat aller IDs\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nEntfernt gespeicherte Dokumente einer ID oder alle.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | Die ID des Zählers. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` Der Query-Builder.\n\nOhne `id` wird jedes gespeicherte Dokument entfernt. Noch nicht geschriebene Werte bleiben im Speicher.\n\nExample: Eine ID entfernen\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nEntfernt alle gespeicherten Daten des Zählers.\n\nReturns: `Counter` Der Zähler, zum Verketten.\n\nLeert die Datei. Noch nicht geschriebene Werte bleiben im Speicher.\n\nExample: Statistiken zurücksetzen\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nGibt eine NoSQL-Datenbank zurück, die ihre Dokumente im Speicher hält.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Datenbank. |\n\nReturns: `Database` Die Datenbank-Instanz.\n\nAlle Dokumente werden bei der ersten Operation aus `databases/{name}.inmemory` geladen und im Speicher gehalten. Nach einer Änderung wird die Datei innerhalb von 5 Sekunden geschrieben. Die Instanz wird beim ersten Aufruf erstellt und danach wiederverwendet.\n\nSie unterstützt `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` und `remove()` mit dem Query-Builder von `NOSQL()`. Halte die Collection klein: Jedes Dokument liegt im Speicher.\n\nExample: Eine Liste der Online-Benutzer\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nGibt eine NoSQL-Datenbank zurück, die in mehreren Dateien eines Ordners gespeichert ist.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name der Datenbank oder `~` gefolgt von einem absoluten Pfad zum Ordner. |\n\nReturns: `Database` Die Datenbank-Instanz.\n\nDie Dokumente werden im Ordner `databases/textdb-{name}/` gespeichert. Neue Dokumente gehen in eine Datei, bis sie etwa 512 kB hat, dann wird eine neue Datei begonnen. Die Methoden und der Query-Builder sind dieselben wie bei `NOSQL()`. Ein Name, der mit `~` beginnt, ist ein absoluter Pfad zum Ordner; eine solche Instanz wird nicht gecacht.\n\nExample: Protokoll von Events\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nPackt die Dateien eines Ordners in eine Sicherungsdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Der Pfad der Sicherungsdatei oder ein beschreibbarer Stream. |\n| `path` | `String|Array` | yes |  | Ein Ordner oder ein Array von Pfaden relativ zum Stammverzeichnis der App. |\n| `callback` | `Function` | no |  | `function(err, meta)`, wobei `meta` `{ filename, files, size }` ist. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`, die `true` zurückgibt, um den Eintrag aufzunehmen. |\n\n`path` ist ein Ordner: Alle seine Dateien und Unterordner werden gepackt. Es kann auch ein Array von Pfaden relativ zum Stammverzeichnis der App sein. Eine vorhandene Sicherungsdatei wird ersetzt. Jede Datei wird mit GZIP komprimiert und als Base64 in einer Zeile nach ihrem relativen Pfad gespeichert.\n\nDie Funktion `filter(path, isdirectory)` erhält einen relativen Pfad, der mit `/` beginnt (Ordner enden mit `/`). Gib `true` zurück, um den Eintrag aufzunehmen. Sockets werden übersprungen.\n\nExample: Hochgeladene Dateien sichern\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nEntpackt eine mit BACKUP() erstellte Sicherungsdatei in einen Ordner.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Der Pfad der Sicherungsdatei oder ein lesbarer Stream. |\n| `target` | `String` | yes |  | Der Ordner, in den die Dateien geschrieben werden. |\n| `callback` | `Function` | no |  | `function(err, meta)`, wobei `meta` `{ files, size, path }` ist. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nNicht vorhandene Ordner werden erstellt. Vorhandene Dateien mit demselben Namen werden überschrieben.\n\nDie Funktion `filter(path, isdirectory)` erhält den relativen Pfad aus der Sicherung. Gib für eine Datei `false` zurück, um sie zu überspringen, einen neuen relativen Pfad (in einem vorhandenen Ordner), um sie woanders zu schreiben, oder nichts, um sie zu behalten. Gib für einen Ordner `false` zurück, um ihn nicht zu erstellen.\n\nExample: Hochgeladene Dateien wiederherstellen\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdps3Ul61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Caché, contadores y almacenes pequeños","summary":"Referencia de CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() y RESTORE().","markdown":"---\ntitle: \"Caché, contadores y almacenes pequeños\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Caché, contadores y almacenes pequeños\n\n> Referencia de CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() y RESTORE().\n\nFunciones globales para pequeñas cantidades de datos: la caché en memoria (`CACHE()` y `F.cache`), cachés en archivo, preferencias, objetos persistentes, contadores, dos almacenes NoSQL adicionales y copias de seguridad de carpetas. En esta referencia, `counter` es una instancia devuelta por `COUNTER()`. La guía [Caché, contadores y almacenes pequeños](../../guides/caching-and-small-stores/) explica cómo usarlos con ejemplos.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nLee o guarda un valor en la caché en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `value` | `Object` | no |  | El valor a guardar. Omítelo para leer. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un texto como `'5 minutes'` o `'1 hour'`, o un `Date`. Sin él, el valor caduca en 5 minutos. |\n\nReturns: `Object` El valor cacheado.\n\nCon un argumento, la función devuelve el valor cacheado, o `undefined` cuando la clave no existe o ha caducado. Con más argumentos, guarda el valor y lo devuelve. Es una forma corta de `F.cache.get2()` y `F.cache.set()`.\n\nLa caché vive en la memoria del proceso y está vacía tras un reinicio (salvo que `allow_cache_snapshot` esté activado).\n\nExample: Cachear una lista\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nLa caché en memoria de la aplicación.\n\nReturns: `Object` La instancia de la caché.\n\nEl objeto que hay detrás de `CACHE()`. Sus elementos están en `F.cache.items`, un objeto donde cada clave contiene `{ value, expire }`. Una vez por minuto, Total.js elimina los elementos caducados y emite `cache_expired` para cada uno.\n\nExample: Contar las claves cacheadas\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nGuarda un valor en la caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `value` | `Object` | yes |  | El valor a guardar. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un texto como `'5 minutes'` o `'1 hour'`, o un `Date`. Sin él, el valor caduca en 5 minutos. |\n\nReturns: `Object` El valor guardado.\n\nReemplaza un valor existente con la misma clave y emite el evento `cache_set`. `F.cache.add()` es el mismo método. Con `allow_cache_cluster`, el valor se envía a los otros procesos del clúster.\n\nExample: Guardar durante una hora\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nLee un valor de la caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `def` | `Object` | no | `undefined` | El valor que se devuelve cuando no hay nada en caché. |\n\nReturns: `Object` El valor cacheado o `def`.\n\nDevuelve `def` cuando la clave no existe o el valor ha caducado. Un valor caducado se elimina y se emite el evento `cache_expired`. `F.cache.read()` es el mismo método.\n\nExample: Leer con un valor por defecto\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nLee un valor de la caché sin actualizar la hora actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `def` | `Object` | no | `undefined` | El valor que se devuelve cuando no hay nada en caché. |\n\nReturns: `Object` El valor cacheado o `def`.\n\nFunciona como `F.cache.get()`, pero compara la caducidad con la global `NOW`, que Total.js actualiza periódicamente, en lugar de con un nuevo `Date`. Es algo más rápido y un elemento puede seguir siendo válido unos segundos más. `CACHE(key)` lo usa. `F.cache.read2()` es el mismo método.\n\nExample: Leer\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nElimina un valor de la caché.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n\nReturns: `Object` El elemento eliminado `{ value, expire }`, o `undefined`.\n\nCon `allow_cache_cluster`, la eliminación se envía a los otros procesos del clúster.\n\nExample: Eliminar tras una actualización\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nElimina todos los valores cuya clave contiene un texto o coincide con una expresión regular.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | Una parte de la clave, o una expresión regular. |\n\nReturns: `Number` El número de elementos eliminados.\n\nUn texto elimina todas las claves que lo contienen; un `RegExp` elimina todas las claves con las que coincide. Para eliminarlo todo usa `F.cache.clear()`. `F.cache.reset()` es el mismo método.\n\nExample: Eliminar por prefijo\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nElimina todos los valores de la caché.\n\nReturns: `Object` La caché, para encadenar.\n\nCon `allow_cache_cluster`, también se vacían los otros procesos del clúster.\n\nExample: Vaciar la caché\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nCambia la caducidad de un valor cacheado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `expire` | `String|Date` | yes |  | Un texto como `'1 hour'`, o un `Date`. |\n\nReturns: `Object` La caché, para encadenar.\n\nNo hace nada cuando la clave no existe.\n\nExample: Prolongar una sesión\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nDevuelve un valor cacheado o lo crea con una función.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clave del valor. |\n| `maker` | `Function` | yes |  | `function(next, options)` que crea el valor y llama a `next(value, [expire])`. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | Cualquier objeto, que se pasa a ambas funciones. |\n\nReturns: `Object` La caché, para encadenar.\n\nCuando la clave contiene un valor, se llama de inmediato a `callback(value, true, options)`. Si no, se ejecuta `maker(next, options)`; llama a `next(value, [expire])` para cachear el valor, y después se llama a `callback(value, false, options)`. Un valor falsy (`false`, `0`, `''`, `null`) no se considera cacheado.\n\nExample: Cachear una consulta\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nDevuelve un valor cacheado en un archivo, o lo crea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El identificador del valor cacheado. |\n| `expire` | `String` | yes |  | Cuánto tiempo es válido el archivo, por ejemplo `'1 hour'` o `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` que crea el valor y llama a `next(err, value, [load])`. |\n| `encoding` | `String` | no | `'json'` | `'json'`, o la codificación de un valor de texto como `'utf8'`. |\n\nEl valor se guarda en la carpeta `tmp/` en un archivo cuyo nombre es un hash de `id`. Cuando el archivo no existe o es más antiguo que `expire`, se ejecuta `maker(next, id)`. Llama a `next(err, value, [load])`: sin error, el valor se escribe en el archivo, y se llama a `callback(err, value)` salvo que `load` sea `false`. Si no, se lee el archivo y se pasa a `callback(err, value)`.\n\nPor defecto, el valor se guarda como JSON y se vuelve a parsear (fechas incluidas). Con otro `encoding`, por ejemplo `'utf8'`, el valor se escribe tal cual y se lee como texto.\n\nExample: Cachear un archivo remoto durante un día\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nDevuelve un objeto que se guarda en un archivo JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | El nombre del archivo. |\n| `delay` | `Number` | no | `10000` | Milisegundos entre `save()` y la escritura. |\n| `skip` | `String|Array` | no |  | Claves que no se escriben en el archivo, como array o como texto separado por comas. |\n\nReturns: `Object` El objeto guardado con un método `save()`.\n\nLee `databases/memorize_{name}.json` (o `databases/memorize.json` sin nombre) de forma síncrona y devuelve su contenido como un objeto, o un objeto vacío cuando el archivo no existe. El objeto tiene un método `save()` que lo vuelve a escribir.\n\nCada llamada vuelve a leer el archivo y devuelve un objeto nuevo, así que llámala una vez y conserva la referencia. Los argumentos `delay` y `skip` se pueden pasar en cualquier orden. La carpeta `databases` debe existir.\n\nExample: Recordar la última ejecución\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nEscribe el objeto de MEMORIZE() en su archivo.\n\nLa escritura se hace tras el retardo indicado a `MEMORIZE()` (10 segundos por defecto). Otro `save()` dentro de ese tiempo reinicia el retardo, así que una ráfaga de cambios da una sola escritura. El objeto se escribe como JSON formateado; las funciones y las claves de `skip` se dejan fuera.\n\nExample: Guardar tras un cambio\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPreferencias de la aplicación que se guardan en un archivo.\n\nReturns: `Object` Las preferencias.\n\nTotal.js carga `databases/preferences.json` al arrancar y copia cada valor a `PREF`, así que lees una preferencia como una propiedad: `PREF.token`. En un hilo, el archivo es `databases/preferences_{thread}.json`. Cambia los valores solo con `PREF.set()`, `PREF.inc()` y `PREF.rem()`; un valor asignado directamente no se guarda. No uses los nombres `set`, `inc` y `rem`.\n\nExample: Leer una preferencia\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nGuarda una preferencia o la lee.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la preferencia. |\n| `value` | `Object` | no |  | El nuevo valor, o `null` para eliminarla. |\n\nReturns: `Object` El valor.\n\nSin `value`, la función devuelve el valor actual. Con un valor, lo guarda en `PREF` y escribe todas las preferencias un segundo después del último cambio (a través de `DEF.onPrefSave`). `null` elimina la preferencia, como `PREF.rem()`.\n\nExample: Guardar un token\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nSuma un número a una preferencia.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la preferencia. |\n| `value` | `Number` | no | `1` | El número a sumar. |\n\nReturns: `Number` El nuevo valor.\n\nEmpieza desde `value` cuando la preferencia no existe. El resultado se guarda como con `PREF.set()`.\n\nExample: Contar importaciones\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nElimina una preferencia del archivo guardado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la preferencia. |\n\nLa preferencia se elimina de `PREF` y el archivo se vuelve a escribir.\n\nExample: Eliminar un token\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nCarga las preferencias al arrancar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)` que recibe las preferencias guardadas. |\n\nEl delegado por defecto lee `databases/preferences.json` y llama a `next(object)`. Reemplázalo para guardar las preferencias en otro sitio; llama a `next(object)` con los valores guardados, o a `next()` cuando no hay ninguno. Asígnalo en un archivo de definición: cuando el delegado cambia mientras arranca la aplicación, Total.js vuelve a cargar las preferencias con el nuevo.\n\nExample: Preferencias en una tabla de base de datos\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nGuarda las preferencias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Todas las preferencias. |\n\nSe llama un segundo después del último cambio de una preferencia, con un objeto con todas las preferencias. El delegado por defecto lo escribe como JSON formateado en `databases/preferences.json`. Reemplázalo junto con `DEF.onPrefLoad`.\n\nExample: Registrar cada guardado\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nDevuelve un contador que mantiene estadísticas diarias.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del contador. |\n\nReturns: `Counter` La instancia del contador.\n\nLos datos se guardan en `databases/{name}.counter` como documentos NoSQL, uno por id y día: `{ id, sum, min, max, day, month, year, ts, date }`, donde `ts` es la fecha como número `yyyyMMdd`. La instancia se crea en la primera llamada y después se reutiliza.\n\n`hit()` reúne valores en memoria. En cada quinto evento `service` (aproximadamente cada cinco minutos), el contador los escribe en el archivo. Los valores que aún no se han escrito se pierden cuando el proceso se detiene.\n\nLos métodos de lectura devuelven un query builder de NoSQL: pasa el callback como último argumento o llama a `.callback()` sobre el resultado.\n\nExample: Contar visitas\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nSuma un valor al contador de hoy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Lo que cuentas, por ejemplo una página o un producto. |\n| `value` | `Number` | no | `1` | El valor a sumar. |\n\nReturns: `Counter` El contador, para encadenar.\n\nEl valor se suma a la suma de `id` del día actual. El contador también guarda el valor individual más pequeño y el más grande como `min` y `max`.\n\nExample: Contar un importe\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nEscribe ahora en el archivo los valores reunidos.\n\nReturns: `Counter` El contador, para encadenar.\n\nEl contador lo llama periódicamente. Llámalo tú antes de una parada planificada para no perder visitas.\n\nExample: Volcar antes de salir\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nDevuelve la suma total de todos los valores guardados.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un id o un array de ids. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nSuma el campo `sum` de todos los días, para un `id` o un array de ids, o para todos los ids. Los valores que aún no se han volcado no se incluyen.\n\nExample: Visitas totales\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nDevuelve los días guardados de un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del contador. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nCada elemento es un documento guardado sin `id`: `{ sum, min, max, day, month, year, ts, date }`. Puedes añadir condiciones, orden y paginación al builder devuelto.\n\nExample: Los últimos 30 días\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nDevuelve los valores de un id agrupados por mes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del contador. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nCada elemento es `{ date, year, month, ts, sum, min, max, count }`, donde `date` es el mes como texto `yyyyMM`, `ts` lo mismo como número y `count` el número de días guardados.\n\nExample: Ventas mensuales\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nDevuelve los valores de un id agrupados por año.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | El id del contador. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nCada elemento es `{ date, year, ts, sum, min, max, count }`, donde `date` es el año como texto y `count` el número de días guardados.\n\nExample: Visitas anuales\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nDevuelve los totales de todos los ids.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` o `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nSin `type` obtienes un elemento por id: `{ id, sum, min, max, count }`. Con `'monthly'` o `'yearly'` obtienes un elemento por id y mes o año, con los campos `ts`, `date`, `year` y (para los meses) `month` añadidos.\n\nExample: Páginas principales\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nDevuelve un query builder sobre los documentos guardados.\n\nReturns: `QueryBuilder` El query builder.\n\nÚsalo para informes que los otros métodos no cubren. Los documentos tienen los campos `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` y `date`.\n\nExample: Un mes de todos los ids\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nElimina los documentos guardados de un id, o todos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | El id del contador. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` El query builder.\n\nSin `id` se eliminan todos los documentos guardados. Los valores que aún no se han volcado permanecen en memoria.\n\nExample: Eliminar un id\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nElimina todos los datos guardados del contador.\n\nReturns: `Counter` El contador, para encadenar.\n\nVacía el archivo. Los valores que aún no se han volcado permanecen en memoria.\n\nExample: Reiniciar las estadísticas\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nDevuelve una base de datos NoSQL que mantiene sus documentos en memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la base de datos. |\n\nReturns: `Database` La instancia de la base de datos.\n\nTodos los documentos se cargan desde `databases/{name}.inmemory` en la primera operación y se mantienen en memoria. Tras un cambio, el archivo se escribe en 5 segundos. La instancia se crea en la primera llamada y después se reutiliza.\n\nAdmite `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` y `remove()` con el query builder de `NOSQL()`. Mantén la colección pequeña: cada documento está en memoria.\n\nExample: Una lista de usuarios conectados\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nDevuelve una base de datos NoSQL guardada en varios archivos de una carpeta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre de la base de datos, o `~` seguido de una ruta absoluta a la carpeta. |\n\nReturns: `Database` La instancia de la base de datos.\n\nLos documentos se guardan en la carpeta `databases/textdb-{name}/`. Los documentos nuevos van a un archivo hasta que tiene unos 512 kB; después se empieza un archivo nuevo. Los métodos y el query builder son los mismos que en `NOSQL()`. Un nombre que empieza por `~` es una ruta absoluta a la carpeta; una instancia así no se cachea.\n\nExample: Registro de eventos\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nEmpaqueta los archivos de una carpeta en un único archivo de copia de seguridad.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | La ruta del archivo de copia de seguridad, o un stream de escritura. |\n| `path` | `String|Array` | yes |  | Una carpeta, o un array de rutas relativas a la raíz de la aplicación. |\n| `callback` | `Function` | no |  | `function(err, meta)` donde `meta` es `{ filename, files, size }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)` que devuelve `true` para incluir el elemento. |\n\n`path` es una carpeta: se empaquetan todos sus archivos y subcarpetas. También puede ser un array de rutas relativas a la raíz de la aplicación. Un archivo de copia de seguridad existente se reemplaza. Cada archivo se comprime con GZIP y se guarda como Base64 en una línea, tras su ruta relativa.\n\nLa función `filter(path, isdirectory)` recibe una ruta relativa que empieza por `/` (las carpetas terminan en `/`). Devuelve `true` para incluir el elemento. Los sockets se omiten.\n\nExample: Copia de seguridad de los archivos subidos\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nDesempaqueta en una carpeta un archivo de copia de seguridad creado por BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | La ruta del archivo de copia de seguridad, o un stream de lectura. |\n| `target` | `String` | yes |  | La carpeta donde se escriben los archivos. |\n| `callback` | `Function` | no |  | `function(err, meta)` donde `meta` es `{ files, size, path }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nLas carpetas que no existen se crean. Los archivos existentes con el mismo nombre se sobrescriben.\n\nLa función `filter(path, isdirectory)` recibe la ruta relativa de la copia de seguridad. Para un archivo, devuelve `false` para omitirlo, una nueva ruta relativa (en una carpeta existente) para escribirlo en otro sitio, o nada para conservarlo. Para una carpeta, devuelve `false` para no crearla.\n\nExample: Restaurar los archivos subidos\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdps3Ul61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Cache, compteurs et petits stockages","summary":"Référence de CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() et RESTORE().","markdown":"---\ntitle: Cache, compteurs et petits stockages\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, compteurs et petits stockages\n\n> Référence de CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() et RESTORE().\n\nFonctions globales pour de petites quantités de données : le cache en mémoire (`CACHE()` et `F.cache`), les caches de fichiers, les préférences, les objets persistants, les compteurs, deux stockages NoSQL supplémentaires et les sauvegardes de dossiers. Dans cette référence, `counter` est une instance renvoyée par `COUNTER()`. Le guide [Cache, compteurs et petits stockages](../../guides/caching-and-small-stores/) explique comment les utiliser avec des exemples.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nLit ou enregistre une valeur dans le cache en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `value` | `Object` | no |  | La valeur à enregistrer. Omets-la pour lire. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un texte tel que `'5 minutes'` ou `'1 hour'`, ou une `Date`. Sans elle, la valeur expire au bout de 5 minutes. |\n\nReturns: `Object` La valeur en cache.\n\nAvec un seul argument, la fonction renvoie la valeur en cache, ou `undefined` lorsque la clé n'existe pas ou a expiré. Avec plus d'arguments, elle enregistre la valeur et la renvoie. C'est une forme courte de `F.cache.get2()` et `F.cache.set()`.\n\nLe cache réside dans la mémoire du processus et il est vide après un redémarrage (sauf si `allow_cache_snapshot` est activé).\n\nExample: Mettre une liste en cache\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nLe cache en mémoire de l'application.\n\nReturns: `Object` L'instance du cache.\n\nL'objet derrière `CACHE()`. Ses éléments se trouvent dans `F.cache.items`, un objet où chaque clé contient `{ value, expire }`. Une fois par minute, Total.js supprime les éléments expirés et émet `cache_expired` pour chacun d'eux.\n\nExample: Compter les clés en cache\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nEnregistre une valeur dans le cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `value` | `Object` | yes |  | La valeur à enregistrer. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un texte tel que `'5 minutes'` ou `'1 hour'`, ou une `Date`. Sans elle, la valeur expire au bout de 5 minutes. |\n\nReturns: `Object` La valeur enregistrée.\n\nRemplace une valeur existante ayant la même clé et émet l'événement `cache_set`. `F.cache.add()` est la même méthode. Avec `allow_cache_cluster`, la valeur est envoyée aux autres processus du cluster.\n\nExample: Enregistrer pour une heure\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nLit une valeur depuis le cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `def` | `Object` | no | `undefined` | La valeur à renvoyer lorsque rien n'est en cache. |\n\nReturns: `Object` La valeur en cache ou `def`.\n\nRenvoie `def` lorsque la clé n'existe pas ou que la valeur a expiré. Une valeur expirée est supprimée et l'événement `cache_expired` est émis. `F.cache.read()` est la même méthode.\n\nExample: Lire avec une valeur par défaut\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nLit une valeur depuis le cache sans mettre à jour l'heure courante.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `def` | `Object` | no | `undefined` | La valeur à renvoyer lorsque rien n'est en cache. |\n\nReturns: `Object` La valeur en cache ou `def`.\n\nFonctionne comme `F.cache.get()`, mais compare l'expiration avec la variable globale `NOW`, que Total.js met à jour périodiquement, au lieu d'une nouvelle `Date`. C'est un peu plus rapide et un élément peut rester valide quelques secondes de plus. `CACHE(key)` l'utilise. `F.cache.read2()` est la même méthode.\n\nExample: Lire\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nSupprime une valeur du cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n\nReturns: `Object` L'élément supprimé `{ value, expire }`, ou `undefined`.\n\nAvec `allow_cache_cluster`, la suppression est envoyée aux autres processus du cluster.\n\nExample: Supprimer après une mise à jour\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nSupprime toutes les valeurs dont la clé contient un texte ou correspond à une expression régulière.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | Une partie de la clé, ou une expression régulière. |\n\nReturns: `Number` Le nombre d'éléments supprimés.\n\nUn texte supprime toutes les clés qui le contiennent ; une `RegExp` supprime toutes les clés qu'elle reconnaît. Pour tout supprimer, utilise `F.cache.clear()`. `F.cache.reset()` est la même méthode.\n\nExample: Supprimer par préfixe\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nSupprime toutes les valeurs du cache.\n\nReturns: `Object` Le cache, pour le chaînage.\n\nAvec `allow_cache_cluster`, les autres processus du cluster sont aussi vidés.\n\nExample: Vider le cache\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nModifie l'expiration d'une valeur en cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `expire` | `String|Date` | yes |  | Un texte tel que `'1 hour'`, ou une `Date`. |\n\nReturns: `Object` Le cache, pour le chaînage.\n\nNe fait rien lorsque la clé n'existe pas.\n\nExample: Prolonger une session\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nRenvoie une valeur en cache ou la crée avec une fonction.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La clé de la valeur. |\n| `maker` | `Function` | yes |  | `function(next, options)` qui crée la valeur et appelle `next(value, [expire])`. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | N'importe quel objet, transmis aux deux fonctions. |\n\nReturns: `Object` Le cache, pour le chaînage.\n\nLorsque la clé contient une valeur, `callback(value, true, options)` est appelée immédiatement. Sinon, `maker(next, options)` s'exécute ; appelle `next(value, [expire])` pour mettre la valeur en cache, puis `callback(value, false, options)` est appelée. Une valeur falsy (`false`, `0`, `''`, `null`) n'est pas considérée comme en cache.\n\nExample: Mettre une requête en cache\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nRenvoie une valeur mise en cache dans un fichier, ou la crée.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identifiant de la valeur en cache. |\n| `expire` | `String` | yes |  | La durée de validité du fichier, par exemple `'1 hour'` ou `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` qui crée la valeur et appelle `next(err, value, [load])`. |\n| `encoding` | `String` | no | `'json'` | `'json'`, ou l'encodage d'une valeur texte tel que `'utf8'`. |\n\nLa valeur est stockée dans le dossier `tmp/`, dans un fichier nommé d'après un hash de `id`. Lorsque le fichier n'existe pas ou est plus ancien que `expire`, `maker(next, id)` s'exécute. Appelle `next(err, value, [load])` : sans erreur, la valeur est écrite dans le fichier, et `callback(err, value)` est appelée sauf si `load` vaut `false`. Sinon, le fichier est lu et transmis à `callback(err, value)`.\n\nPar défaut, la valeur est enregistrée en JSON puis analysée à la lecture (dates comprises). Avec un autre `encoding`, par exemple `'utf8'`, la valeur est écrite telle quelle et lue comme un texte.\n\nExample: Mettre un fichier distant en cache pour une journée\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nRenvoie un objet enregistré dans un fichier JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | Le nom du fichier. |\n| `delay` | `Number` | no | `10000` | Millisecondes entre `save()` et l'écriture. |\n| `skip` | `String|Array` | no |  | Clés qui ne sont pas écrites dans le fichier, sous forme de tableau ou de texte séparé par des virgules. |\n\nReturns: `Object` L'objet stocké avec une méthode `save()`.\n\nLit `databases/memorize_{name}.json` (ou `databases/memorize.json` sans nom) de manière synchrone et renvoie son contenu sous forme d'objet, ou un objet vide lorsque le fichier n'existe pas. L'objet possède une méthode `save()` qui le réécrit.\n\nChaque appel relit le fichier et renvoie un nouvel objet ; appelle-la donc une seule fois et conserve la référence. Les arguments `delay` et `skip` peuvent être passés dans n'importe quel ordre. Le dossier `databases` doit exister.\n\nExample: Mémoriser la dernière exécution\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nÉcrit l'objet de MEMORIZE() dans son fichier.\n\nL'écriture a lieu après le délai donné à `MEMORIZE()` (10 secondes par défaut). Un autre `save()` pendant ce délai le relance ; une rafale de modifications donne donc une seule écriture. L'objet est écrit en JSON formaté ; les fonctions et les clés de `skip` sont exclues.\n\nExample: Enregistrer après une modification\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPréférences de l'application enregistrées dans un fichier.\n\nReturns: `Object` Les préférences.\n\nTotal.js charge `databases/preferences.json` au démarrage et copie chaque valeur dans `PREF` ; tu lis donc une préférence comme une propriété : `PREF.token`. Dans un thread, le fichier est `databases/preferences_{thread}.json`. Modifie les valeurs uniquement avec `PREF.set()`, `PREF.inc()` et `PREF.rem()` ; une valeur assignée directement n'est pas enregistrée. N'utilise pas les noms `set`, `inc` et `rem`.\n\nExample: Lire une préférence\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nEnregistre une préférence ou la lit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la préférence. |\n| `value` | `Object` | no |  | La nouvelle valeur, ou `null` pour la supprimer. |\n\nReturns: `Object` La valeur.\n\nSans `value`, la fonction renvoie la valeur actuelle. Avec une valeur, elle l'enregistre dans `PREF` et écrit toutes les préférences une seconde après la dernière modification (via `DEF.onPrefSave`). `null` supprime la préférence, comme `PREF.rem()`.\n\nExample: Enregistrer un jeton\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nAjoute un nombre à une préférence.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la préférence. |\n| `value` | `Number` | no | `1` | Le nombre à ajouter. |\n\nReturns: `Number` La nouvelle valeur.\n\nPart de `value` lorsque la préférence n'existe pas. Le résultat est enregistré comme avec `PREF.set()`.\n\nExample: Compter les imports\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nSupprime une préférence du fichier enregistré.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la préférence. |\n\nLa préférence est supprimée de `PREF` et le fichier est réécrit.\n\nExample: Supprimer un jeton\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nCharge les préférences au démarrage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)` qui reçoit les préférences stockées. |\n\nLe délégué par défaut lit `databases/preferences.json` et appelle `next(object)`. Remplace-le pour conserver les préférences ailleurs ; appelle `next(object)` avec les valeurs stockées, ou `next()` s'il n'y en a aucune. Assigne-le dans un fichier de définition : lorsque le délégué change pendant le démarrage de l'application, Total.js recharge les préférences avec le nouveau.\n\nExample: Préférences dans une table de base de données\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nEnregistre les préférences.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Toutes les préférences. |\n\nAppelé une seconde après la dernière modification d'une préférence, avec un objet contenant toutes les préférences. Le délégué par défaut l'écrit en JSON formaté dans `databases/preferences.json`. Remplace-le en même temps que `DEF.onPrefLoad`.\n\nExample: Journaliser chaque enregistrement\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nRenvoie un compteur qui conserve des statistiques quotidiennes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du compteur. |\n\nReturns: `Counter` L'instance du compteur.\n\nLes données sont stockées dans `databases/{name}.counter` sous forme de documents NoSQL, un par id et par jour : `{ id, sum, min, max, day, month, year, ts, date }`, où `ts` est la date sous forme de nombre `yyyyMMdd`. L'instance est créée au premier appel puis réutilisée.\n\n`hit()` collecte les valeurs en mémoire. À chaque cinquième événement `service` (environ toutes les cinq minutes), le compteur les écrit dans le fichier. Les valeurs non encore écrites sont perdues lorsque le processus s'arrête.\n\nLes méthodes de lecture renvoient un query builder NoSQL : passe le callback comme dernier argument ou appelle `.callback()` sur le résultat.\n\nExample: Compter les visites\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nAjoute une valeur au compteur du jour.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Ce que tu comptes, par exemple une page ou un produit. |\n| `value` | `Number` | no | `1` | La valeur à ajouter. |\n\nReturns: `Counter` Le compteur, pour le chaînage.\n\nLa valeur est ajoutée à la somme de `id` pour le jour en cours. Le compteur conserve aussi la plus petite et la plus grande valeur individuelle sous `min` et `max`.\n\nExample: Compter un montant\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nÉcrit immédiatement les valeurs collectées dans le fichier.\n\nReturns: `Counter` Le compteur, pour le chaînage.\n\nLe compteur l'appelle périodiquement. Appelle-la toi-même avant un arrêt planifié afin qu'aucune visite ne soit perdue.\n\nExample: Vider avant la sortie\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nRenvoie la somme totale de toutes les valeurs stockées.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un id ou un tableau d'ids. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nAdditionne le champ `sum` de tous les jours, pour un `id` ou un tableau d'ids, ou pour tous les ids. Les valeurs non encore écrites ne sont pas incluses.\n\nExample: Total des visites\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nRenvoie les jours stockés d'un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du compteur. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nChaque élément est un document stocké sans `id` : `{ sum, min, max, day, month, year, ts, date }`. Tu peux ajouter des conditions, un tri et une pagination au builder renvoyé.\n\nExample: Les 30 derniers jours\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nRenvoie les valeurs d'un id regroupées par mois.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du compteur. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nChaque élément est `{ date, year, month, ts, sum, min, max, count }`, où `date` est le mois sous forme de texte `yyyyMM`, `ts` la même valeur sous forme de nombre et `count` le nombre de jours stockés.\n\nExample: Ventes mensuelles\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nRenvoie les valeurs d'un id regroupées par année.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id du compteur. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nChaque élément est `{ date, year, ts, sum, min, max, count }`, où `date` est l'année sous forme de texte et `count` le nombre de jours stockés.\n\nExample: Visites annuelles\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nRenvoie les totaux de tous les ids.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` ou `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nSans `type`, tu obtiens un élément par id : `{ id, sum, min, max, count }`. Avec `'monthly'` ou `'yearly'`, tu obtiens un élément par id et par mois ou par année, avec les champs `ts`, `date`, `year` et (pour les mois) `month` en plus.\n\nExample: Pages les plus visitées\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nRenvoie un query builder sur les documents stockés.\n\nReturns: `QueryBuilder` Le query builder.\n\nUtilise-le pour les rapports que les autres méthodes ne couvrent pas. Les documents ont les champs `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` et `date`.\n\nExample: Un mois pour tous les ids\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nSupprime les documents stockés d'un id, ou tous.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | L'id du compteur. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` Le query builder.\n\nSans `id`, tous les documents stockés sont supprimés. Les valeurs non encore écrites restent en mémoire.\n\nExample: Supprimer un id\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nSupprime toutes les données stockées du compteur.\n\nReturns: `Counter` Le compteur, pour le chaînage.\n\nVide le fichier. Les valeurs non encore écrites restent en mémoire.\n\nExample: Réinitialiser les statistiques\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nRenvoie une base de données NoSQL qui conserve ses documents en mémoire.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la base de données. |\n\nReturns: `Database` L'instance de la base de données.\n\nTous les documents sont chargés depuis `databases/{name}.inmemory` lors de la première opération et conservés en mémoire. Après une modification, le fichier est écrit dans les 5 secondes. L'instance est créée au premier appel puis réutilisée.\n\nElle prend en charge `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` et `remove()` avec le query builder de `NOSQL()`. Garde la collection petite : chaque document est en mémoire.\n\nExample: Une liste des utilisateurs en ligne\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nRenvoie une base de données NoSQL stockée dans plusieurs fichiers d'un dossier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de la base de données, ou `~` suivi d'un chemin absolu vers le dossier. |\n\nReturns: `Database` L'instance de la base de données.\n\nLes documents sont stockés dans le dossier `databases/textdb-{name}/`. Les nouveaux documents vont dans un fichier jusqu'à ce qu'il atteigne environ 512 kB, puis un nouveau fichier est créé. Les méthodes et le query builder sont les mêmes que pour `NOSQL()`. Un nom commençant par `~` est un chemin absolu vers le dossier ; une telle instance n'est pas mise en cache.\n\nExample: Journal d'événements\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nRegroupe les fichiers d'un dossier dans un seul fichier de sauvegarde.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Le chemin du fichier de sauvegarde, ou un flux en écriture. |\n| `path` | `String|Array` | yes |  | Un dossier, ou un tableau de chemins relatifs à la racine de l'application. |\n| `callback` | `Function` | no |  | `function(err, meta)` où `meta` vaut `{ filename, files, size }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)` qui renvoie `true` pour inclure l'élément. |\n\n`path` est un dossier : tous ses fichiers et sous-dossiers sont regroupés. Il peut aussi s'agir d'un tableau de chemins relatifs à la racine de l'application. Un fichier de sauvegarde existant est remplacé. Chaque fichier est compressé avec GZIP et stocké en Base64 sur une ligne, après son chemin relatif.\n\nLa fonction `filter(path, isdirectory)` reçoit un chemin relatif qui commence par `/` (les dossiers se terminent par `/`). Renvoie `true` pour inclure l'élément. Les sockets sont ignorés.\n\nExample: Sauvegarder les fichiers téléversés\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nExtrait dans un dossier un fichier de sauvegarde créé par BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Le chemin du fichier de sauvegarde, ou un flux en lecture. |\n| `target` | `String` | yes |  | Le dossier dans lequel les fichiers sont écrits. |\n| `callback` | `Function` | no |  | `function(err, meta)` où `meta` vaut `{ files, size, path }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nLes dossiers qui n'existent pas sont créés. Les fichiers existants portant le même nom sont écrasés.\n\nLa fonction `filter(path, isdirectory)` reçoit le chemin relatif issu de la sauvegarde. Pour un fichier, renvoie `false` pour l'ignorer, un nouveau chemin relatif (dans un dossier existant) pour l'écrire ailleurs, ou rien pour le conserver. Pour un dossier, renvoie `false` pour ne pas le créer.\n\nExample: Restaurer les fichiers téléversés\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdps3Ul61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Cache, counter e piccoli archivi","summary":"Riferimento di CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() e RESTORE().","markdown":"---\ntitle: Cache, counter e piccoli archivi\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, counter e piccoli archivi\n\n> Riferimento di CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() e RESTORE().\n\nFunzioni globali per piccole quantità di dati: la cache in memoria (`CACHE()` e `F.cache`), le cache su file, le preferenze, gli oggetti persistenti, i counter, due archivi NoSQL aggiuntivi e i backup delle cartelle. In questo riferimento `counter` è un'istanza restituita da `COUNTER()`. La guida [Cache, counter e piccoli archivi](../../guides/caching-and-small-stores/) spiega come usarli con degli esempi.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nLegge o salva un valore nella cache in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `value` | `Object` | no |  | Il valore da salvare. Omettilo per leggere. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un testo come `'5 minutes'` o `'1 hour'`, oppure una `Date`. Senza di esso il valore scade dopo 5 minuti. |\n\nReturns: `Object` Il valore in cache.\n\nCon un solo argomento la funzione restituisce il valore in cache, oppure `undefined` quando la chiave non esiste o è scaduta. Con più argomenti salva il valore e lo restituisce. È una forma breve di `F.cache.get2()` e `F.cache.set()`.\n\nLa cache vive nella memoria del processo ed è vuota dopo un riavvio (a meno che `allow_cache_snapshot` non sia attivato).\n\nExample: Mettere in cache una lista\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nLa cache in memoria dell'app.\n\nReturns: `Object` L'istanza della cache.\n\nL'oggetto dietro `CACHE()`. I suoi elementi sono in `F.cache.items`, un oggetto in cui ogni chiave contiene `{ value, expire }`. Una volta al minuto Total.js rimuove gli elementi scaduti ed emette `cache_expired` per ciascuno di essi.\n\nExample: Contare le chiavi in cache\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nSalva un valore nella cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `value` | `Object` | yes |  | Il valore da salvare. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Un testo come `'5 minutes'` o `'1 hour'`, oppure una `Date`. Senza di esso il valore scade dopo 5 minuti. |\n\nReturns: `Object` Il valore salvato.\n\nSostituisce un valore esistente con la stessa chiave ed emette l'evento `cache_set`. `F.cache.add()` è lo stesso metodo. Con `allow_cache_cluster` il valore viene inviato agli altri processi del cluster.\n\nExample: Salvare per un'ora\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nLegge un valore dalla cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `def` | `Object` | no | `undefined` | Il valore da restituire quando non c'è nulla in cache. |\n\nReturns: `Object` Il valore in cache o `def`.\n\nRestituisce `def` quando la chiave non esiste o il valore è scaduto. Un valore scaduto viene rimosso e viene emesso l'evento `cache_expired`. `F.cache.read()` è lo stesso metodo.\n\nExample: Leggere con un valore predefinito\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nLegge un valore dalla cache senza aggiornare l'ora corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `def` | `Object` | no | `undefined` | Il valore da restituire quando non c'è nulla in cache. |\n\nReturns: `Object` Il valore in cache o `def`.\n\nFunziona come `F.cache.get()`, ma confronta la scadenza con la variabile globale `NOW`, che Total.js aggiorna periodicamente, invece che con una nuova `Date`. È un po' più veloce e un elemento può restare valido qualche secondo in più. `CACHE(key)` la usa. `F.cache.read2()` è lo stesso metodo.\n\nExample: Lettura\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nRimuove un valore dalla cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n\nReturns: `Object` L'elemento rimosso `{ value, expire }`, oppure `undefined`.\n\nCon `allow_cache_cluster` la rimozione viene inviata agli altri processi del cluster.\n\nExample: Rimuovere dopo un aggiornamento\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nRimuove tutti i valori la cui chiave contiene un testo o corrisponde a un'espressione regolare.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | Una parte della chiave, o un'espressione regolare. |\n\nReturns: `Number` Il numero di elementi rimossi.\n\nUn testo rimuove ogni chiave che lo contiene; una `RegExp` rimuove ogni chiave che le corrisponde. Per rimuovere tutto usa `F.cache.clear()`. `F.cache.reset()` è lo stesso metodo.\n\nExample: Rimuovere per prefisso\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nRimuove tutti i valori dalla cache.\n\nReturns: `Object` La cache, per concatenare le chiamate.\n\nCon `allow_cache_cluster` vengono svuotati anche gli altri processi del cluster.\n\nExample: Svuotare la cache\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nModifica la scadenza di un valore in cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `expire` | `String|Date` | yes |  | Un testo come `'1 hour'`, oppure una `Date`. |\n\nReturns: `Object` La cache, per concatenare le chiamate.\n\nNon fa nulla quando la chiave non esiste.\n\nExample: Prolungare una sessione\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nRestituisce un valore in cache oppure lo crea con una funzione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | La chiave del valore. |\n| `maker` | `Function` | yes |  | `function(next, options)` che crea il valore e chiama `next(value, [expire])`. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | Qualsiasi oggetto, passato a entrambe le funzioni. |\n\nReturns: `Object` La cache, per concatenare le chiamate.\n\nQuando la chiave contiene un valore, `callback(value, true, options)` viene chiamata subito. Altrimenti viene eseguita `maker(next, options)`; chiama `next(value, [expire])` per mettere in cache il valore, e poi viene chiamata `callback(value, false, options)`. Un valore falsy (`false`, `0`, `''`, `null`) non viene considerato presente in cache.\n\nExample: Mettere in cache una query\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nRestituisce un valore memorizzato in cache in un file, oppure lo crea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'identificatore del valore in cache. |\n| `expire` | `String` | yes |  | Per quanto tempo il file è valido, ad esempio `'1 hour'` o `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)` che crea il valore e chiama `next(err, value, [load])`. |\n| `encoding` | `String` | no | `'json'` | `'json'`, oppure la codifica di un valore testuale come `'utf8'`. |\n\nIl valore viene conservato nella cartella `tmp/` in un file il cui nome deriva da un hash di `id`. Quando il file non esiste o è più vecchio di `expire`, viene eseguita `maker(next, id)`. Chiama `next(err, value, [load])`: senza errore il valore viene scritto nel file, e `callback(err, value)` viene chiamata a meno che `load` non sia `false`. Altrimenti il file viene letto e passato a `callback(err, value)`.\n\nPer impostazione predefinita il valore viene salvato come JSON e reinterpretato in lettura (date comprese). Con un altro `encoding`, ad esempio `'utf8'`, il valore viene scritto così com'è e letto come testo.\n\nExample: Mettere in cache un file remoto per un giorno\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nRestituisce un oggetto che viene salvato in un file JSON.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | Il nome del file. |\n| `delay` | `Number` | no | `10000` | Millisecondi tra `save()` e la scrittura. |\n| `skip` | `String|Array` | no |  | Chiavi che non vengono scritte nel file, come array o come testo separato da virgole. |\n\nReturns: `Object` L'oggetto memorizzato con un metodo `save()`.\n\nLegge in modo sincrono `databases/memorize_{name}.json` (o `databases/memorize.json` senza nome) e ne restituisce il contenuto come oggetto, oppure un oggetto vuoto quando il file non esiste. L'oggetto ha un metodo `save()` che lo riscrive.\n\nOgni chiamata rilegge il file e restituisce un nuovo oggetto, quindi chiamala una volta e conserva il riferimento. Gli argomenti `delay` e `skip` possono essere passati in qualsiasi ordine. La cartella `databases` deve esistere.\n\nExample: Ricordare l'ultima esecuzione\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nScrive l'oggetto di MEMORIZE() nel suo file.\n\nLa scrittura avviene dopo il ritardo passato a `MEMORIZE()` (10 secondi per impostazione predefinita). Un altro `save()` in quel lasso di tempo fa ripartire il ritardo, quindi una raffica di modifiche produce una sola scrittura. L'oggetto viene scritto come JSON formattato; le funzioni e le chiavi in `skip` vengono escluse.\n\nExample: Salvare dopo una modifica\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPreferenze dell'app salvate in un file.\n\nReturns: `Object` Le preferenze.\n\nTotal.js carica `databases/preferences.json` all'avvio e copia ogni valore in `PREF`, quindi leggi una preferenza come proprietà: `PREF.token`. In un thread il file è `databases/preferences_{thread}.json`. Modifica i valori solo con `PREF.set()`, `PREF.inc()` e `PREF.rem()`; un valore assegnato direttamente non viene salvato. Non usare i nomi `set`, `inc` e `rem`.\n\nExample: Leggere una preferenza\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nSalva una preferenza o la legge.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della preferenza. |\n| `value` | `Object` | no |  | Il nuovo valore, oppure `null` per rimuoverla. |\n\nReturns: `Object` Il valore.\n\nSenza `value` la funzione restituisce il valore corrente. Con un valore lo salva in `PREF` e scrive tutte le preferenze un secondo dopo l'ultima modifica (tramite `DEF.onPrefSave`). `null` rimuove la preferenza, come `PREF.rem()`.\n\nExample: Salvare un token\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nAggiunge un numero a una preferenza.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della preferenza. |\n| `value` | `Number` | no | `1` | Il numero da aggiungere. |\n\nReturns: `Number` Il nuovo valore.\n\nParte da `value` quando la preferenza non esiste. Il risultato viene salvato come con `PREF.set()`.\n\nExample: Contare le importazioni\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nRimuove una preferenza dal file salvato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome della preferenza. |\n\nLa preferenza viene rimossa da `PREF` e il file viene riscritto.\n\nExample: Rimuovere un token\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nCarica le preferenze all'avvio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)` che riceve le preferenze memorizzate. |\n\nIl delegato predefinito legge `databases/preferences.json` e chiama `next(object)`. Sostituiscilo per conservare le preferenze altrove; chiama `next(object)` con i valori memorizzati, oppure `next()` quando non ce ne sono. Assegnalo in un file di definizione: quando il delegato cambia mentre l'app si avvia, Total.js ricarica le preferenze con quello nuovo.\n\nExample: Preferenze in una tabella del database\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nSalva le preferenze.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Tutte le preferenze. |\n\nViene chiamato un secondo dopo l'ultima modifica di una preferenza, con un oggetto di tutte le preferenze. Il delegato predefinito lo scrive come JSON formattato in `databases/preferences.json`. Sostituiscilo insieme a `DEF.onPrefLoad`.\n\nExample: Registrare ogni salvataggio\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nRestituisce un counter che tiene statistiche giornaliere.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del counter. |\n\nReturns: `Counter` L'istanza del counter.\n\nI dati vengono conservati in `databases/{name}.counter` come documenti NoSQL, uno per id e giorno: `{ id, sum, min, max, day, month, year, ts, date }`, dove `ts` è la data come numero `yyyyMMdd`. L'istanza viene creata alla prima chiamata e poi riutilizzata.\n\n`hit()` raccoglie i valori in memoria. A ogni quinto evento `service` (circa ogni cinque minuti) il counter li scrive nel file. I valori non ancora scritti vanno persi quando il processo si ferma.\n\nI metodi di lettura restituiscono un query builder NoSQL: passa la callback come ultimo argomento oppure chiama `.callback()` sul risultato.\n\nExample: Contare le visite\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nAggiunge un valore al counter di oggi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Ciò che conti, ad esempio una pagina o un prodotto. |\n| `value` | `Number` | no | `1` | Il valore da aggiungere. |\n\nReturns: `Counter` Il counter, per concatenare le chiamate.\n\nIl valore viene aggiunto alla somma di `id` per il giorno corrente. Il counter tiene anche il valore singolo più piccolo e quello più grande come `min` e `max`.\n\nExample: Contare un importo\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nScrive subito nel file i valori raccolti.\n\nReturns: `Counter` Il counter, per concatenare le chiamate.\n\nIl counter la chiama periodicamente. Chiamala tu prima di un arresto pianificato, così non vanno persi accessi.\n\nExample: Flush prima dell'uscita\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nRestituisce la somma totale di tutti i valori memorizzati.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Un id o un array di id. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nSomma il campo `sum` di tutti i giorni, per un `id` o un array di id, oppure per tutti gli id. I valori non ancora scritti con flush non sono inclusi.\n\nExample: Visite totali\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nRestituisce i giorni memorizzati di un id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nOgni elemento è un documento memorizzato senza `id`: `{ sum, min, max, day, month, year, ts, date }`. Puoi aggiungere condizioni, ordinamento e paginazione al builder restituito.\n\nExample: Gli ultimi 30 giorni\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nRestituisce i valori di un id raggruppati per mese.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nOgni elemento è `{ date, year, month, ts, sum, min, max, count }`, dove `date` è il mese come testo `yyyyMM`, `ts` lo stesso valore come numero e `count` il numero di giorni memorizzati.\n\nExample: Vendite mensili\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nRestituisce i valori di un id raggruppati per anno.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | L'id del counter. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nOgni elemento è `{ date, year, ts, sum, min, max, count }`, dove `date` è l'anno come testo e `count` il numero di giorni memorizzati.\n\nExample: Visite annuali\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nRestituisce i totali di tutti gli id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` o `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nSenza `type` ottieni un elemento per id: `{ id, sum, min, max, count }`. Con `'monthly'` o `'yearly'` ottieni un elemento per id e mese o anno, con l'aggiunta dei campi `ts`, `date`, `year` e (per i mesi) `month`.\n\nExample: Pagine più visitate\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nRestituisce un query builder sui documenti memorizzati.\n\nReturns: `QueryBuilder` Il query builder.\n\nUsalo per i report che gli altri metodi non coprono. I documenti hanno i campi `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` e `date`.\n\nExample: Un mese di tutti gli id\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nRimuove i documenti memorizzati di un id, oppure tutti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | L'id del counter. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` Il query builder.\n\nSenza `id` viene rimosso ogni documento memorizzato. I valori non ancora scritti con flush restano in memoria.\n\nExample: Rimuovere un id\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nRimuove tutti i dati memorizzati del counter.\n\nReturns: `Counter` Il counter, per concatenare le chiamate.\n\nSvuota il file. I valori non ancora scritti con flush restano in memoria.\n\nExample: Azzerare le statistiche\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nRestituisce un database NoSQL che tiene i suoi documenti in memoria.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del database. |\n\nReturns: `Database` L'istanza del database.\n\nTutti i documenti vengono caricati da `databases/{name}.inmemory` alla prima operazione e tenuti in memoria. Dopo una modifica il file viene scritto entro 5 secondi. L'istanza viene creata alla prima chiamata e poi riutilizzata.\n\nSupporta `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` e `remove()` con il query builder di `NOSQL()`. Mantieni piccola la collezione: ogni documento è in memoria.\n\nExample: Un elenco di utenti online\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nRestituisce un database NoSQL conservato in più file di una cartella.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del database, oppure `~` seguito da un percorso assoluto della cartella. |\n\nReturns: `Database` L'istanza del database.\n\nI documenti vengono conservati nella cartella `databases/textdb-{name}/`. I nuovi documenti vanno in un file finché non raggiunge circa 512 kB, poi viene iniziato un nuovo file. I metodi e il query builder sono gli stessi di `NOSQL()`. Un nome che inizia con `~` è un percorso assoluto della cartella; un'istanza di questo tipo non viene messa in cache.\n\nExample: Registro di eventi\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nImpacchetta i file di una cartella in un unico file di backup.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Il percorso del file di backup, oppure uno stream scrivibile. |\n| `path` | `String|Array` | yes |  | Una cartella, oppure un array di percorsi relativi alla root dell'app. |\n| `callback` | `Function` | no |  | `function(err, meta)` dove `meta` è `{ filename, files, size }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)` che restituisce `true` per includere l'elemento. |\n\n`path` è una cartella: vengono impacchettati tutti i suoi file e le sue sottocartelle. Può anche essere un array di percorsi relativi alla root dell'app. Un file di backup esistente viene sostituito. Ogni file viene compresso con GZIP e memorizzato come Base64 su una riga, dopo il suo percorso relativo.\n\nLa funzione `filter(path, isdirectory)` riceve un percorso relativo che inizia con `/` (le cartelle terminano con `/`). Restituisci `true` per includere l'elemento. I socket vengono saltati.\n\nExample: Backup dei file caricati\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nSpacchetta in una cartella un file di backup creato da BACKUP().\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Il percorso del file di backup, oppure uno stream leggibile. |\n| `target` | `String` | yes |  | La cartella in cui vengono scritti i file. |\n| `callback` | `Function` | no |  | `function(err, meta)` dove `meta` è `{ files, size, path }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nLe cartelle che non esistono vengono create. I file esistenti con lo stesso nome vengono sovrascritti.\n\nLa funzione `filter(path, isdirectory)` riceve il percorso relativo dal backup. Per un file restituisci `false` per saltarlo, un nuovo percorso relativo (in una cartella esistente) per scriverlo altrove, oppure niente per mantenerlo. Per una cartella restituisci `false` per non crearla.\n\nExample: Ripristinare i file caricati\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabdps3Ul61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/caching-and-small-stores/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Cache, počítadlá a malé úložiská","summary":"Referencia CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() a RESTORE().","markdown":"---\ntitle: \"Cache, počítadlá a malé úložiská\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/caching-and-small-stores/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Cache, počítadlá a malé úložiská\n\n> Referencia CACHE(), F.cache, FILECACHE(), PREF, MEMORIZE(), COUNTER(), INMEMORY(), TEXTDB(), BACKUP() a RESTORE().\n\nGlobálne funkcie pre malé množstvá dát: pamäťová cache (`CACHE()` a `F.cache`), súborové cache, preferencie, perzistentné objekty, počítadlá, dve ďalšie NoSQL úložiská a zálohy priečinkov. V tejto referencii je `counter` inštancia vrátená z `COUNTER()`. Návod [Cache, počítadlá a malé úložiská](../../guides/caching-and-small-stores/) vysvetľuje ich použitie na príkladoch.\n\n## API\n\n### CACHE(key, [value], [expire])\n\nType: `method`\n\nNačíta alebo uloží hodnotu v pamäťovej cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `value` | `Object` | no |  | Hodnota na uloženie. Vynechaj ju, ak chceš čítať. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Text ako `'5 minutes'` alebo `'1 hour'`, prípadne `Date`. Bez neho hodnota vyprší o 5 minút. |\n\nReturns: `Object` Hodnota z cache.\n\nS jedným argumentom funkcia vráti hodnotu z cache alebo `undefined`, keď kľúč neexistuje alebo mu vypršala platnosť. S viacerými argumentmi hodnotu uloží a vráti ju. Je to skrátená forma `F.cache.get2()` a `F.cache.set()`.\n\nCache žije v pamäti procesu a po reštarte je prázdna (pokiaľ nie je zapnuté `allow_cache_snapshot`).\n\nExample: Uloženie zoznamu do cache\n```js\nfunction list() {\n\tvar $ = this;\n\tvar items = CACHE('products');\n\n\tif (items) {\n\t\t$.json(items);\n\t\treturn;\n\t}\n\n\tNOSQL('products').find().callback(function(err, response) {\n\t\tCACHE('products', response, '10 minutes');\n\t\t$.json(response);\n\t});\n}\n```\n\n### F.cache\n\nType: `property`\n\nPamäťová cache aplikácie.\n\nReturns: `Object` Inštancia cache.\n\nObjekt za `CACHE()`. Jeho položky sú v `F.cache.items`, objekte, kde každý kľúč obsahuje `{ value, expire }`. Raz za minútu Total.js odstráni položky, ktorým vypršala platnosť, a pre každú z nich vyšle `cache_expired`.\n\nExample: Počet kľúčov v cache\n```js\nvar count = Object.keys(F.cache.items).length;\n```\n\n### F.cache.set(key, value, [expire])\n\nType: `method`\n\nUloží hodnotu do cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `value` | `Object` | yes |  | Hodnota na uloženie. |\n| `expire` | `String|Date` | no | `'5 minutes'` | Text ako `'5 minutes'` alebo `'1 hour'`, prípadne `Date`. Bez neho hodnota vyprší o 5 minút. |\n\nReturns: `Object` Uložená hodnota.\n\nNahradí existujúcu hodnotu s rovnakým kľúčom a vyšle udalosť `cache_set`. `F.cache.add()` je tá istá metóda. S `allow_cache_cluster` sa hodnota pošle ostatným procesom clustra.\n\nExample: Uloženie na jednu hodinu\n```js\nF.cache.set('user_' + user.id, user, '1 hour');\n```\n\n### F.cache.get(key, [def])\n\nType: `method`\n\nNačíta hodnotu z cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `def` | `Object` | no | `undefined` | Hodnota, ktorá sa vráti, keď v cache nič nie je. |\n\nReturns: `Object` Hodnota z cache alebo `def`.\n\nVráti `def`, keď kľúč neexistuje alebo hodnote vypršala platnosť. Hodnota s vypršanou platnosťou sa odstráni a vyšle sa udalosť `cache_expired`. `F.cache.read()` je tá istá metóda.\n\nExample: Čítanie s predvolenou hodnotou\n```js\nvar user = F.cache.get('user_' + id, null);\n```\n\n### F.cache.get2(key, [def])\n\nType: `method`\n\nNačíta hodnotu z cache bez aktualizácie aktuálneho času.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `def` | `Object` | no | `undefined` | Hodnota, ktorá sa vráti, keď v cache nič nie je. |\n\nReturns: `Object` Hodnota z cache alebo `def`.\n\nFunguje ako `F.cache.get()`, ale platnosť porovnáva s globálnym `NOW`, ktoré Total.js periodicky aktualizuje, namiesto nového `Date`. Je o niečo rýchlejšia a položka môže zostať platná o pár sekúnd dlhšie. Používa ju `CACHE(key)`. `F.cache.read2()` je tá istá metóda.\n\nExample: Čítanie\n```js\nvar rates = F.cache.get2('rates', {});\n```\n\n### F.cache.remove(key)\n\nType: `method`\n\nOdstráni jednu hodnotu z cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n\nReturns: `Object` Odstránená položka `{ value, expire }` alebo `undefined`.\n\nS `allow_cache_cluster` sa odstránenie pošle ostatným procesom clustra.\n\nExample: Odstránenie po aktualizácii\n```js\nNOSQL('users').modify(model).id(model.id).callback(function() {\n\tF.cache.remove('user_' + model.id);\n});\n```\n\n### F.cache.removeAll(search)\n\nType: `method`\n\nOdstráni všetky hodnoty, ktorých kľúč obsahuje text alebo zodpovedá regulárnemu výrazu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `search` | `String|RegExp` | yes |  | Časť kľúča alebo regulárny výraz. |\n\nReturns: `Number` Počet odstránených položiek.\n\nText odstráni každý kľúč, ktorý ho obsahuje; `RegExp` odstráni každý kľúč, ktorému zodpovedá. Ak chceš odstrániť všetko, použi `F.cache.clear()`. `F.cache.reset()` je tá istá metóda.\n\nExample: Odstránenie podľa prefixu\n```js\nvar count = F.cache.removeAll('user_');\nF.cache.removeAll(/^product_\\d+$/);\n```\n\n### F.cache.clear()\n\nType: `method`\n\nOdstráni z cache všetky hodnoty.\n\nReturns: `Object` Cache na reťazenie.\n\nS `allow_cache_cluster` sa vyprázdnia aj ostatné procesy clustra.\n\nExample: Vyprázdnenie cache\n```js\nF.cache.clear();\n```\n\n### F.cache.setExpire(key, expire)\n\nType: `method`\n\nZmení platnosť hodnoty v cache.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `expire` | `String|Date` | yes |  | Text ako `'1 hour'` alebo `Date`. |\n\nReturns: `Object` Cache na reťazenie.\n\nKeď kľúč neexistuje, nerobí nič.\n\nExample: Predĺženie session\n```js\nF.cache.setExpire('session_' + id, '30 minutes');\n```\n\n### F.cache.fn(key, maker, [callback], [options])\n\nType: `method`\n\nVráti hodnotu z cache alebo ju vytvorí funkciou.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String` | yes |  | Kľúč hodnoty. |\n| `maker` | `Function` | yes |  | `function(next, options)`, ktorá vytvorí hodnotu a zavolá `next(value, [expire])`. |\n| `callback` | `Function` | no |  | `function(value, fromcache, options)`. |\n| `options` | `Object` | no |  | Ľubovoľný objekt, odovzdaný obom funkciám. |\n\nReturns: `Object` Cache na reťazenie.\n\nKeď kľúč obsahuje hodnotu, okamžite sa zavolá `callback(value, true, options)`. Inak sa spustí `maker(next, options)`; zavolaj `next(value, [expire])`, čím hodnotu uložíš do cache, a potom sa zavolá `callback(value, false, options)`. Nepravdivá hodnota (`false`, `0`, `''`, `null`) sa nepovažuje za uloženú v cache.\n\nExample: Uloženie dotazu do cache\n```js\nfunction stats() {\n\tvar $ = this;\n\tF.cache.fn('stats', function(next) {\n\t\tNOSQL('orders').count().callback(function(err, count) {\n\t\t\tnext({ orders: count }, '5 minutes');\n\t\t});\n\t}, function(value) {\n\t\t$.json(value);\n\t});\n}\n```\n\n### FILECACHE(id, expire, callback, maker, [encoding])\n\nType: `method`\n\nVráti hodnotu uloženú v súbore alebo ju vytvorí.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Identifikátor hodnoty v cache. |\n| `expire` | `String` | yes |  | Ako dlho je súbor platný, napríklad `'1 hour'` alebo `'2 days'`. |\n| `callback` | `Function` | yes |  | `function(err, value)`. |\n| `maker` | `Function` | yes |  | `function(next, id)`, ktorá vytvorí hodnotu a zavolá `next(err, value, [load])`. |\n| `encoding` | `String` | no | `'json'` | `'json'` alebo kódovanie textovej hodnoty, napríklad `'utf8'`. |\n\nHodnota sa ukladá v priečinku `tmp/` do súboru pomenovaného podľa hashu `id`. Keď súbor neexistuje alebo je starší ako `expire`, spustí sa `maker(next, id)`. Zavolaj `next(err, value, [load])`: bez chyby sa hodnota zapíše do súboru a zavolá sa `callback(err, value)`, pokiaľ `load` nie je `false`. Inak sa súbor načíta a odovzdá do `callback(err, value)`.\n\nPredvolene sa hodnota ukladá ako JSON a parsuje sa späť (vrátane dátumov). S iným `encoding`, napríklad `'utf8'`, sa hodnota zapíše tak, ako je, a načíta sa ako text.\n\nExample: Uloženie vzdialeného súboru do cache na deň\n```js\nFILECACHE('countries', '1 day', function(err, countries) {\n\tconsole.log(countries.length);\n}, function(next) {\n\tRESTBuilder.GET('https://example.com/countries.json').callback(next);\n});\n```\n\n### MEMORIZE([name], [delay], [skip])\n\nType: `method` · Since: `0.0.46`\n\nVráti objekt, ktorý sa ukladá do JSON súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | no | `''` | Názov súboru. |\n| `delay` | `Number` | no | `10000` | Milisekundy medzi `save()` a zápisom. |\n| `skip` | `String|Array` | no |  | Kľúče, ktoré sa nezapisujú do súboru, ako pole alebo text oddelený čiarkami. |\n\nReturns: `Object` Uložený objekt s metódou `save()`.\n\nSynchrónne načíta `databases/memorize_{name}.json` (alebo `databases/memorize.json` bez názvu) a vráti jeho obsah ako objekt, alebo prázdny objekt, keď súbor neexistuje. Objekt má metódu `save()`, ktorá ho zapíše späť.\n\nKaždé volanie súbor načíta znova a vráti nový objekt, preto ho zavolaj raz a referenciu si ponechaj. Argumenty `delay` a `skip` môžeš odovzdať v ľubovoľnom poradí. Priečinok `databases` musí existovať.\n\nExample: Zapamätanie posledného spustenia\n```js\nvar state = MEMORIZE('importer', 'running');\n\nstate.lastrun = NOW;\nstate.running = true; // not saved\nstate.save();\n```\n\n### data.save()\n\nType: `method` · Since: `0.0.46`\n\nZapíše objekt z MEMORIZE() do jeho súboru.\n\nZápis prebehne po oneskorení zadanom v `MEMORIZE()` (predvolene 10 sekúnd). Ďalšie `save()` počas tohto času oneskorenie reštartuje, takže dávka zmien dá jeden zápis. Objekt sa zapíše ako formátovaný JSON; funkcie a kľúče v `skip` sa vynechajú.\n\nExample: Uloženie po zmene\n```js\nvar counters = MEMORIZE('counters', 1000);\ncounters.downloads = (counters.downloads || 0) + 1;\ncounters.save();\n```\n\n### PREF\n\nType: `property`\n\nPreferencie aplikácie, ktoré sa ukladajú do súboru.\n\nReturns: `Object` Preferencie.\n\nTotal.js pri štarte načíta `databases/preferences.json` a každú hodnotu skopíruje do `PREF`, takže preferenciu čítaš ako vlastnosť: `PREF.token`. Vo vlákne je súbor `databases/preferences_{thread}.json`. Hodnoty meň iba cez `PREF.set()`, `PREF.inc()` a `PREF.rem()`; priamo priradená hodnota sa neuloží. Nepoužívaj názvy `set`, `inc` a `rem`.\n\nExample: Čítanie preferencie\n```js\nON('ready', function() {\n\tif (!PREF.installed) {\n\t\t// first start\n\t\tPREF.set('installed', NOW);\n\t}\n});\n```\n\n### PREF.set(name, [value])\n\nType: `method`\n\nUloží preferenciu alebo ju načíta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov preferencie. |\n| `value` | `Object` | no |  | Nová hodnota alebo `null` na odstránenie. |\n\nReturns: `Object` Hodnota.\n\nBez `value` funkcia vráti aktuálnu hodnotu. S hodnotou ju uloží do `PREF` a všetky preferencie zapíše sekundu po poslednej zmene (cez `DEF.onPrefSave`). `null` preferenciu odstráni, rovnako ako `PREF.rem()`.\n\nExample: Uloženie tokenu\n```js\nPREF.set('token', GUID(30));\nconsole.log(PREF.token);\n```\n\n### PREF.inc(name, [value])\n\nType: `method`\n\nPripočíta k preferencii číslo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov preferencie. |\n| `value` | `Number` | no | `1` | Číslo, ktoré sa pripočíta. |\n\nReturns: `Number` Nová hodnota.\n\nKeď preferencia neexistuje, začne od `value`. Výsledok sa uloží ako pri `PREF.set()`.\n\nExample: Počítanie importov\n```js\nvar count = PREF.inc('imports');\nPREF.inc('credits', -5);\n```\n\n### PREF.rem(name)\n\nType: `method`\n\nOdstráni preferenciu z uloženého súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov preferencie. |\n\nPreferencia sa odstráni z `PREF` a súbor sa zapíše znova.\n\nExample: Odstránenie tokenu\n```js\nPREF.rem('token');\n```\n\n### DEF.onPrefLoad = function(next) {}\n\nType: `delegate`\n\nNačíta preferencie pri štarte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `next` | `Function` | yes |  | `function(object)`, ktorá dostane uložené preferencie. |\n\nPredvolený delegát načíta `databases/preferences.json` a zavolá `next(object)`. Nahraď ho, ak chceš preferencie uchovávať inde; zavolaj `next(object)` s uloženými hodnotami alebo `next()`, keď žiadne nie sú. Priraď ho v definičnom súbore: keď sa delegát zmení počas štartu aplikácie, Total.js načíta preferencie znova s novým delegátom.\n\nExample: Preferencie v databázovej tabuľke\n```js\n// definitions/preferences.js\nDEF.onPrefLoad = function(next) {\n\tNOSQL('preferences').read().callback(function(err, doc) {\n\t\tnext(doc ? doc.data : null);\n\t});\n};\n\nDEF.onPrefSave = function(data) {\n\tNOSQL('preferences').modify({ data: data }, true).where('id', 'app');\n};\n```\n\n### DEF.onPrefSave = function(data) {}\n\nType: `delegate`\n\nUloží preferencie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `data` | `Object` | yes |  | Všetky preferencie. |\n\nVolá sa sekundu po poslednej zmene preferencie s objektom všetkých preferencií. Predvolený delegát ho zapíše ako formátovaný JSON do `databases/preferences.json`. Nahraď ho spolu s `DEF.onPrefLoad`.\n\nExample: Logovanie každého uloženia\n```js\nvar save = DEF.onPrefSave;\nDEF.onPrefSave = function(data) {\n\tconsole.log('Preferences saved');\n\tsave(data);\n};\n```\n\n### COUNTER(name)\n\nType: `method`\n\nVráti počítadlo, ktoré uchováva denné štatistiky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov počítadla. |\n\nReturns: `Counter` Inštancia počítadla.\n\nDáta sa ukladajú do `databases/{name}.counter` ako NoSQL dokumenty, jeden na id a deň: `{ id, sum, min, max, day, month, year, ts, date }`, kde `ts` je dátum ako číslo `yyyyMMdd`. Inštancia sa vytvorí pri prvom volaní a potom sa znova používa.\n\n`hit()` zbiera hodnoty v pamäti. Pri každej piatej udalosti `service` (približne každých päť minút) ich počítadlo zapíše do súboru. Hodnoty, ktoré ešte nie sú zapísané, sa stratia, keď sa proces zastaví.\n\nMetódy na čítanie vracajú NoSQL query builder: callback odovzdaj ako posledný argument alebo na výsledku zavolaj `.callback()`.\n\nExample: Počítanie návštev\n```js\nexports.install = function() {\n\tROUTE('GET /', index);\n};\n\nfunction index() {\n\tCOUNTER('visits').hit('homepage');\n\tthis.view('index');\n}\n```\n\n### counter.hit(id, [value])\n\nType: `method`\n\nPridá hodnotu do dnešného počítadla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Čo počítaš, napríklad stránku alebo produkt. |\n| `value` | `Number` | no | `1` | Hodnota, ktorá sa pripočíta. |\n\nReturns: `Counter` Počítadlo na reťazenie.\n\nHodnota sa pripočíta k súčtu `id` za aktuálny deň. Počítadlo si tiež uchováva najmenšiu a najväčšiu jednotlivú hodnotu ako `min` a `max`.\n\nExample: Počítanie sumy\n```js\nCOUNTER('sales').hit('eshop', order.price);\nCOUNTER('sales').hit('orders');\n```\n\n### counter.flush()\n\nType: `method`\n\nOkamžite zapíše zozbierané hodnoty do súboru.\n\nReturns: `Counter` Počítadlo na reťazenie.\n\nPočítadlo ju volá periodicky. Zavolaj ju sám pred plánovaným zastavením, aby sa nestratili žiadne prístupy.\n\nExample: Flush pred ukončením\n```js\nON('exit', function() {\n\tCOUNTER('visits').flush();\n});\n```\n\n### counter.count([id], [callback])\n\nType: `method`\n\nVráti celkový súčet všetkých uložených hodnôt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String|Array` | no |  | Id alebo pole id. |\n| `callback` | `Function` | no |  | `function(err, sum)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nSčíta pole `sum` všetkých dní pre jedno `id`, pole id alebo pre všetky id. Hodnoty, ktoré ešte neboli zapísané cez flush, sa nezahŕňajú.\n\nExample: Celkový počet návštev\n```js\nCOUNTER('visits').count('homepage', function(err, sum) {\n\tconsole.log('Visits:', sum);\n});\n```\n\n### counter.daily(id, [callback])\n\nType: `method`\n\nVráti uložené dni jedného id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id počítadla. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nKaždá položka je uložený dokument bez `id`: `{ sum, min, max, day, month, year, ts, date }`. K vrátenému builderu môžeš pridať podmienky, triedenie a stránkovanie.\n\nExample: Posledných 30 dní\n```js\nCOUNTER('visits').daily('homepage').sort('ts_desc').take(30).callback(function(err, days) {\n\tconsole.log(days);\n});\n```\n\n### counter.monthly(id, [callback])\n\nType: `method`\n\nVráti hodnoty jedného id zoskupené podľa mesiaca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id počítadla. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nKaždá položka je `{ date, year, month, ts, sum, min, max, count }`, kde `date` je mesiac ako text `yyyyMM`, `ts` to isté ako číslo a `count` počet uložených dní.\n\nExample: Mesačné predaje\n```js\nCOUNTER('sales').monthly('eshop', function(err, months) {\n\tmonths.forEach(m => console.log(m.year, m.month, m.sum));\n});\n```\n\n### counter.yearly(id, [callback])\n\nType: `method`\n\nVráti hodnoty jedného id zoskupené podľa roka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | yes |  | Id počítadla. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nKaždá položka je `{ date, year, ts, sum, min, max, count }`, kde `date` je rok ako text a `count` počet uložených dní.\n\nExample: Ročné návštevy\n```js\nCOUNTER('visits').yearly('homepage', console.log);\n```\n\n### counter.summarize([type], [callback])\n\nType: `method`\n\nVráti súčty všetkých id.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `type` | `String` | no |  | `'monthly'` alebo `'yearly'`. |\n| `callback` | `Function` | no |  | `function(err, items)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nBez `type` dostaneš jednu položku na id: `{ id, sum, min, max, count }`. S `'monthly'` alebo `'yearly'` dostaneš jednu položku na id a mesiac alebo rok, s pridanými poľami `ts`, `date`, `year` a (pri mesiacoch) `month`.\n\nExample: Najnavštevovanejšie stránky\n```js\nCOUNTER('visits').summarize(function(err, items) {\n\titems.quicksort('sum_desc');\n\tconsole.log(items.slice(0, 10));\n});\n```\n\n### counter.find()\n\nType: `method`\n\nVráti query builder nad uloženými dokumentmi.\n\nReturns: `QueryBuilder` Query builder.\n\nPouži ho na reporty, ktoré ostatné metódy nepokrývajú. Dokumenty majú polia `id`, `sum`, `min`, `max`, `day`, `month`, `year`, `ts` a `date`.\n\nExample: Jeden mesiac všetkých id\n```js\nCOUNTER('visits').find().where('year', 2026).where('month', 11).callback(console.log);\n```\n\n### counter.remove([id], [callback])\n\nType: `method`\n\nOdstráni uložené dokumenty jedného id alebo všetky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `id` | `String` | no |  | Id počítadla. |\n| `callback` | `Function` | no |  | `function(err, count)`. |\n\nReturns: `QueryBuilder` Query builder.\n\nBez `id` sa odstráni každý uložený dokument. Hodnoty, ktoré ešte neboli zapísané cez flush, zostanú v pamäti.\n\nExample: Odstránenie jedného id\n```js\nCOUNTER('visits').remove('oldpage');\n```\n\n### counter.clear()\n\nType: `method`\n\nOdstráni všetky uložené dáta počítadla.\n\nReturns: `Counter` Počítadlo na reťazenie.\n\nVyprázdni súbor. Hodnoty, ktoré ešte neboli zapísané cez flush, zostanú v pamäti.\n\nExample: Vynulovanie štatistík\n```js\nCOUNTER('visits').clear();\n```\n\n### INMEMORY(name)\n\nType: `method`\n\nVráti NoSQL databázu, ktorá drží svoje dokumenty v pamäti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy. |\n\nReturns: `Database` Inštancia databázy.\n\nVšetky dokumenty sa pri prvej operácii načítajú z `databases/{name}.inmemory` a držia sa v pamäti. Po zmene sa súbor zapíše do 5 sekúnd. Inštancia sa vytvorí pri prvom volaní a potom sa znova používa.\n\nPodporuje `insert()`, `find()`, `read()`, `list()`, `count()`, `scalar()`, `modify()`/`update()` a `remove()` s query builderom z `NOSQL()`. Kolekciu udržiavaj malú: každý dokument je v pamäti.\n\nExample: Zoznam online používateľov\n```js\nINMEMORY('online').insert({ id: user.id, name: user.name, dtconnected: NOW });\n\nINMEMORY('online').count().callback(function(err, count) {\n\tconsole.log(count, 'users online');\n});\n\nINMEMORY('online').remove().where('id', user.id);\n```\n\n### TEXTDB(name)\n\nType: `method`\n\nVráti NoSQL databázu uloženú vo viacerých súboroch priečinka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov databázy alebo `~`, za ktorým nasleduje absolútna cesta k priečinku. |\n\nReturns: `Database` Inštancia databázy.\n\nDokumenty sa ukladajú do priečinka `databases/textdb-{name}/`. Nové dokumenty idú do súboru, kým nemá približne 512 kB, potom sa začne nový súbor. Metódy a query builder sú rovnaké ako pri `NOSQL()`. Názov, ktorý začína na `~`, je absolútna cesta k priečinku; takáto inštancia sa neukladá do cache.\n\nExample: Log udalostí\n```js\nTEXTDB('events').insert({ type: 'login', userid: user.id, created: NOW });\n\nTEXTDB('events').find().where('type', 'login').take(50).callback(console.log);\n```\n\n### BACKUP(filename, path, [callback], [filter])\n\nType: `method`\n\nZbalí súbory priečinka do jedného záložného súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Cesta k záložnému súboru alebo zapisovateľný stream. |\n| `path` | `String|Array` | yes |  | Priečinok alebo pole ciest relatívnych ku koreňu aplikácie. |\n| `callback` | `Function` | no |  | `function(err, meta)`, kde `meta` je `{ filename, files, size }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`, ktorá vráti `true`, ak sa má položka zahrnúť. |\n\n`path` je priečinok: zbalia sa všetky jeho súbory a podpriečinky. Môže to byť aj pole ciest relatívnych ku koreňu aplikácie. Existujúci záložný súbor sa nahradí. Každý súbor sa komprimuje cez GZIP a uloží ako Base64 na jeden riadok za svoju relatívnu cestu.\n\nFunkcia `filter(path, isdirectory)` dostane relatívnu cestu, ktorá začína na `/` (priečinky končia na `/`). Vráť `true`, ak chceš položku zahrnúť. Sockety sa preskakujú.\n\nExample: Záloha nahraných súborov\n```js\nBACKUP(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Packed', meta.files, 'files');\n}, function(path, isdirectory) {\n\treturn isdirectory || !path.endsWith('.tmp');\n});\n```\n\n### RESTORE(filename, target, [callback], [filter])\n\nType: `method`\n\nRozbalí záložný súbor vytvorený cez BACKUP() do priečinka.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String|Stream` | yes |  | Cesta k záložnému súboru alebo čitateľný stream. |\n| `target` | `String` | yes |  | Priečinok, do ktorého sa súbory zapíšu. |\n| `callback` | `Function` | no |  | `function(err, meta)`, kde `meta` je `{ files, size, path }`. |\n| `filter` | `Function` | no |  | `function(path, isdirectory)`. |\n\nPriečinky, ktoré neexistujú, sa vytvoria. Existujúce súbory s rovnakým názvom sa prepíšu.\n\nFunkcia `filter(path, isdirectory)` dostane relatívnu cestu zo zálohy. Pri súbore vráť `false`, ak ho chceš preskočiť, novú relatívnu cestu (v existujúcom priečinku), ak ho chceš zapísať inam, alebo nič, ak ho chceš ponechať. Pri priečinku vráť `false`, ak ho nechceš vytvoriť.\n\nExample: Obnova nahraných súborov\n```js\nRESTORE(PATH.temp('uploads.backup'), PATH.public('uploads'), function(err, meta) {\n\tconsole.log('Restored', meta.files, 'files', meta.size, 'bytes');\n});\n```\n","entries":[{"type":"method","name":"CACHE()","signature":"CACHE(key, [value], [expire])","since":"","deprecated":false},{"type":"property","name":"F.cache","signature":"F.cache","since":"","deprecated":false},{"type":"method","name":"F.cache.set()","signature":"F.cache.set(key, value, [expire])","since":"","deprecated":false},{"type":"method","name":"F.cache.get()","signature":"F.cache.get(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.get2()","signature":"F.cache.get2(key, [def])","since":"","deprecated":false},{"type":"method","name":"F.cache.remove()","signature":"F.cache.remove(key)","since":"","deprecated":false},{"type":"method","name":"F.cache.removeAll()","signature":"F.cache.removeAll(search)","since":"","deprecated":false},{"type":"method","name":"F.cache.clear()","signature":"F.cache.clear()","since":"","deprecated":false},{"type":"method","name":"F.cache.setExpire()","signature":"F.cache.setExpire(key, expire)","since":"","deprecated":false},{"type":"method","name":"F.cache.fn()","signature":"F.cache.fn(key, maker, [callback], [options])","since":"","deprecated":false},{"type":"method","name":"FILECACHE()","signature":"FILECACHE(id, expire, callback, maker, [encoding])","since":"","deprecated":false},{"type":"method","name":"MEMORIZE()","signature":"MEMORIZE([name], [delay], [skip])","since":"0.0.46","deprecated":false},{"type":"method","name":"MEMORIZE().save()","signature":"data.save()","since":"0.0.46","deprecated":false},{"type":"property","name":"PREF","signature":"PREF","since":"","deprecated":false},{"type":"method","name":"PREF.set()","signature":"PREF.set(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.inc()","signature":"PREF.inc(name, [value])","since":"","deprecated":false},{"type":"method","name":"PREF.rem()","signature":"PREF.rem(name)","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefLoad","signature":"DEF.onPrefLoad = function(next) {}","since":"","deprecated":false},{"type":"delegate","name":"DEF.onPrefSave","signature":"DEF.onPrefSave = function(data) {}","since":"","deprecated":false},{"type":"method","name":"COUNTER()","signature":"COUNTER(name)","since":"","deprecated":false},{"type":"method","name":"counter.hit()","signature":"counter.hit(id, [value])","since":"","deprecated":false},{"type":"method","name":"counter.flush()","signature":"counter.flush()","since":"","deprecated":false},{"type":"method","name":"counter.count()","signature":"counter.count([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.daily()","signature":"counter.daily(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.monthly()","signature":"counter.monthly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.yearly()","signature":"counter.yearly(id, [callback])","since":"","deprecated":false},{"type":"method","name":"counter.summarize()","signature":"counter.summarize([type], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.find()","signature":"counter.find()","since":"","deprecated":false},{"type":"method","name":"counter.remove()","signature":"counter.remove([id], [callback])","since":"","deprecated":false},{"type":"method","name":"counter.clear()","signature":"counter.clear()","since":"","deprecated":false},{"type":"method","name":"INMEMORY()","signature":"INMEMORY(name)","since":"","deprecated":false},{"type":"method","name":"TEXTDB()","signature":"TEXTDB(name)","since":"","deprecated":false},{"type":"method","name":"BACKUP()","signature":"BACKUP(filename, path, [callback], [filter])","since":"","deprecated":false},{"type":"method","name":"RESTORE()","signature":"RESTORE(filename, target, [callback], [filter])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabnMm5VA60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Application structure","summary":"Start scripts, directories, bundles, packages and global loaders.","markdown":"---\ntitle: Application structure\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Application structure\n\n> Start scripts, directories, bundles, packages and global loaders.\n\nThe functions, flags and options that define how a Total.js 4 application is started and loaded. The guide [Application structure and modes](../../guides/application-structure/) explains the load order, the debug and release modes and bundles with examples; this page is the exact reference.\n\nTesting has its own page: [Testing](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nStarts the application in debug mode with a watcher that restarts it on changes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Start options (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nThe module exports a function that takes the start options. The calling process becomes the watcher: it forks the start script as a child process, watches the application directories and restarts the child when a file changes. The child runs `HTTP('debug', options)` (or `HTTPS()` with `options.https`, or `LOAD()` with `options.servicemode`). `DEBUG` is `true`. The watcher writes `{script}.pid`; deleting the file ends both processes.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nStarts the application in release mode.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Start options. |\n\nThe module exports a function that takes the same start options as `total4/debug`. `RELEASE` is `true` and files are not watched. By default the application runs in the current process. With the `--watcher` argument or `options.watcher`, the process becomes a supervisor: it forks the start script and starts it again when it exits or sends `total:restart`. The process writes `{script}.pid`; deleting the file ends it.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Run with a supervisor\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nStarts the HTTP server and loads the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` or `'release'`. |\n| `options` | `Object` | no | `{}` | Start options (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Called instead of `listen()` when the application is loaded. |\n\n`total4/debug` and `total4/release` call it for you. `mode` is `'debug'` or `'release'`. It extracts bundles, reads the configuration, loads all directories in their order, starts listening and emits `load` and `ready`. With `middleware`, the server is not started until you call `listen()`.\n\nExample: Without the start modules\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nStarts an HTTPS server and loads the application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` or `'release'`. |\n| `options` | `Object` | no | `{}` | Start options with `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Called instead of `listen()`. |\n\nWorks like `HTTP()`. Pass the certificate in `options.https` as `{ key, cert }`: Buffers, file paths, or base64 strings.\n\nExample: Certificate files\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nThe port of the HTTP server.\n\nReturns: `Number`\n\nWhen it is missing, a free numeric command-line argument is used, then `CONF.default_port`. `CONF.default_port = 'auto'` reads `process.env.PORT`. The fallback is `8000`.\n\nExample: Port\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nThe IP address the server listens on.\n\nReturns: `String`\n\nDefaults to `CONF.default_ip`, then `'0.0.0.0'`. The values `'null'`, `'undefined'` and `'auto'` let Node.js choose.\n\nExample: Localhost only\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nConfiguration values that override the configuration files.\n\nReturns: `Object`\n\nThe object is merged into `CONF` when the server starts.\n\nExample: Name\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nMore directories for the debug watcher.\n\nReturns: `String[]`\n\nAn array of paths relative to the application directory. Changes in them restart the application, like changes in the standard directories. Only `total4/debug` reads it.\n\nExample: Watch a directory\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nReloads the browser when views, public files or scripts change.\n\nReturns: `Boolean|Number|String`\n\nOnly for `total4/debug`. `true` starts a WebSocket server on port `35729`; a number sets another port. A string (a hostname) connects to the Total.js live reload service instead. Views and public files do not restart the application, they only reload the page.\n\nExample: Live reload\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nStarts the application with the Node.js inspector.\n\nReturns: `Number`\n\nThe value is the port of `--inspect` (default `9229`). Only for `total4/debug`; the watcher adds the argument to the forked process.\n\nExample: Inspector\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nStarts the application without the HTTP server.\n\nReturns: `Boolean|String|String[]`\n\n`true` loads everything with `LOAD()`; a string or an array is passed to `LOAD()` as the list of types. Use it for background services.\n\nExample: Service\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nRuns `total4/release` with a supervisor process.\n\nReturns: `Boolean`\n\nWith `true`, the release process forks the application and starts it again when it exits. The `--watcher` command-line argument does the same.\n\nExample: Supervisor\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nControls whether bundles are extracted on start.\n\nReturns: `Boolean`\n\n`false` skips extracting `/bundles/` into `/.src/`, but the application still runs from `/.src/` when `/bundles/` exists. Use it when the bundles are already extracted.\n\nExample: Skip extracting\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nInstalls the application without starting the HTTP server.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | What to load. |\n| `directory` | `String` | no | `the directory of the script` | The application directory. |\n| `callback` | `Function` | no |  | Called when the application is loaded. |\n\nReturns: `Promise` Only when `callback` is missing.\n\n`types` is an array or a string separated by commas or spaces: `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. A name with the prefix `no` excludes it (`'nocontrollers'`). When at least one name has no prefix, only the listed types are loaded. Without `types` everything is loaded except bundles, packages, components and themes. Add `debug` to run in debug mode (otherwise `RELEASE` is `true`). Without `service`, the internal cache timer is stopped. `directory` sets the application directory; `'..'` means the parent of the script. The configuration is always read. `ready` is emitted 500 ms after loading. Without a callback it returns a Promise.\n\nExample: A script\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nRuns once when the framework installs a file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | The configuration value for this file, or `undefined`. |\n\nEvery script in an installed directory can export it. The framework calls it right after `require()` and then deletes it. `options` is the configuration value `CONF['{type}_{name}']`, for example `CONF.module_mail` for `/modules/mail.js`. Types are `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` and `source`. After it, the framework emits `ON('install', type, name, module)` and `ON('{type}_{name}', module)`.\n\nExample: A module\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nReturns an installed module.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the module. |\n\nReturns: `Object` The exports of the module, or `null`.\n\nModules come from `/modules/` and packages. The name is the file name without the extension (with subdirectories, `folder/name`). A module that exports `id` is also available under that id. Returns `null` when the module does not exist.\n\nExample: Use a module\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nAll installed modules by name.\n\nReturns: `Object`\n\nThe same object as `F.modules`. `MODS.mail` equals `MODULE('mail')`, except that a missing module gives `undefined`.\n\nExample: Iterate\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nAll installed plugins by name.\n\nReturns: `Object`\n\nThe same object as `F.plugins`. A plugin is `plugins/{name}/index.js` or (an `.html` plugin) `plugins/{name}.html`. Each plugin gets `id` (its name). An `.html` plugin runs the code of its `<script total>` block, and every `<file name=\"...\">` block is written to a temporary file listed in `plugin.files`.\n\nExample: A plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nReturns an installed model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the model. |\n\nReturns: `Object` The exports of the model.\n\nModels come from `/models/`. The name is the file name without the extension. Returns `undefined` when the model does not exist.\n\nExample: A model\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nLoads a script from `/source/` the first time you ask for it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The file name without the extension. |\n\nReturns: `Object` The exports of the script, or `null`.\n\n`SOURCE()` is an alias. The file `/source/{name}.js` is installed (its `exports.install()` runs) and cached. The next calls return the cached exports. Returns `null` when the file does not exist.\n\nExample: Lazy loading\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nRequires a script relative to the application directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | The path relative to the application directory. |\n\nReturns: `Object` The exports of the script.\n\nIt is `require(F.directory + '/' + path)`. Use it to load your own libraries without relative paths that depend on the current file.\n\nExample: A library\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDownloads a script from a URL and requires it.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of a JavaScript file. |\n| `callback` | `Function(err, module, response)` | no |  | Called when the script is loaded. |\n\nThe script is saved to the temporary directory and `require()`d. The next calls in the same process return the same module without downloading. Import only code from a source you trust: it runs with the full rights of the application.\n\nExample: Remote code\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nThe version of the framework as a number.\n\nReturns: `Number`\n\nIt is `4099`. `F.is4` has the same value. Use it to check a minimal version.\n\nExample: Check\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nThe major version as a string.\n\nReturns: `String`\n\nIt is `'4'`. It is part of the user agent of `ACTION()` requests and of the version in `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nThe version of Node.js.\n\nReturns: `String`\n\nThe value of `process.version`, for example `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nThe version of Node.js as a number.\n\nReturns: `Number`\n\n`process.version` without `v` and dots, parsed as an integer: `'v18.17.0'` gives `18170`.\n\nExample: Compare\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` when the application runs from extracted bundles.\n\nReturns: `Boolean`\n\nThe application directory is then `/.src/`, not the directory of the start script.\n\n### F.isLoaded\n\nType: `property`\n\n`true` when all directories are installed.\n\nReturns: `Boolean`\n\nIt is set before `load` and `ready` are emitted.\n\nExample: Wait for loading\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true` when the application was started with `LOAD()`.\n\nReturns: `Boolean`\n\nIt is `false` otherwise. `F.isWorker` is similar, but it is `true` until `HTTP()` or `HTTPS()` starts the server.\n\nExample: Skip in scripts\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nAlways `true` in the framework.\n\nReturns: `Boolean`\n\n`is_client` is always `false`. They let code that is shared with the browser detect where it runs.\n\nExample: Shared code\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nA file that contains a whole application or a part of it.\n\nBundles in `/bundles/` are extracted into `/.src/` on start, then the files of the application are copied over them and the application runs from `/.src/`. `config*`, `sitemap`, `versions`, `workflows`, `dependencies` and `.resource` files are merged. A file whose name starts with `--` is appended to the file of the same name without the prefix. Existing files in `/databases/` and `/updates/` are kept. A `{name}.url` file with a URL downloads the bundle on start. Files that end with `-bk.bundle` or `_bk.bundle` are skipped. Create a bundle with `total4 bundle`.\n\nExample: Structure\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nRuns the application from `/.src/` without extracting the bundles again.\n\nWhen this file exists in the root, the framework uses `/.src/` as it is and the debug watcher watches the files there, together with the views and public files. Use it to edit the extracted files of a bundle directly.\n\n### /.bundleignore\n\nType: `type`\n\nPaths that are not copied into `/.src/` when bundles are extracted.\n\nOne rule per line: `/path/` skips the directory with everything in it, `/path/*.ext` skips files with the extension in that directory, `/path/file.ext` skips one file. The older name `.bundlesignore` also works.\n\nExample: Rules\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nSet to `shallow` to keep the extracted bundles.\n\nReturns: `String`\n\nWith `bundling : shallow` in the configuration, the framework does not clean `/.src/` and does not extract the bundles again when `/.src/bundle.json` exists.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCreates a bundle from the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | The name of the bundle file, with the `.bundle` extension. |\n\nThe default file name is `app.bundle`. The start scripts, `.pid` files, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` and `/.git/` are left out. The opposite command, `total4 extract <filename>`, extracts a bundle or a package into the current directory.\n\nExample: Create\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Extract\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nReturns the path to a file in an extracted package.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name of the package. |\n| `filename` | `String` | no |  | A file inside the package. |\n\nReturns: `String` The absolute path.\n\nPackages in `/packages/` (`name.package` files or directories) are extracted into the temporary directory and their `index.js` is installed. `PATH.package('name/file')` is the same as `PATH.package('name', 'file')`. `WORKER('@name/file')` and similar functions use it for the `@` prefix.\n\nExample: Read a template\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnMm5VA60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Anwendungsstruktur","summary":"Startskripte, Verzeichnisse, Bundles, Pakete und globale Loader.","markdown":"---\ntitle: Anwendungsstruktur\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Anwendungsstruktur\n\n> Startskripte, Verzeichnisse, Bundles, Pakete und globale Loader.\n\nDie Funktionen, Flags und Optionen, die festlegen, wie eine Total.js 4-Anwendung gestartet und geladen wird. Der Leitfaden [Anwendungsstruktur und Modi](../../guides/application-structure/) erklärt die Ladereihenfolge, den Debug- und Release-Modus und Bundles mit Beispielen; diese Seite ist die genaue Referenz.\n\nTests haben eine eigene Seite: [Tests](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nStartet die Anwendung im Debug-Modus mit einem Watcher, der sie bei Änderungen neu startet.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Startoptionen (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nDas Modul exportiert eine Funktion, die die Startoptionen entgegennimmt. Der aufrufende Prozess wird zum Watcher: Er forkt das Startskript als Kindprozess, überwacht die Anwendungsverzeichnisse und startet das Kind neu, wenn sich eine Datei ändert. Das Kind führt `HTTP('debug', options)` aus (oder `HTTPS()` mit `options.https`, oder `LOAD()` mit `options.servicemode`). `DEBUG` ist `true`. Der Watcher schreibt `{script}.pid`; das Löschen der Datei beendet beide Prozesse.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nStartet die Anwendung im Release-Modus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Startoptionen. |\n\nDas Modul exportiert eine Funktion, die dieselben Startoptionen wie `total4/debug` entgegennimmt. `RELEASE` ist `true`, und Dateien werden nicht überwacht. Standardmäßig läuft die Anwendung im aktuellen Prozess. Mit dem Argument `--watcher` oder `options.watcher` wird der Prozess zum Supervisor: Er forkt das Startskript und startet es erneut, wenn es sich beendet oder `total:restart` sendet. Der Prozess schreibt `{script}.pid`; das Löschen der Datei beendet ihn.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Mit einem Supervisor ausführen\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nStartet den HTTP-Server und lädt die Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` oder `'release'`. |\n| `options` | `Object` | no | `{}` | Startoptionen (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Wird statt `listen()` aufgerufen, wenn die Anwendung geladen ist. |\n\n`total4/debug` und `total4/release` rufen es für dich auf. `mode` ist `'debug'` oder `'release'`. Es entpackt Bundles, liest die Konfiguration, lädt alle Verzeichnisse in ihrer Reihenfolge, beginnt zu lauschen und löst `load` und `ready` aus. Mit `middleware` wird der Server erst gestartet, wenn du `listen()` aufrufst.\n\nExample: Ohne die Startmodule\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nStartet einen HTTPS-Server und lädt die Anwendung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` oder `'release'`. |\n| `options` | `Object` | no | `{}` | Startoptionen mit `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Wird statt `listen()` aufgerufen. |\n\nFunktioniert wie `HTTP()`. Übergib das Zertifikat in `options.https` als `{ key, cert }`: Buffer, Dateipfade oder Base64-Strings.\n\nExample: Zertifikatsdateien\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nDer Port des HTTP-Servers.\n\nReturns: `Number`\n\nFehlt er, wird ein freies numerisches Kommandozeilenargument verwendet, danach `CONF.default_port`. `CONF.default_port = 'auto'` liest `process.env.PORT`. Der Rückfallwert ist `8000`.\n\nExample: Port\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nDie IP-Adresse, auf der der Server lauscht.\n\nReturns: `String`\n\nStandardmäßig `CONF.default_ip`, danach `'0.0.0.0'`. Mit den Werten `'null'`, `'undefined'` und `'auto'` wählt Node.js selbst.\n\nExample: Nur localhost\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nKonfigurationswerte, die die Konfigurationsdateien überschreiben.\n\nReturns: `Object`\n\nDas Objekt wird beim Start des Servers in `CONF` übernommen.\n\nExample: Name\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nWeitere Verzeichnisse für den Debug-Watcher.\n\nReturns: `String[]`\n\nEin Array von Pfaden relativ zum Anwendungsverzeichnis. Änderungen darin starten die Anwendung neu, wie Änderungen in den Standardverzeichnissen. Nur `total4/debug` liest es.\n\nExample: Ein Verzeichnis überwachen\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nLädt den Browser neu, wenn sich Views, öffentliche Dateien oder Skripte ändern.\n\nReturns: `Boolean|Number|String`\n\nNur für `total4/debug`. `true` startet einen WebSocket-Server auf Port `35729`; eine Zahl setzt einen anderen Port. Ein String (ein Hostname) verbindet sich stattdessen mit dem Live-Reload-Dienst von Total.js. Views und öffentliche Dateien starten die Anwendung nicht neu, sie laden nur die Seite neu.\n\nExample: Live Reload\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nStartet die Anwendung mit dem Node.js-Inspector.\n\nReturns: `Number`\n\nDer Wert ist der Port von `--inspect` (Standard `9229`). Nur für `total4/debug`; der Watcher fügt das Argument dem geforkten Prozess hinzu.\n\nExample: Inspector\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nStartet die Anwendung ohne den HTTP-Server.\n\nReturns: `Boolean|String|String[]`\n\n`true` lädt alles mit `LOAD()`; ein String oder ein Array wird als Liste der Typen an `LOAD()` übergeben. Verwende es für Hintergrunddienste.\n\nExample: Dienst\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nFührt `total4/release` mit einem Supervisor-Prozess aus.\n\nReturns: `Boolean`\n\nMit `true` forkt der Release-Prozess die Anwendung und startet sie erneut, wenn sie sich beendet. Das Kommandozeilenargument `--watcher` tut dasselbe.\n\nExample: Supervisor\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nSteuert, ob Bundles beim Start entpackt werden.\n\nReturns: `Boolean`\n\n`false` überspringt das Entpacken von `/bundles/` nach `/.src/`, aber die Anwendung läuft trotzdem aus `/.src/`, wenn `/bundles/` existiert. Verwende es, wenn die Bundles bereits entpackt sind.\n\nExample: Entpacken überspringen\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nInstalliert die Anwendung, ohne den HTTP-Server zu starten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | Was geladen wird. |\n| `directory` | `String` | no | `the directory of the script` | Das Anwendungsverzeichnis. |\n| `callback` | `Function` | no |  | Wird aufgerufen, wenn die Anwendung geladen ist. |\n\nReturns: `Promise` Nur wenn `callback` fehlt.\n\n`types` ist ein Array oder ein durch Kommas oder Leerzeichen getrennter String: `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. Ein Name mit dem Präfix `no` schließt ihn aus (`'nocontrollers'`). Wenn mindestens ein Name kein Präfix hat, werden nur die aufgeführten Typen geladen. Ohne `types` wird alles geladen außer Bundles, Paketen, Komponenten und Themes. Füge `debug` hinzu, um im Debug-Modus zu laufen (sonst ist `RELEASE` gleich `true`). Ohne `service` wird der interne Cache-Timer angehalten. `directory` setzt das Anwendungsverzeichnis; `'..'` bedeutet das Elternverzeichnis des Skripts. Die Konfiguration wird immer gelesen. `ready` wird 500 ms nach dem Laden ausgelöst. Ohne Callback gibt es ein Promise zurück.\n\nExample: Ein Skript\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nLäuft einmal, wenn das Framework eine Datei installiert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Der Konfigurationswert für diese Datei oder `undefined`. |\n\nJedes Skript in einem installierten Verzeichnis kann es exportieren. Das Framework ruft es direkt nach `require()` auf und löscht es danach. `options` ist der Konfigurationswert `CONF['{type}_{name}']`, zum Beispiel `CONF.module_mail` für `/modules/mail.js`. Typen sind `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` und `source`. Danach löst das Framework `ON('install', type, name, module)` und `ON('{type}_{name}', module)` aus.\n\nExample: Ein Modul\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nGibt ein installiertes Modul zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Moduls. |\n\nReturns: `Object` Die Exporte des Moduls oder `null`.\n\nModule kommen aus `/modules/` und aus Paketen. Der Name ist der Dateiname ohne Endung (mit Unterverzeichnissen `folder/name`). Ein Modul, das `id` exportiert, ist auch unter dieser ID verfügbar. Gibt `null` zurück, wenn das Modul nicht existiert.\n\nExample: Ein Modul verwenden\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nAlle installierten Module nach Namen.\n\nReturns: `Object`\n\nDasselbe Objekt wie `F.modules`. `MODS.mail` entspricht `MODULE('mail')`, nur dass ein fehlendes Modul `undefined` ergibt.\n\nExample: Iterieren\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nAlle installierten Plugins nach Namen.\n\nReturns: `Object`\n\nDasselbe Objekt wie `F.plugins`. Ein Plugin ist `plugins/{name}/index.js` oder (ein `.html`-Plugin) `plugins/{name}.html`. Jedes Plugin bekommt `id` (seinen Namen). Ein `.html`-Plugin führt den Code seines `<script total>`-Blocks aus, und jeder `<file name=\"...\">`-Block wird in eine temporäre Datei geschrieben, die in `plugin.files` aufgeführt ist.\n\nExample: Ein Plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nGibt ein installiertes Model zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Models. |\n\nReturns: `Object` Die Exporte des Models.\n\nModels kommen aus `/models/`. Der Name ist der Dateiname ohne Endung. Gibt `undefined` zurück, wenn das Model nicht existiert.\n\nExample: Ein Model\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nLädt ein Skript aus `/source/`, wenn du es zum ersten Mal anforderst.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Dateiname ohne Endung. |\n\nReturns: `Object` Die Exporte des Skripts oder `null`.\n\n`SOURCE()` ist ein Alias. Die Datei `/source/{name}.js` wird installiert (ihr `exports.install()` läuft) und zwischengespeichert. Die nächsten Aufrufe geben die zwischengespeicherten Exporte zurück. Gibt `null` zurück, wenn die Datei nicht existiert.\n\nExample: Lazy Loading\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nLädt ein Skript relativ zum Anwendungsverzeichnis mit require.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Der Pfad relativ zum Anwendungsverzeichnis. |\n\nReturns: `Object` Die Exporte des Skripts.\n\nEs ist `require(F.directory + '/' + path)`. Verwende es, um deine eigenen Bibliotheken ohne relative Pfade zu laden, die von der aktuellen Datei abhängen.\n\nExample: Eine Bibliothek\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nLädt ein Skript von einer URL herunter und lädt es mit require.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL einer JavaScript-Datei. |\n| `callback` | `Function(err, module, response)` | no |  | Wird aufgerufen, wenn das Skript geladen ist. |\n\nDas Skript wird im temporären Verzeichnis gespeichert und mit `require()` geladen. Die nächsten Aufrufe im selben Prozess geben dasselbe Modul ohne erneuten Download zurück. Importiere nur Code aus einer Quelle, der du vertraust: Er läuft mit allen Rechten der Anwendung.\n\nExample: Entfernter Code\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nDie Version des Frameworks als Zahl.\n\nReturns: `Number`\n\nSie ist `4099`. `F.is4` hat denselben Wert. Verwende sie, um eine Mindestversion zu prüfen.\n\nExample: Prüfen\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nDie Hauptversion als String.\n\nReturns: `String`\n\nSie ist `'4'`. Sie ist Teil des User-Agents von `ACTION()`-Requests und der Version in `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nDie Version von Node.js.\n\nReturns: `String`\n\nDer Wert von `process.version`, zum Beispiel `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nDie Version von Node.js als Zahl.\n\nReturns: `Number`\n\n`process.version` ohne `v` und Punkte, als Ganzzahl geparst: `'v18.17.0'` ergibt `18170`.\n\nExample: Vergleichen\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true`, wenn die Anwendung aus entpackten Bundles läuft.\n\nReturns: `Boolean`\n\nDas Anwendungsverzeichnis ist dann `/.src/`, nicht das Verzeichnis des Startskripts.\n\n### F.isLoaded\n\nType: `property`\n\n`true`, wenn alle Verzeichnisse installiert sind.\n\nReturns: `Boolean`\n\nEs wird gesetzt, bevor `load` und `ready` ausgelöst werden.\n\nExample: Auf das Laden warten\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true`, wenn die Anwendung mit `LOAD()` gestartet wurde.\n\nReturns: `Boolean`\n\nSonst ist es `false`. `F.isWorker` ist ähnlich, aber es ist `true`, bis `HTTP()` oder `HTTPS()` den Server startet.\n\nExample: In Skripten überspringen\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nIm Framework immer `true`.\n\nReturns: `Boolean`\n\n`is_client` ist immer `false`. Damit erkennt Code, der mit dem Browser geteilt wird, wo er läuft.\n\nExample: Gemeinsamer Code\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nEine Datei, die eine ganze Anwendung oder einen Teil davon enthält.\n\nBundles in `/bundles/` werden beim Start nach `/.src/` entpackt, dann werden die Dateien der Anwendung darüber kopiert, und die Anwendung läuft aus `/.src/`. `config*`-, `sitemap`-, `versions`-, `workflows`-, `dependencies`- und `.resource`-Dateien werden zusammengeführt. Eine Datei, deren Name mit `--` beginnt, wird an die gleichnamige Datei ohne das Präfix angehängt. Vorhandene Dateien in `/databases/` und `/updates/` bleiben erhalten. Eine `{name}.url`-Datei mit einer URL lädt das Bundle beim Start herunter. Dateien, die auf `-bk.bundle` oder `_bk.bundle` enden, werden übersprungen. Erstelle ein Bundle mit `total4 bundle`.\n\nExample: Struktur\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nFührt die Anwendung aus `/.src/` aus, ohne die Bundles erneut zu entpacken.\n\nWenn diese Datei im Wurzelverzeichnis existiert, verwendet das Framework `/.src/` so, wie es ist, und der Debug-Watcher überwacht die Dateien dort, zusammen mit den Views und öffentlichen Dateien. Verwende es, um die entpackten Dateien eines Bundles direkt zu bearbeiten.\n\n### /.bundleignore\n\nType: `type`\n\nPfade, die beim Entpacken der Bundles nicht nach `/.src/` kopiert werden.\n\nEine Regel pro Zeile: `/path/` überspringt das Verzeichnis mit seinem gesamten Inhalt, `/path/*.ext` überspringt Dateien mit der Endung in diesem Verzeichnis, `/path/file.ext` überspringt eine einzelne Datei. Der ältere Name `.bundlesignore` funktioniert auch.\n\nExample: Regeln\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nSetze es auf `shallow`, um die entpackten Bundles zu behalten.\n\nReturns: `String`\n\nMit `bundling : shallow` in der Konfiguration räumt das Framework `/.src/` nicht auf und entpackt die Bundles nicht erneut, wenn `/.src/bundle.json` existiert.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nErstellt ein Bundle aus dem aktuellen Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Der Name der Bundle-Datei, mit der Endung `.bundle`. |\n\nDer Standard-Dateiname ist `app.bundle`. Die Startskripte, `.pid`-Dateien, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` und `/.git/` werden ausgelassen. Der umgekehrte Befehl, `total4 extract <filename>`, entpackt ein Bundle oder ein Paket in das aktuelle Verzeichnis.\n\nExample: Erstellen\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Entpacken\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nGibt den Pfad zu einer Datei in einem entpackten Paket zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Pakets. |\n| `filename` | `String` | no |  | Eine Datei innerhalb des Pakets. |\n\nReturns: `String` Der absolute Pfad.\n\nPakete in `/packages/` (`name.package`-Dateien oder -Verzeichnisse) werden in das temporäre Verzeichnis entpackt, und ihre `index.js` wird installiert. `PATH.package('name/file')` ist dasselbe wie `PATH.package('name', 'file')`. `WORKER('@name/file')` und ähnliche Funktionen verwenden es für das Präfix `@`.\n\nExample: Eine Vorlage lesen\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnMm5VA60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Estructura de la aplicación","summary":"Scripts de inicio, directorios, bundles, paquetes y cargadores globales.","markdown":"---\ntitle: \"Estructura de la aplicación\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Estructura de la aplicación\n\n> Scripts de inicio, directorios, bundles, paquetes y cargadores globales.\n\nLas funciones, flags y opciones que definen cómo se inicia y se carga una aplicación Total.js 4. La guía [Estructura de la aplicación y modos](../../guides/application-structure/) explica con ejemplos el orden de carga, los modos debug y release y los bundles; esta página es la referencia exacta.\n\nLas pruebas tienen su propia página: [Pruebas](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nInicia la aplicación en modo debug con un watcher que la reinicia cuando hay cambios.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opciones de inicio (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nEl módulo exporta una función que recibe las opciones de inicio. El proceso que la llama se convierte en el watcher: hace fork del script de inicio como proceso hijo, vigila los directorios de la aplicación y reinicia el hijo cuando cambia un archivo. El hijo ejecuta `HTTP('debug', options)` (o `HTTPS()` con `options.https`, o `LOAD()` con `options.servicemode`). `DEBUG` es `true`. El watcher escribe `{script}.pid`; al borrar el archivo terminan ambos procesos.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nInicia la aplicación en modo release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opciones de inicio. |\n\nEl módulo exporta una función que recibe las mismas opciones de inicio que `total4/debug`. `RELEASE` es `true` y los archivos no se vigilan. Por defecto la aplicación se ejecuta en el proceso actual. Con el argumento `--watcher` u `options.watcher`, el proceso se convierte en supervisor: hace fork del script de inicio y lo vuelve a iniciar cuando termina o envía `total:restart`. El proceso escribe `{script}.pid`; al borrar el archivo, termina.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Ejecutar con un supervisor\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nInicia el servidor HTTP y carga la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no | `{}` | Opciones de inicio (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Se llama en lugar de `listen()` cuando la aplicación está cargada. |\n\n`total4/debug` y `total4/release` lo llaman por ti. `mode` es `'debug'` o `'release'`. Extrae los bundles, lee la configuración, carga todos los directorios en su orden, empieza a escuchar y emite `load` y `ready`. Con `middleware`, el servidor no se inicia hasta que llamas a `listen()`.\n\nExample: Sin los módulos de inicio\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nInicia un servidor HTTPS y carga la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no | `{}` | Opciones de inicio con `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Se llama en lugar de `listen()`. |\n\nFunciona como `HTTP()`. Pasa el certificado en `options.https` como `{ key, cert }`: Buffers, rutas de archivo o cadenas base64.\n\nExample: Archivos de certificado\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nEl puerto del servidor HTTP.\n\nReturns: `Number`\n\nSi falta, se usa un argumento numérico libre de la línea de comandos y, después, `CONF.default_port`. `CONF.default_port = 'auto'` lee `process.env.PORT`. El valor de reserva es `8000`.\n\nExample: Puerto\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nLa dirección IP en la que escucha el servidor.\n\nReturns: `String`\n\nPor defecto es `CONF.default_ip` y, después, `'0.0.0.0'`. Los valores `'null'`, `'undefined'` y `'auto'` dejan que elija Node.js.\n\nExample: Solo localhost\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nValores de configuración que sobrescriben los archivos de configuración.\n\nReturns: `Object`\n\nEl objeto se fusiona en `CONF` cuando se inicia el servidor.\n\nExample: Nombre\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nMás directorios para el watcher de debug.\n\nReturns: `String[]`\n\nUn array de rutas relativas al directorio de la aplicación. Los cambios en ellas reinician la aplicación, igual que los cambios en los directorios estándar. Solo lo lee `total4/debug`.\n\nExample: Vigilar un directorio\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nRecarga el navegador cuando cambian vistas, archivos públicos o scripts.\n\nReturns: `Boolean|Number|String`\n\nSolo para `total4/debug`. `true` inicia un servidor WebSocket en el puerto `35729`; un número define otro puerto. Una cadena (un nombre de host) conecta en su lugar con el servicio de recarga en vivo de Total.js. Las vistas y los archivos públicos no reinician la aplicación, solo recargan la página.\n\nExample: Recarga en vivo\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nInicia la aplicación con el inspector de Node.js.\n\nReturns: `Number`\n\nEl valor es el puerto de `--inspect` (por defecto `9229`). Solo para `total4/debug`; el watcher añade el argumento al proceso hijo.\n\nExample: Inspector\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nInicia la aplicación sin el servidor HTTP.\n\nReturns: `Boolean|String|String[]`\n\n`true` lo carga todo con `LOAD()`; una cadena o un array se pasa a `LOAD()` como la lista de tipos. Úsalo para servicios en segundo plano.\n\nExample: Servicio\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nEjecuta `total4/release` con un proceso supervisor.\n\nReturns: `Boolean`\n\nCon `true`, el proceso release hace fork de la aplicación y la vuelve a iniciar cuando termina. El argumento de línea de comandos `--watcher` hace lo mismo.\n\nExample: Supervisor\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nControla si los bundles se extraen al iniciar.\n\nReturns: `Boolean`\n\n`false` omite la extracción de `/bundles/` en `/.src/`, pero la aplicación sigue ejecutándose desde `/.src/` cuando existe `/bundles/`. Úsalo cuando los bundles ya están extraídos.\n\nExample: Omitir la extracción\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nInstala la aplicación sin iniciar el servidor HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | Qué cargar. |\n| `directory` | `String` | no | `the directory of the script` | El directorio de la aplicación. |\n| `callback` | `Function` | no |  | Se llama cuando la aplicación está cargada. |\n\nReturns: `Promise` Solo cuando falta `callback`.\n\n`types` es un array o una cadena separada por comas o espacios: `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. Un nombre con el prefijo `no` lo excluye (`'nocontrollers'`). Cuando al menos un nombre no tiene prefijo, solo se cargan los tipos listados. Sin `types` se carga todo excepto los bundles, paquetes, componentes y temas. Añade `debug` para ejecutar en modo debug (si no, `RELEASE` es `true`). Sin `service`, se detiene el temporizador interno de la caché. `directory` define el directorio de la aplicación; `'..'` significa el directorio padre del script. La configuración se lee siempre. `ready` se emite 500 ms después de la carga. Sin callback devuelve una Promise.\n\nExample: Un script\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nSe ejecuta una vez cuando el framework instala un archivo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | El valor de configuración de este archivo, o `undefined`. |\n\nCualquier script de un directorio instalado puede exportarlo. El framework lo llama justo después de `require()` y luego lo elimina. `options` es el valor de configuración `CONF['{type}_{name}']`, por ejemplo `CONF.module_mail` para `/modules/mail.js`. Los tipos son `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` y `source`. Después, el framework emite `ON('install', type, name, module)` y `ON('{type}_{name}', module)`.\n\nExample: Un módulo\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nDevuelve un módulo instalado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del módulo. |\n\nReturns: `Object` Los exports del módulo, o `null`.\n\nLos módulos vienen de `/modules/` y de los paquetes. El nombre es el nombre del archivo sin la extensión (con subdirectorios, `folder/name`). Un módulo que exporta `id` también está disponible con ese id. Devuelve `null` cuando el módulo no existe.\n\nExample: Usar un módulo\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nTodos los módulos instalados por nombre.\n\nReturns: `Object`\n\nEl mismo objeto que `F.modules`. `MODS.mail` equivale a `MODULE('mail')`, salvo que un módulo inexistente da `undefined`.\n\nExample: Recorrer\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nTodos los plugins instalados por nombre.\n\nReturns: `Object`\n\nEl mismo objeto que `F.plugins`. Un plugin es `plugins/{name}/index.js` o (un plugin `.html`) `plugins/{name}.html`. Cada plugin recibe `id` (su nombre). Un plugin `.html` ejecuta el código de su bloque `<script total>`, y cada bloque `<file name=\"...\">` se escribe en un archivo temporal listado en `plugin.files`.\n\nExample: Un plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nDevuelve un modelo instalado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del modelo. |\n\nReturns: `Object` Los exports del modelo.\n\nLos modelos vienen de `/models/`. El nombre es el nombre del archivo sin la extensión. Devuelve `undefined` cuando el modelo no existe.\n\nExample: Un modelo\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nCarga un script de `/source/` la primera vez que lo pides.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del archivo sin la extensión. |\n\nReturns: `Object` Los exports del script, o `null`.\n\n`SOURCE()` es un alias. El archivo `/source/{name}.js` se instala (se ejecuta su `exports.install()`) y se guarda en caché. Las llamadas siguientes devuelven los exports en caché. Devuelve `null` cuando el archivo no existe.\n\nExample: Carga diferida\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nHace require de un script relativo al directorio de la aplicación.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | La ruta relativa al directorio de la aplicación. |\n\nReturns: `Object` Los exports del script.\n\nEs `require(F.directory + '/' + path)`. Úsalo para cargar tus propias librerías sin rutas relativas que dependan del archivo actual.\n\nExample: Una librería\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nDescarga un script de una URL y hace require de él.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL de un archivo JavaScript. |\n| `callback` | `Function(err, module, response)` | no |  | Se llama cuando el script está cargado. |\n\nEl script se guarda en el directorio temporal y se carga con `require()`. Las llamadas siguientes en el mismo proceso devuelven el mismo módulo sin descargarlo. Importa solo código de una fuente de confianza: se ejecuta con todos los permisos de la aplicación.\n\nExample: Código remoto\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nLa versión del framework como número.\n\nReturns: `Number`\n\nEs `4099`. `F.is4` tiene el mismo valor. Úsalo para comprobar una versión mínima.\n\nExample: Comprobación\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nLa versión mayor como cadena.\n\nReturns: `String`\n\nEs `'4'`. Forma parte del user agent de las peticiones de `ACTION()` y de la versión en `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nLa versión de Node.js.\n\nReturns: `String`\n\nEl valor de `process.version`, por ejemplo `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nLa versión de Node.js como número.\n\nReturns: `Number`\n\n`process.version` sin `v` ni puntos, convertido a entero: `'v18.17.0'` da `18170`.\n\nExample: Comparar\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` cuando la aplicación se ejecuta desde bundles extraídos.\n\nReturns: `Boolean`\n\nEn ese caso el directorio de la aplicación es `/.src/`, no el directorio del script de inicio.\n\n### F.isLoaded\n\nType: `property`\n\n`true` cuando todos los directorios están instalados.\n\nReturns: `Boolean`\n\nSe define antes de que se emitan `load` y `ready`.\n\nExample: Esperar a la carga\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true` cuando la aplicación se inició con `LOAD()`.\n\nReturns: `Boolean`\n\nEn otro caso es `false`. `F.isWorker` es similar, pero es `true` hasta que `HTTP()` o `HTTPS()` inicia el servidor.\n\nExample: Omitir en scripts\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nSiempre `true` en el framework.\n\nReturns: `Boolean`\n\n`is_client` es siempre `false`. Permiten que el código compartido con el navegador detecte dónde se ejecuta.\n\nExample: Código compartido\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nUn archivo que contiene una aplicación completa o una parte de ella.\n\nLos bundles de `/bundles/` se extraen en `/.src/` al iniciar; después se copian encima los archivos de la aplicación y la aplicación se ejecuta desde `/.src/`. Los archivos `config*`, `sitemap`, `versions`, `workflows`, `dependencies` y `.resource` se fusionan. Un archivo cuyo nombre empieza por `--` se añade al final del archivo del mismo nombre sin el prefijo. Los archivos existentes en `/databases/` y `/updates/` se conservan. Un archivo `{name}.url` con una URL descarga el bundle al iniciar. Los archivos que terminan en `-bk.bundle` o `_bk.bundle` se omiten. Crea un bundle con `total4 bundle`.\n\nExample: Estructura\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nEjecuta la aplicación desde `/.src/` sin volver a extraer los bundles.\n\nCuando este archivo existe en la raíz, el framework usa `/.src/` tal como está y el watcher de debug vigila allí los archivos, junto con las vistas y los archivos públicos. Úsalo para editar directamente los archivos extraídos de un bundle.\n\n### /.bundleignore\n\nType: `type`\n\nRutas que no se copian en `/.src/` cuando se extraen los bundles.\n\nUna regla por línea: `/path/` omite el directorio con todo su contenido, `/path/*.ext` omite los archivos con esa extensión en ese directorio, `/path/file.ext` omite un archivo. El nombre antiguo `.bundlesignore` también funciona.\n\nExample: Reglas\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nDefínelo como `shallow` para conservar los bundles extraídos.\n\nReturns: `String`\n\nCon `bundling : shallow` en la configuración, el framework no limpia `/.src/` y no vuelve a extraer los bundles cuando existe `/.src/bundle.json`.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrea un bundle a partir del directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | El nombre del archivo del bundle, con la extensión `.bundle`. |\n\nEl nombre de archivo por defecto es `app.bundle`. Se excluyen los scripts de inicio, los archivos `.pid`, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` y `/.git/`. El comando opuesto, `total4 extract <filename>`, extrae un bundle o un paquete en el directorio actual.\n\nExample: Crear\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Extraer\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nDevuelve la ruta a un archivo de un paquete extraído.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del paquete. |\n| `filename` | `String` | no |  | Un archivo dentro del paquete. |\n\nReturns: `String` La ruta absoluta.\n\nLos paquetes de `/packages/` (archivos o directorios `name.package`) se extraen en el directorio temporal y se instala su `index.js`. `PATH.package('name/file')` es lo mismo que `PATH.package('name', 'file')`. `WORKER('@name/file')` y funciones similares lo usan para el prefijo `@`.\n\nExample: Leer una plantilla\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnMm5VA60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Structure de l'application","summary":"Scripts de démarrage, répertoires, bundles, paquets et chargeurs globaux.","markdown":"---\ntitle: \"Structure de l'application\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Structure de l'application\n\n> Scripts de démarrage, répertoires, bundles, paquets et chargeurs globaux.\n\nLes fonctions, flags et options qui définissent comment une application Total.js 4 est démarrée et chargée. Le guide [Structure de l'application et modes](../../guides/application-structure/) explique l'ordre de chargement, les modes debug et release et les bundles avec des exemples ; cette page en est la référence exacte.\n\nLes tests ont leur propre page : [Tests](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nDémarre l'application en mode debug avec un watcher qui la redémarre à chaque modification.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Options de démarrage (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nLe module exporte une fonction qui prend les options de démarrage. Le processus appelant devient le watcher : il forke le script de démarrage comme processus enfant, surveille les répertoires de l'application et redémarre l'enfant lorsqu'un fichier change. L'enfant exécute `HTTP('debug', options)` (ou `HTTPS()` avec `options.https`, ou `LOAD()` avec `options.servicemode`). `DEBUG` vaut `true`. Le watcher écrit `{script}.pid` ; supprimer ce fichier termine les deux processus.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nDémarre l'application en mode release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Options de démarrage. |\n\nLe module exporte une fonction qui prend les mêmes options de démarrage que `total4/debug`. `RELEASE` vaut `true` et les fichiers ne sont pas surveillés. Par défaut, l'application s'exécute dans le processus courant. Avec l'argument `--watcher` ou `options.watcher`, le processus devient un superviseur : il forke le script de démarrage et le relance lorsqu'il se termine ou envoie `total:restart`. Le processus écrit `{script}.pid` ; supprimer ce fichier le termine.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Exécuter avec un superviseur\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nDémarre le serveur HTTP et charge l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` ou `'release'`. |\n| `options` | `Object` | no | `{}` | Options de démarrage (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Appelé à la place de `listen()` lorsque l'application est chargée. |\n\n`total4/debug` et `total4/release` l'appellent pour toi. `mode` vaut `'debug'` ou `'release'`. Elle extrait les bundles, lit la configuration, charge tous les répertoires dans leur ordre, commence l'écoute et émet `load` et `ready`. Avec `middleware`, le serveur ne démarre pas tant que tu n'appelles pas `listen()`.\n\nExample: Sans les modules de démarrage\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nDémarre un serveur HTTPS et charge l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` ou `'release'`. |\n| `options` | `Object` | no | `{}` | Options de démarrage avec `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Appelé à la place de `listen()`. |\n\nFonctionne comme `HTTP()`. Passe le certificat dans `options.https` sous la forme `{ key, cert }` : des Buffers, des chemins de fichiers ou des chaînes base64.\n\nExample: Fichiers de certificat\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nLe port du serveur HTTP.\n\nReturns: `Number`\n\nLorsqu'il est absent, un argument numérique libre de la ligne de commande est utilisé, puis `CONF.default_port`. `CONF.default_port = 'auto'` lit `process.env.PORT`. La valeur de repli est `8000`.\n\nExample: Port\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nL'adresse IP sur laquelle le serveur écoute.\n\nReturns: `String`\n\nPar défaut `CONF.default_ip`, puis `'0.0.0.0'`. Les valeurs `'null'`, `'undefined'` et `'auto'` laissent Node.js choisir.\n\nExample: Localhost uniquement\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nDes valeurs de configuration qui remplacent celles des fichiers de configuration.\n\nReturns: `Object`\n\nL'objet est fusionné dans `CONF` au démarrage du serveur.\n\nExample: Nom\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nDes répertoires supplémentaires pour le watcher de debug.\n\nReturns: `String[]`\n\nUn tableau de chemins relatifs au répertoire de l'application. Les modifications qu'ils contiennent redémarrent l'application, comme celles des répertoires standard. Seul `total4/debug` le lit.\n\nExample: Surveiller un répertoire\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nRecharge le navigateur lorsque les vues, les fichiers publics ou les scripts changent.\n\nReturns: `Boolean|Number|String`\n\nUniquement pour `total4/debug`. `true` démarre un serveur WebSocket sur le port `35729` ; un nombre définit un autre port. Une chaîne (un nom d'hôte) se connecte plutôt au service de live reload de Total.js. Les vues et les fichiers publics ne redémarrent pas l'application, ils rechargent seulement la page.\n\nExample: Live reload\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nDémarre l'application avec l'inspecteur Node.js.\n\nReturns: `Number`\n\nLa valeur est le port de `--inspect` (par défaut `9229`). Uniquement pour `total4/debug` ; le watcher ajoute l'argument au processus forké.\n\nExample: Inspecteur\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nDémarre l'application sans le serveur HTTP.\n\nReturns: `Boolean|String|String[]`\n\n`true` charge tout avec `LOAD()` ; une chaîne ou un tableau est passé à `LOAD()` comme liste de types. Utilise-le pour les services en arrière-plan.\n\nExample: Service\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nExécute `total4/release` avec un processus superviseur.\n\nReturns: `Boolean`\n\nAvec `true`, le processus release forke l'application et la relance lorsqu'elle se termine. L'argument de ligne de commande `--watcher` fait la même chose.\n\nExample: Superviseur\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nDétermine si les bundles sont extraits au démarrage.\n\nReturns: `Boolean`\n\n`false` saute l'extraction de `/bundles/` dans `/.src/`, mais l'application s'exécute quand même depuis `/.src/` lorsque `/bundles/` existe. Utilise-le lorsque les bundles sont déjà extraits.\n\nExample: Sauter l'extraction\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nInstalle l'application sans démarrer le serveur HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | Ce qu'il faut charger. |\n| `directory` | `String` | no | `the directory of the script` | Le répertoire de l'application. |\n| `callback` | `Function` | no |  | Appelé lorsque l'application est chargée. |\n\nReturns: `Promise` Uniquement si `callback` est absent.\n\n`types` est un tableau ou une chaîne séparée par des virgules ou des espaces : `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. Un nom avec le préfixe `no` l'exclut (`'nocontrollers'`). Lorsqu'au moins un nom n'a pas de préfixe, seuls les types listés sont chargés. Sans `types`, tout est chargé sauf les bundles, les paquets, les composants et les thèmes. Ajoute `debug` pour exécuter en mode debug (sinon `RELEASE` vaut `true`). Sans `service`, le minuteur interne du cache est arrêté. `directory` définit le répertoire de l'application ; `'..'` désigne le parent du script. La configuration est toujours lue. `ready` est émis 500 ms après le chargement. Sans callback, elle renvoie une Promise.\n\nExample: Un script\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nS'exécute une fois lorsque le framework installe un fichier.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | La valeur de configuration de ce fichier, ou `undefined`. |\n\nChaque script d'un répertoire installé peut l'exporter. Le framework l'appelle juste après le `require()` puis la supprime. `options` est la valeur de configuration `CONF['{type}_{name}']`, par exemple `CONF.module_mail` pour `/modules/mail.js`. Les types sont `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` et `source`. Ensuite, le framework émet `ON('install', type, name, module)` et `ON('{type}_{name}', module)`.\n\nExample: Un module\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nRenvoie un module installé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du module. |\n\nReturns: `Object` Les exports du module, ou `null`.\n\nLes modules proviennent de `/modules/` et des paquets. Le nom est le nom du fichier sans l'extension (avec les sous-répertoires, `folder/name`). Un module qui exporte `id` est aussi disponible sous cet id. Renvoie `null` lorsque le module n'existe pas.\n\nExample: Utiliser un module\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nTous les modules installés, par nom.\n\nReturns: `Object`\n\nLe même objet que `F.modules`. `MODS.mail` équivaut à `MODULE('mail')`, sauf qu'un module manquant donne `undefined`.\n\nExample: Parcourir\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nTous les plugins installés, par nom.\n\nReturns: `Object`\n\nLe même objet que `F.plugins`. Un plugin est `plugins/{name}/index.js` ou (un plugin `.html`) `plugins/{name}.html`. Chaque plugin reçoit `id` (son nom). Un plugin `.html` exécute le code de son bloc `<script total>`, et chaque bloc `<file name=\"...\">` est écrit dans un fichier temporaire listé dans `plugin.files`.\n\nExample: Un plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nRenvoie un modèle installé.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du modèle. |\n\nReturns: `Object` Les exports du modèle.\n\nLes modèles proviennent de `/models/`. Le nom est le nom du fichier sans l'extension. Renvoie `undefined` lorsque le modèle n'existe pas.\n\nExample: Un modèle\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nCharge un script de `/source/` la première fois que tu le demandes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du fichier sans l'extension. |\n\nReturns: `Object` Les exports du script, ou `null`.\n\n`SOURCE()` est un alias. Le fichier `/source/{name}.js` est installé (son `exports.install()` s'exécute) et mis en cache. Les appels suivants renvoient les exports en cache. Renvoie `null` lorsque le fichier n'existe pas.\n\nExample: Chargement différé\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nFait un require d'un script relatif au répertoire de l'application.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Le chemin relatif au répertoire de l'application. |\n\nReturns: `Object` Les exports du script.\n\nC'est `require(F.directory + '/' + path)`. Utilise-le pour charger tes propres bibliothèques sans chemins relatifs qui dépendent du fichier courant.\n\nExample: Une bibliothèque\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nTélécharge un script depuis une URL et en fait un require.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL d'un fichier JavaScript. |\n| `callback` | `Function(err, module, response)` | no |  | Appelé lorsque le script est chargé. |\n\nLe script est enregistré dans le répertoire temporaire puis chargé avec `require()`. Les appels suivants dans le même processus renvoient le même module sans téléchargement. N'importe que du code provenant d'une source de confiance : il s'exécute avec tous les droits de l'application.\n\nExample: Code distant\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nLa version du framework sous forme de nombre.\n\nReturns: `Number`\n\nElle vaut `4099`. `F.is4` a la même valeur. Utilise-la pour vérifier une version minimale.\n\nExample: Vérification\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nLa version majeure sous forme de chaîne.\n\nReturns: `String`\n\nElle vaut `'4'`. Elle fait partie du user agent des requêtes `ACTION()` et de la version dans `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nLa version de Node.js.\n\nReturns: `String`\n\nLa valeur de `process.version`, par exemple `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nLa version de Node.js sous forme de nombre.\n\nReturns: `Number`\n\n`process.version` sans le `v` ni les points, analysé comme un entier : `'v18.17.0'` donne `18170`.\n\nExample: Comparer\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` lorsque l'application s'exécute depuis des bundles extraits.\n\nReturns: `Boolean`\n\nLe répertoire de l'application est alors `/.src/`, et non le répertoire du script de démarrage.\n\n### F.isLoaded\n\nType: `property`\n\n`true` lorsque tous les répertoires sont installés.\n\nReturns: `Boolean`\n\nElle est définie avant l'émission de `load` et `ready`.\n\nExample: Attendre le chargement\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true` lorsque l'application a été démarrée avec `LOAD()`.\n\nReturns: `Boolean`\n\nElle vaut `false` sinon. `F.isWorker` est similaire, mais vaut `true` jusqu'à ce que `HTTP()` ou `HTTPS()` démarre le serveur.\n\nExample: Ignorer dans les scripts\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nToujours `true` dans le framework.\n\nReturns: `Boolean`\n\n`is_client` vaut toujours `false`. Elles permettent au code partagé avec le navigateur de détecter où il s'exécute.\n\nExample: Code partagé\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nUn fichier qui contient une application entière ou une partie de celle-ci.\n\nLes bundles de `/bundles/` sont extraits dans `/.src/` au démarrage, puis les fichiers de l'application sont copiés par-dessus et l'application s'exécute depuis `/.src/`. Les fichiers `config*`, `sitemap`, `versions`, `workflows`, `dependencies` et `.resource` sont fusionnés. Un fichier dont le nom commence par `--` est ajouté à la fin du fichier de même nom sans le préfixe. Les fichiers existants dans `/databases/` et `/updates/` sont conservés. Un fichier `{name}.url` contenant une URL télécharge le bundle au démarrage. Les fichiers qui se terminent par `-bk.bundle` ou `_bk.bundle` sont ignorés. Crée un bundle avec `total4 bundle`.\n\nExample: Structure\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nExécute l'application depuis `/.src/` sans extraire à nouveau les bundles.\n\nLorsque ce fichier existe à la racine, le framework utilise `/.src/` tel quel et le watcher de debug y surveille les fichiers, ainsi que les vues et les fichiers publics. Utilise-le pour modifier directement les fichiers extraits d'un bundle.\n\n### /.bundleignore\n\nType: `type`\n\nLes chemins qui ne sont pas copiés dans `/.src/` lors de l'extraction des bundles.\n\nUne règle par ligne : `/path/` ignore le répertoire avec tout son contenu, `/path/*.ext` ignore les fichiers ayant cette extension dans ce répertoire, `/path/file.ext` ignore un seul fichier. L'ancien nom `.bundlesignore` fonctionne aussi.\n\nExample: Règles\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nDéfinis-la à `shallow` pour conserver les bundles extraits.\n\nReturns: `String`\n\nAvec `bundling : shallow` dans la configuration, le framework ne nettoie pas `/.src/` et n'extrait pas à nouveau les bundles lorsque `/.src/bundle.json` existe.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrée un bundle à partir du répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Le nom du fichier bundle, avec l'extension `.bundle`. |\n\nLe nom de fichier par défaut est `app.bundle`. Les scripts de démarrage, les fichiers `.pid`, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` et `/.git/` sont exclus. La commande inverse, `total4 extract <filename>`, extrait un bundle ou un paquet dans le répertoire courant.\n\nExample: Créer\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Extraire\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nRenvoie le chemin d'un fichier dans un paquet extrait.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du paquet. |\n| `filename` | `String` | no |  | Un fichier dans le paquet. |\n\nReturns: `String` Le chemin absolu.\n\nLes paquets de `/packages/` (fichiers ou répertoires `name.package`) sont extraits dans le répertoire temporaire et leur `index.js` est installé. `PATH.package('name/file')` équivaut à `PATH.package('name', 'file')`. `WORKER('@name/file')` et les fonctions similaires l'utilisent pour le préfixe `@`.\n\nExample: Lire un template\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnMm5VA60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Struttura dell'applicazione","summary":"Script di avvio, directory, bundle, pacchetti e loader globali.","markdown":"---\ntitle: \"Struttura dell'applicazione\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Struttura dell'applicazione\n\n> Script di avvio, directory, bundle, pacchetti e loader globali.\n\nLe funzioni, i flag e le opzioni che definiscono come un'applicazione Total.js 4 viene avviata e caricata. La guida [Struttura dell'applicazione e modalità](../../guides/application-structure/) spiega con esempi l'ordine di caricamento, le modalità debug e release e i bundle; questa pagina è il riferimento esatto.\n\nI test hanno una pagina propria: [Test](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nAvvia l'applicazione in modalità debug con un watcher che la riavvia alle modifiche.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opzioni di avvio (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nIl modulo esporta una funzione che accetta le opzioni di avvio. Il processo chiamante diventa il watcher: esegue il fork dello script di avvio come processo figlio, osserva le directory dell'applicazione e riavvia il figlio quando un file cambia. Il figlio esegue `HTTP('debug', options)` (oppure `HTTPS()` con `options.https`, o `LOAD()` con `options.servicemode`). `DEBUG` è `true`. Il watcher scrive `{script}.pid`; eliminare il file termina entrambi i processi.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nAvvia l'applicazione in modalità release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Opzioni di avvio. |\n\nIl modulo esporta una funzione che accetta le stesse opzioni di avvio di `total4/debug`. `RELEASE` è `true` e i file non vengono osservati. Per impostazione predefinita l'applicazione gira nel processo corrente. Con l'argomento `--watcher` o `options.watcher`, il processo diventa un supervisore: esegue il fork dello script di avvio e lo riavvia quando termina o invia `total:restart`. Il processo scrive `{script}.pid`; eliminare il file lo termina.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Eseguire con un supervisore\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nAvvia il server HTTP e carica l'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no | `{}` | Opzioni di avvio (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Chiamato al posto di `listen()` quando l'applicazione è caricata. |\n\n`total4/debug` e `total4/release` la chiamano per te. `mode` è `'debug'` o `'release'`. Estrae i bundle, legge la configurazione, carica tutte le directory nel loro ordine, si mette in ascolto ed emette `load` e `ready`. Con `middleware`, il server non viene avviato finché non chiami `listen()`.\n\nExample: Senza i moduli di avvio\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nAvvia un server HTTPS e carica l'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` o `'release'`. |\n| `options` | `Object` | no | `{}` | Opzioni di avvio con `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Chiamato al posto di `listen()`. |\n\nFunziona come `HTTP()`. Passa il certificato in `options.https` come `{ key, cert }`: Buffer, percorsi di file o stringhe base64.\n\nExample: File del certificato\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nLa porta del server HTTP.\n\nReturns: `Number`\n\nQuando manca, viene usato un argomento numerico libero della riga di comando, poi `CONF.default_port`. `CONF.default_port = 'auto'` legge `process.env.PORT`. Il valore di riserva è `8000`.\n\nExample: Porta\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nL'indirizzo IP su cui il server è in ascolto.\n\nReturns: `String`\n\nIl valore predefinito è `CONF.default_ip`, poi `'0.0.0.0'`. I valori `'null'`, `'undefined'` e `'auto'` lasciano scegliere a Node.js.\n\nExample: Solo localhost\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nValori di configurazione che sovrascrivono i file di configurazione.\n\nReturns: `Object`\n\nL'oggetto viene unito a `CONF` all'avvio del server.\n\nExample: Nome\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nDirectory aggiuntive per il watcher di debug.\n\nReturns: `String[]`\n\nUn array di percorsi relativi alla directory dell'applicazione. Le modifiche al loro interno riavviano l'applicazione, come le modifiche nelle directory standard. Solo `total4/debug` la legge.\n\nExample: Osservare una directory\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nRicarica il browser quando cambiano viste, file pubblici o script.\n\nReturns: `Boolean|Number|String`\n\nSolo per `total4/debug`. `true` avvia un server WebSocket sulla porta `35729`; un numero imposta un'altra porta. Una stringa (un hostname) si collega invece al servizio di live reload di Total.js. Le viste e i file pubblici non riavviano l'applicazione, ricaricano solo la pagina.\n\nExample: Live reload\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nAvvia l'applicazione con l'inspector di Node.js.\n\nReturns: `Number`\n\nIl valore è la porta di `--inspect` (predefinita `9229`). Solo per `total4/debug`; il watcher aggiunge l'argomento al processo figlio.\n\nExample: Inspector\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nAvvia l'applicazione senza il server HTTP.\n\nReturns: `Boolean|String|String[]`\n\n`true` carica tutto con `LOAD()`; una stringa o un array viene passato a `LOAD()` come elenco dei tipi. Usalo per servizi in background.\n\nExample: Servizio\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nEsegue `total4/release` con un processo supervisore.\n\nReturns: `Boolean`\n\nCon `true`, il processo release esegue il fork dell'applicazione e la riavvia quando termina. L'argomento `--watcher` della riga di comando fa lo stesso.\n\nExample: Supervisore\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nControlla se i bundle vengono estratti all'avvio.\n\nReturns: `Boolean`\n\n`false` salta l'estrazione di `/bundles/` in `/.src/`, ma l'applicazione gira comunque da `/.src/` quando `/bundles/` esiste. Usalo quando i bundle sono già estratti.\n\nExample: Saltare l'estrazione\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nInstalla l'applicazione senza avviare il server HTTP.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | Cosa caricare. |\n| `directory` | `String` | no | `the directory of the script` | La directory dell'applicazione. |\n| `callback` | `Function` | no |  | Chiamata quando l'applicazione è caricata. |\n\nReturns: `Promise` Solo quando manca `callback`.\n\n`types` è un array o una stringa separata da virgole o spazi: `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. Un nome con il prefisso `no` lo esclude (`'nocontrollers'`). Quando almeno un nome non ha il prefisso, vengono caricati solo i tipi elencati. Senza `types` viene caricato tutto tranne bundle, pacchetti, componenti e temi. Aggiungi `debug` per girare in modalità debug (altrimenti `RELEASE` è `true`). Senza `service`, il timer interno della cache viene fermato. `directory` imposta la directory dell'applicazione; `'..'` indica la directory padre dello script. La configurazione viene sempre letta. `ready` viene emesso 500 ms dopo il caricamento. Senza callback restituisce una Promise.\n\nExample: Uno script\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nViene eseguita una volta quando il framework installa un file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Il valore di configurazione per questo file, oppure `undefined`. |\n\nOgni script in una directory installata può esportarla. Il framework la chiama subito dopo `require()` e poi la elimina. `options` è il valore di configurazione `CONF['{type}_{name}']`, per esempio `CONF.module_mail` per `/modules/mail.js`. I tipi sono `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` e `source`. Dopo di essa, il framework emette `ON('install', type, name, module)` e `ON('{type}_{name}', module)`.\n\nExample: Un modulo\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nRestituisce un modulo installato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del modulo. |\n\nReturns: `Object` Gli export del modulo, oppure `null`.\n\nI moduli provengono da `/modules/` e dai pacchetti. Il nome è il nome del file senza estensione (con le sottodirectory, `folder/name`). Un modulo che esporta `id` è disponibile anche con quell'id. Restituisce `null` quando il modulo non esiste.\n\nExample: Usare un modulo\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nTutti i moduli installati, per nome.\n\nReturns: `Object`\n\nLo stesso oggetto di `F.modules`. `MODS.mail` equivale a `MODULE('mail')`, tranne che un modulo mancante restituisce `undefined`.\n\nExample: Iterare\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nTutti i plugin installati, per nome.\n\nReturns: `Object`\n\nLo stesso oggetto di `F.plugins`. Un plugin è `plugins/{name}/index.js` oppure (un plugin `.html`) `plugins/{name}.html`. Ogni plugin riceve `id` (il suo nome). Un plugin `.html` esegue il codice del suo blocco `<script total>` e ogni blocco `<file name=\"...\">` viene scritto in un file temporaneo elencato in `plugin.files`.\n\nExample: Un plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nRestituisce un modello installato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del modello. |\n\nReturns: `Object` Gli export del modello.\n\nI modelli provengono da `/models/`. Il nome è il nome del file senza estensione. Restituisce `undefined` quando il modello non esiste.\n\nExample: Un modello\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nCarica uno script da `/source/` la prima volta che lo richiedi.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del file senza estensione. |\n\nReturns: `Object` Gli export dello script, oppure `null`.\n\n`SOURCE()` è un alias. Il file `/source/{name}.js` viene installato (viene eseguito il suo `exports.install()`) e messo in cache. Le chiamate successive restituiscono gli export dalla cache. Restituisce `null` quando il file non esiste.\n\nExample: Caricamento lazy\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nEsegue require di uno script relativo alla directory dell'applicazione.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Il percorso relativo alla directory dell'applicazione. |\n\nReturns: `Object` Gli export dello script.\n\nEquivale a `require(F.directory + '/' + path)`. Usala per caricare le tue librerie senza percorsi relativi che dipendono dal file corrente.\n\nExample: Una libreria\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nScarica uno script da un URL e ne esegue require.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL di un file JavaScript. |\n| `callback` | `Function(err, module, response)` | no |  | Chiamata quando lo script è caricato. |\n\nLo script viene salvato nella directory temporanea e caricato con `require()`. Le chiamate successive nello stesso processo restituiscono lo stesso modulo senza scaricarlo. Importa solo codice da una fonte di cui ti fidi: viene eseguito con tutti i permessi dell'applicazione.\n\nExample: Codice remoto\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nLa versione del framework come numero.\n\nReturns: `Number`\n\nVale `4099`. `F.is4` ha lo stesso valore. Usalo per verificare una versione minima.\n\nExample: Verifica\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nLa versione principale come stringa.\n\nReturns: `String`\n\nVale `'4'`. Fa parte dello user agent delle richieste `ACTION()` e della versione in `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nLa versione di Node.js.\n\nReturns: `String`\n\nIl valore di `process.version`, per esempio `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nLa versione di Node.js come numero.\n\nReturns: `Number`\n\n`process.version` senza `v` e senza punti, interpretato come intero: `'v18.17.0'` dà `18170`.\n\nExample: Confrontare\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true` quando l'applicazione gira da bundle estratti.\n\nReturns: `Boolean`\n\nLa directory dell'applicazione è allora `/.src/`, non la directory dello script di avvio.\n\n### F.isLoaded\n\nType: `property`\n\n`true` quando tutte le directory sono installate.\n\nReturns: `Boolean`\n\nViene impostato prima che vengano emessi `load` e `ready`.\n\nExample: Attendere il caricamento\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true` quando l'applicazione è stata avviata con `LOAD()`.\n\nReturns: `Boolean`\n\nAltrimenti è `false`. `F.isWorker` è simile, ma è `true` finché `HTTP()` o `HTTPS()` non avvia il server.\n\nExample: Saltare negli script\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nSempre `true` nel framework.\n\nReturns: `Boolean`\n\n`is_client` è sempre `false`. Permettono al codice condiviso con il browser di capire dove viene eseguito.\n\nExample: Codice condiviso\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nUn file che contiene un'intera applicazione o una sua parte.\n\nI bundle in `/bundles/` vengono estratti in `/.src/` all'avvio, poi i file dell'applicazione vengono copiati sopra di essi e l'applicazione gira da `/.src/`. I file `config*`, `sitemap`, `versions`, `workflows`, `dependencies` e `.resource` vengono uniti. Un file il cui nome inizia con `--` viene accodato al file con lo stesso nome senza il prefisso. I file esistenti in `/databases/` e `/updates/` vengono mantenuti. Un file `{name}.url` con un URL scarica il bundle all'avvio. I file che terminano con `-bk.bundle` o `_bk.bundle` vengono saltati. Crea un bundle con `total4 bundle`.\n\nExample: Struttura\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nEsegue l'applicazione da `/.src/` senza estrarre di nuovo i bundle.\n\nQuando questo file esiste nella radice, il framework usa `/.src/` così com'è e il watcher di debug osserva i file lì presenti, insieme alle viste e ai file pubblici. Usalo per modificare direttamente i file estratti di un bundle.\n\n### /.bundleignore\n\nType: `type`\n\nPercorsi che non vengono copiati in `/.src/` quando i bundle vengono estratti.\n\nUna regola per riga: `/path/` salta la directory con tutto il suo contenuto, `/path/*.ext` salta i file con quell'estensione in quella directory, `/path/file.ext` salta un singolo file. Funziona anche il vecchio nome `.bundlesignore`.\n\nExample: Regole\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nImpostalo a `shallow` per mantenere i bundle estratti.\n\nReturns: `String`\n\nCon `bundling : shallow` nella configurazione, il framework non pulisce `/.src/` e non estrae di nuovo i bundle quando esiste `/.src/bundle.json`.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrea un bundle dalla directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Il nome del file del bundle, con l'estensione `.bundle`. |\n\nIl nome di file predefinito è `app.bundle`. Gli script di avvio, i file `.pid`, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` e `/.git/` vengono esclusi. Il comando opposto, `total4 extract <filename>`, estrae un bundle o un pacchetto nella directory corrente.\n\nExample: Creare\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Estrarre\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nRestituisce il percorso di un file in un pacchetto estratto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome del pacchetto. |\n| `filename` | `String` | no |  | Un file all'interno del pacchetto. |\n\nReturns: `String` Il percorso assoluto.\n\nI pacchetti in `/packages/` (file o directory `name.package`) vengono estratti nella directory temporanea e il loro `index.js` viene installato. `PATH.package('name/file')` equivale a `PATH.package('name', 'file')`. `WORKER('@name/file')` e funzioni simili lo usano per il prefisso `@`.\n\nExample: Leggere un template\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JabnMm5VA60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/application-structure/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Štruktúra aplikácie","summary":"Štartovacie skripty, adresáre, bundly, balíky a globálne načítavače.","markdown":"---\ntitle: \"Štruktúra aplikácie\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/application-structure/\nupdated: 2026-11-16T15:41:20.819Z\n---\n\n# Štruktúra aplikácie\n\n> Štartovacie skripty, adresáre, bundly, balíky a globálne načítavače.\n\nFunkcie, flagy a možnosti, ktoré určujú, ako sa aplikácia Total.js 4 spúšťa a načítava. Príručka [Štruktúra aplikácie a režimy](../../guides/application-structure/) s príkladmi vysvetľuje poradie načítania, režimy debug a release a bundly; táto stránka je presná referencia.\n\nTestovanie má vlastnú stránku: [Testovanie](../testing/).\n\n## API\n\n### require('total4/debug')(options)\n\nType: `command`\n\nSpustí aplikáciu v režime debug s watcherom, ktorý ju pri zmenách reštartuje.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Štartovacie možnosti (`port`, `ip`, `watch`, `livereload`, `inspector`, `servicemode`, `https`, `config`...). |\n\nModul exportuje funkciu, ktorá berie štartovacie možnosti. Volajúci proces sa stane watcherom: forkne štartovací skript ako podproces, sleduje adresáre aplikácie a reštartuje podproces, keď sa zmení súbor. Podproces spustí `HTTP('debug', options)` (alebo `HTTPS()` s `options.https`, alebo `LOAD()` s `options.servicemode`). `DEBUG` je `true`. Watcher zapíše `{script}.pid`; zmazanie súboru ukončí oba procesy.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\n// options.watch = ['adminer'];\nrequire('total4/debug')(options);\n```\n\n### require('total4/release')(options)\n\nType: `command`\n\nSpustí aplikáciu v režime release.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no | `{}` | Štartovacie možnosti. |\n\nModul exportuje funkciu, ktorá berie rovnaké štartovacie možnosti ako `total4/debug`. `RELEASE` je `true` a súbory sa nesledujú. Predvolene aplikácia beží v aktuálnom procese. S argumentom `--watcher` alebo `options.watcher` sa proces stane supervízorom: forkne štartovací skript a spustí ho znova, keď skončí alebo pošle `total:restart`. Proces zapíše `{script}.pid`; zmazanie súboru ho ukončí.\n\nExample: index.js\n```js\nvar options = {};\n// options.port = 8000;\nrequire('total4/release')(options);\n```\n\nExample: Spustenie so supervízorom\n```bash\nnode index.js --watcher\n```\n\n### HTTP(mode, [options], [middleware])\n\nType: `method`\n\nSpustí HTTP server a načíta aplikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` alebo `'release'`. |\n| `options` | `Object` | no | `{}` | Štartovacie možnosti (`port`, `ip`, `unixsocket`, `config`, `bundling`...). |\n| `middleware` | `Function(listen)` | no |  | Volá sa namiesto `listen()`, keď je aplikácia načítaná. |\n\n`total4/debug` a `total4/release` ju volajú za teba. `mode` je `'debug'` alebo `'release'`. Rozbalí bundly, prečíta konfiguráciu, načíta všetky adresáre v ich poradí, začne počúvať a emituje `load` a `ready`. S `middleware` sa server nespustí, kým nezavoláš `listen()`.\n\nExample: Bez štartovacích modulov\n```js\nrequire('total4');\nHTTP('release', { port: 8000 });\n```\n\n### HTTPS(mode, [options], [middleware])\n\nType: `method`\n\nSpustí HTTPS server a načíta aplikáciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `mode` | `String` | yes |  | `'debug'` alebo `'release'`. |\n| `options` | `Object` | no | `{}` | Štartovacie možnosti s `https: { key, cert }`. |\n| `middleware` | `Function(listen)` | no |  | Volá sa namiesto `listen()`. |\n\nFunguje ako `HTTP()`. Certifikát odovzdaj v `options.https` ako `{ key, cert }`: ako Buffery, cesty k súborom alebo reťazce base64.\n\nExample: Súbory certifikátu\n```js\nrequire('total4');\nHTTPS('release', { port: 443, https: { key: 'keys/server.key', cert: 'keys/server.crt' } });\n```\n\n### options.port\n\nType: `config`\n\nPort HTTP servera.\n\nReturns: `Number`\n\nKeď chýba, použije sa voľný číselný argument príkazového riadku, potom `CONF.default_port`. `CONF.default_port = 'auto'` číta `process.env.PORT`. Záložná hodnota je `8000`.\n\nExample: Port\n```js\noptions.port = 8000;\n```\n\n### options.ip\n\nType: `config`\n\nIP adresa, na ktorej server počúva.\n\nReturns: `String`\n\nPredvolene `CONF.default_ip`, potom `'0.0.0.0'`. Hodnoty `'null'`, `'undefined'` a `'auto'` nechajú výber na Node.js.\n\nExample: Len localhost\n```js\noptions.ip = '127.0.0.1';\n```\n\n### options.config\n\nType: `config`\n\nKonfiguračné hodnoty, ktoré prepíšu konfiguračné súbory.\n\nReturns: `Object`\n\nObjekt sa pri štarte servera zlúči do `CONF`.\n\nExample: Názov\n```js\noptions.config = { name: 'Shop' };\n```\n\n### options.watch\n\nType: `config`\n\nĎalšie adresáre pre debug watcher.\n\nReturns: `String[]`\n\nPole ciest relatívnych k adresáru aplikácie. Zmeny v nich reštartujú aplikáciu, rovnako ako zmeny v štandardných adresároch. Číta ho len `total4/debug`.\n\nExample: Sledovanie adresára\n```js\noptions.watch = ['adminer', 'lib'];\n```\n\n### options.livereload\n\nType: `config`\n\nZnova načíta prehliadač, keď sa zmenia view, verejné súbory alebo skripty.\n\nReturns: `Boolean|Number|String`\n\nLen pre `total4/debug`. `true` spustí WebSocket server na porte `35729`; číslo nastaví iný port. Reťazec (názov hostiteľa) sa namiesto toho pripojí k službe live reload od Total.js. View a verejné súbory aplikáciu nereštartujú, len znova načítajú stránku.\n\nExample: Live reload\n```js\noptions.livereload = true;\n```\n\n### options.inspector\n\nType: `config`\n\nSpustí aplikáciu s inšpektorom Node.js.\n\nReturns: `Number`\n\nHodnota je port pre `--inspect` (predvolene `9229`). Len pre `total4/debug`; watcher pridá argument do forknutého procesu.\n\nExample: Inšpektor\n```js\noptions.inspector = 9229;\n```\n\n### options.servicemode\n\nType: `config`\n\nSpustí aplikáciu bez HTTP servera.\n\nReturns: `Boolean|String|String[]`\n\n`true` načíta všetko cez `LOAD()`; reťazec alebo pole sa odovzdá do `LOAD()` ako zoznam typov. Použi to pre služby na pozadí.\n\nExample: Služba\n```js\noptions.servicemode = 'config,definitions,modules,operations';\nrequire('total4/release')(options);\n```\n\n### options.watcher\n\nType: `config`\n\nSpustí `total4/release` s procesom supervízora.\n\nReturns: `Boolean`\n\nPri `true` proces release forkne aplikáciu a spustí ju znova, keď skončí. Rovnako funguje argument príkazového riadku `--watcher`.\n\nExample: Supervízor\n```js\noptions.watcher = true;\nrequire('total4/release')(options);\n```\n\n### options.bundling\n\nType: `config`\n\nUrčuje, či sa bundly pri štarte rozbalia.\n\nReturns: `Boolean`\n\n`false` preskočí rozbaľovanie `/bundles/` do `/.src/`, ale aplikácia stále beží z `/.src/`, keď `/bundles/` existuje. Použi to, keď sú bundly už rozbalené.\n\nExample: Preskočenie rozbaľovania\n```js\noptions.bundling = false;\n```\n\n### LOAD([types], [directory], [callback])\n\nType: `method`\n\nNainštaluje aplikáciu bez spustenia HTTP servera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `types` | `String|String[]` | no | `['nobundles', 'nopackages', 'nocomponents', 'nothemes']` | Čo sa má načítať. |\n| `directory` | `String` | no | `the directory of the script` | Adresár aplikácie. |\n| `callback` | `Function` | no |  | Volá sa, keď je aplikácia načítaná. |\n\nReturns: `Promise` Len keď `callback` chýba.\n\n`types` je pole alebo reťazec oddelený čiarkami alebo medzerami: `jsonschemas`, `modules`, `packages`, `models`, `schemas`, `actions`, `tasks`, `operations`, `themes`, `definitions`, `controllers`, `components`, `middleware`, `builds`, `extensions`, `plugins`, `flowstreams`, `preferences`, `bundles`, `versions`, `sitemap`, `service`. Názov s prefixom `no` ho vylúči (`'nocontrollers'`). Keď aspoň jeden názov nemá prefix, načítajú sa len uvedené typy. Bez `types` sa načíta všetko okrem bundlov, balíkov, komponentov a tém. Pridaj `debug` pre beh v režime debug (inak je `RELEASE` `true`). Bez `service` sa zastaví interný časovač cache. `directory` nastaví adresár aplikácie; `'..'` znamená nadradený adresár skriptu. Konfigurácia sa číta vždy. `ready` sa emituje 500 ms po načítaní. Bez callbacku vráti Promise.\n\nExample: Skript\n```js\nrequire('total4');\n\nLOAD('config,definitions,models', function() {\n\tMODEL('product').refresh();\n});\n```\n\nExample: Promise\n```js\nrequire('total4');\n\nasync function main() {\n\tawait LOAD('definitions,operations', '..');\n\tOPERATION('cleanup', NOOP);\n}\n\nmain();\n```\n\n### exports.install = function([options])\n\nType: `delegate`\n\nSpustí sa raz, keď framework inštaluje súbor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `options` | `Object` | no |  | Konfiguračná hodnota pre tento súbor alebo `undefined`. |\n\nMôže ju exportovať každý skript v inštalovanom adresári. Framework ju zavolá hneď po `require()` a potom ju zmaže. `options` je konfiguračná hodnota `CONF['{type}_{name}']`, napríklad `CONF.module_mail` pre `/modules/mail.js`. Typy sú `module`, `model`, `schema`, `action`, `task`, `operation`, `definition`, `controller`, `middleware`, `theme`, `plugin`, `package` a `source`. Potom framework emituje `ON('install', type, name, module)` a `ON('{type}_{name}', module)`.\n\nExample: Modul\n```js\n// /modules/counter.js\nvar count = 0;\n\nexports.install = function(options) {\n\tcount = (options && options.start) || 0;\n};\n\nexports.increment = function() {\n\treturn ++count;\n};\n```\n\n### MODULE(name)\n\nType: `method`\n\nVráti nainštalovaný modul.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modulu. |\n\nReturns: `Object` Exporty modulu alebo `null`.\n\nModuly pochádzajú z `/modules/` a z balíkov. Názov je názov súboru bez prípony (s podadresármi `folder/name`). Modul, ktorý exportuje `id`, je dostupný aj pod týmto id. Vráti `null`, keď modul neexistuje.\n\nExample: Použitie modulu\n```js\nMODULE('mail').send('info@example.com', 'Hello');\n```\n\n### MODS\n\nType: `property`\n\nVšetky nainštalované moduly podľa názvu.\n\nReturns: `Object`\n\nTen istý objekt ako `F.modules`. `MODS.mail` sa rovná `MODULE('mail')`, okrem toho, že chýbajúci modul dá `undefined`.\n\nExample: Prechádzanie\n```js\nfor (var name in MODS)\n\tconsole.log(name);\n```\n\n### PLUGINS\n\nType: `property`\n\nVšetky nainštalované pluginy podľa názvu.\n\nReturns: `Object`\n\nTen istý objekt ako `F.plugins`. Plugin je `plugins/{name}/index.js` alebo (plugin `.html`) `plugins/{name}.html`. Každý plugin dostane `id` (svoj názov). Plugin `.html` spustí kód svojho bloku `<script total>` a každý blok `<file name=\"...\">` sa zapíše do dočasného súboru uvedeného v `plugin.files`.\n\nExample: Plugin\n```js\n// /plugins/dashboard/index.js\nexports.install = function() {\n\tROUTE('GET /dashboard/', function() {\n\t\tthis.plain('Dashboard');\n\t});\n};\n\n// anywhere else\nPLUGINS.dashboard.id; // 'dashboard'\n```\n\n### MODEL(name)\n\nType: `method`\n\nVráti nainštalovaný model.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov modelu. |\n\nReturns: `Object` Exporty modelu.\n\nModely pochádzajú z `/models/`. Názov je názov súboru bez prípony. Vráti `undefined`, keď model neexistuje.\n\nExample: Model\n```js\n// /models/product.js\nexports.price = function(item) {\n\treturn item.price * 1.2;\n};\n\n// anywhere else\nvar price = MODEL('product').price({ price: 10 });\n```\n\n### INCLUDE(name)\n\nType: `method`\n\nNačíta skript z `/source/` pri prvej požiadavke naň.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov súboru bez prípony. |\n\nReturns: `Object` Exporty skriptu alebo `null`.\n\n`SOURCE()` je alias. Súbor `/source/{name}.js` sa nainštaluje (spustí sa jeho `exports.install()`) a uloží do cache. Ďalšie volania vrátia exporty z cache. Vráti `null`, keď súbor neexistuje.\n\nExample: Lenivé načítanie\n```js\nvar pdf = INCLUDE('pdf');\npdf && pdf.render(data);\n```\n\n### REQUIRE(path)\n\nType: `method`\n\nNačíta skript cez require relatívne k adresáru aplikácie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `path` | `String` | yes |  | Cesta relatívna k adresáru aplikácie. |\n\nReturns: `Object` Exporty skriptu.\n\nJe to `require(F.directory + '/' + path)`. Použi to na načítanie vlastných knižníc bez relatívnych ciest, ktoré závisia od aktuálneho súboru.\n\nExample: Knižnica\n```js\nvar tools = REQUIRE('lib/tools.js');\n```\n\n### IMPORT(url, [callback])\n\nType: `method`\n\nStiahne skript z URL a načíta ho cez require.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL súboru JavaScript. |\n| `callback` | `Function(err, module, response)` | no |  | Volá sa, keď je skript načítaný. |\n\nSkript sa uloží do dočasného adresára a načíta cez `require()`. Ďalšie volania v tom istom procese vrátia ten istý modul bez sťahovania. Importuj len kód zo zdroja, ktorému dôveruješ: beží s plnými právami aplikácie.\n\nExample: Vzdialený kód\n```js\nIMPORT('https://example.com/helpers.js', function(err, helpers) {\n\tif (!err)\n\t\thelpers.init();\n});\n```\n\n### F.version\n\nType: `property`\n\nVerzia frameworku ako číslo.\n\nReturns: `Number`\n\nJe to `4099`. `F.is4` má rovnakú hodnotu. Použi ju na kontrolu minimálnej verzie.\n\nExample: Kontrola\n```js\nif (F.version < 4096)\n\tconsole.warn('Update Total.js');\n```\n\n### F.version_header\n\nType: `property`\n\nHlavná verzia ako reťazec.\n\nReturns: `String`\n\nJe to `'4'`. Je súčasťou user agenta požiadaviek `ACTION()` a verzie v `F.usage()`.\n\n### F.version_node\n\nType: `property`\n\nVerzia Node.js.\n\nReturns: `String`\n\nHodnota `process.version`, napríklad `'v18.17.0'`.\n\n### F.version_node2\n\nType: `property` · Since: `0.0.96`\n\nVerzia Node.js ako číslo.\n\nReturns: `Number`\n\n`process.version` bez `v` a bodiek, spracované ako celé číslo: `'v18.17.0'` dá `18170`.\n\nExample: Porovnanie\n```js\nif (F.version_node2 >= 18000)\n\tconsole.log('Node.js 18 or newer');\n```\n\n### F.isBundle\n\nType: `property`\n\n`true`, keď aplikácia beží z rozbalených bundlov.\n\nReturns: `Boolean`\n\nAdresárom aplikácie je potom `/.src/`, nie adresár štartovacieho skriptu.\n\n### F.isLoaded\n\nType: `property`\n\n`true`, keď sú nainštalované všetky adresáre.\n\nReturns: `Boolean`\n\nNastaví sa pred emitovaním `load` a `ready`.\n\nExample: Čakanie na načítanie\n```js\nWAIT(() => F.isLoaded, function() {\n\t// the application is ready\n});\n```\n\n### isWORKER\n\nType: `property`\n\n`true`, keď bola aplikácia spustená cez `LOAD()`.\n\nReturns: `Boolean`\n\nInak je `false`. `F.isWorker` je podobné, ale je `true`, kým `HTTP()` alebo `HTTPS()` nespustí server.\n\nExample: Vynechanie v skriptoch\n```js\nif (!isWORKER)\n\tSCHEDULE('03:00', '1 day', cleanup);\n```\n\n### is_server\n\nType: `property`\n\nVo frameworku vždy `true`.\n\nReturns: `Boolean`\n\n`is_client` je vždy `false`. Umožňujú kódu zdieľanému s prehliadačom zistiť, kde beží.\n\nExample: Zdieľaný kód\n```js\nif (typeof(is_server) !== 'undefined' && is_server)\n\texports.format = format;\n```\n\n### /bundles/{name}.bundle\n\nType: `type`\n\nSúbor, ktorý obsahuje celú aplikáciu alebo jej časť.\n\nBundly v `/bundles/` sa pri štarte rozbalia do `/.src/`, potom sa cez ne skopírujú súbory aplikácie a aplikácia beží z `/.src/`. Súbory `config*`, `sitemap`, `versions`, `workflows`, `dependencies` a `.resource` sa zlúčia. Súbor, ktorého názov začína `--`, sa pripojí k súboru s rovnakým názvom bez prefixu. Existujúce súbory v `/databases/` a `/updates/` sa zachovajú. Súbor `{name}.url` s URL stiahne bundle pri štarte. Súbory, ktoré končia `-bk.bundle` alebo `_bk.bundle`, sa preskočia. Bundle vytvoríš cez `total4 bundle`.\n\nExample: Štruktúra\n```text\n/bundles/cms.bundle\n/bundles/extra.url\n/views/index.html\t\t  <- overrides the view from the bundle\n/public/css/--custom.css   <- appended to /public/css/custom.css\n/config\t\t\t\t\t <- merged with the config of the bundle\n```\n\n### /bundles.debug\n\nType: `type`\n\nSpustí aplikáciu z `/.src/` bez opätovného rozbalenia bundlov.\n\nKeď tento súbor existuje v koreni, framework použije `/.src/` tak, ako je, a debug watcher sleduje súbory v ňom spolu s view a verejnými súbormi. Použi ho, ak chceš priamo upravovať rozbalené súbory bundlu.\n\n### /.bundleignore\n\nType: `type`\n\nCesty, ktoré sa pri rozbaľovaní bundlov nekopírujú do `/.src/`.\n\nJedno pravidlo na riadok: `/path/` preskočí adresár so všetkým v ňom, `/path/*.ext` preskočí súbory s danou príponou v tom adresári, `/path/file.ext` preskočí jeden súbor. Funguje aj starší názov `.bundlesignore`.\n\nExample: Pravidlá\n```text\n/tests/\n/public/img/*.psd\n/views/demo.html\n```\n\n### bundling\n\nType: `config`\n\nNastav na `shallow`, aby sa rozbalené bundly zachovali.\n\nReturns: `String`\n\nS `bundling : shallow` v konfigurácii framework nevyčistí `/.src/` a nerozbalí bundly znova, keď existuje `/.src/bundle.json`.\n\nExample: config\n```text\nbundling\t\t  : shallow\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nVytvorí bundle z aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Názov súboru bundlu s príponou `.bundle`. |\n\nPredvolený názov súboru je `app.bundle`. Štartovacie skripty, súbory `.pid`, `package.json`, `readme.md`, `license.txt`, `/bundles/`, `/tmp/`, `/.src/` a `/.git/` sa vynechajú. Opačný príkaz, `total4 extract <filename>`, rozbalí bundle alebo balík do aktuálneho adresára.\n\nExample: Vytvorenie\n```bash\ntotal4 bundle cms.bundle\n```\n\nExample: Rozbalenie\n```bash\ntotal4 extract cms.bundle\n```\n\n### PATH.package(name, [filename])\n\nType: `method`\n\nVráti cestu k súboru v rozbalenom balíku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov balíka. |\n| `filename` | `String` | no |  | Súbor v balíku. |\n\nReturns: `String` Absolútna cesta.\n\nBalíky v `/packages/` (súbory alebo adresáre `name.package`) sa rozbalia do dočasného adresára a nainštaluje sa ich `index.js`. `PATH.package('name/file')` je to isté ako `PATH.package('name', 'file')`. `WORKER('@name/file')` a podobné funkcie ju používajú pre prefix `@`.\n\nExample: Čítanie šablóny\n```js\nvar html = F.Fs.readFileSync(PATH.package('invoices/template.html'), 'utf8');\n```\n","entries":[{"type":"command","name":"total4/debug","signature":"require('total4/debug')(options)","since":"","deprecated":false},{"type":"command","name":"total4/release","signature":"require('total4/release')(options)","since":"","deprecated":false},{"type":"method","name":"HTTP()","signature":"HTTP(mode, [options], [middleware])","since":"","deprecated":false},{"type":"method","name":"HTTPS()","signature":"HTTPS(mode, [options], [middleware])","since":"","deprecated":false},{"type":"config","name":"options.port","signature":"options.port","since":"","deprecated":false},{"type":"config","name":"options.ip","signature":"options.ip","since":"","deprecated":false},{"type":"config","name":"options.config","signature":"options.config","since":"","deprecated":false},{"type":"config","name":"options.watch","signature":"options.watch","since":"","deprecated":false},{"type":"config","name":"options.livereload","signature":"options.livereload","since":"","deprecated":false},{"type":"config","name":"options.inspector","signature":"options.inspector","since":"","deprecated":false},{"type":"config","name":"options.servicemode","signature":"options.servicemode","since":"","deprecated":false},{"type":"config","name":"options.watcher","signature":"options.watcher","since":"","deprecated":false},{"type":"config","name":"options.bundling","signature":"options.bundling","since":"","deprecated":false},{"type":"method","name":"LOAD()","signature":"LOAD([types], [directory], [callback])","since":"","deprecated":false},{"type":"delegate","name":"exports.install","signature":"exports.install = function([options])","since":"","deprecated":false},{"type":"method","name":"MODULE()","signature":"MODULE(name)","since":"","deprecated":false},{"type":"property","name":"MODS","signature":"MODS","since":"","deprecated":false},{"type":"property","name":"PLUGINS","signature":"PLUGINS","since":"","deprecated":false},{"type":"method","name":"MODEL()","signature":"MODEL(name)","since":"","deprecated":false},{"type":"method","name":"INCLUDE()","signature":"INCLUDE(name)","since":"","deprecated":false},{"type":"method","name":"REQUIRE()","signature":"REQUIRE(path)","since":"","deprecated":false},{"type":"method","name":"IMPORT()","signature":"IMPORT(url, [callback])","since":"","deprecated":false},{"type":"property","name":"F.version","signature":"F.version","since":"","deprecated":false},{"type":"property","name":"F.version_header","signature":"F.version_header","since":"","deprecated":false},{"type":"property","name":"F.version_node","signature":"F.version_node","since":"","deprecated":false},{"type":"property","name":"F.version_node2","signature":"F.version_node2","since":"0.0.96","deprecated":false},{"type":"property","name":"F.isBundle","signature":"F.isBundle","since":"","deprecated":false},{"type":"property","name":"F.isLoaded","signature":"F.isLoaded","since":"","deprecated":false},{"type":"property","name":"isWORKER","signature":"isWORKER","since":"","deprecated":false},{"type":"property","name":"is_server","signature":"is_server","since":"","deprecated":false},{"type":"type","name":".bundle","signature":"/bundles/{name}.bundle","since":"","deprecated":false},{"type":"type","name":"bundles.debug","signature":"/bundles.debug","since":"","deprecated":false},{"type":"type","name":".bundleignore","signature":"/.bundleignore","since":"","deprecated":false},{"type":"config","name":"CONF.bundling","signature":"bundling","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"method","name":"PATH.package()","signature":"PATH.package(name, [filename])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:20.819Z"}
{"id":"JafRp21vd60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Testing","summary":"TESTER(), TEST(), ACTION() and the methods of a test request.","markdown":"---\ntitle: Testing\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Testing\n\n> TESTER(), TEST(), ACTION() and the methods of a test request.\n\nThe testing tools of Total.js 4. The guide [Testing](../../guides/testing/) explains how to use them with examples.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nRuns groups of tests in order and stops at the first failure.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Declares the groups and calls `start()`. |\n| `options` | `Object` | no |  | `{ silent: true }` hides the console output. |\n\n`group(name, fn(test, cleanup))` declares a group. Inside it, `test([name], fn(next))` declares a test; call `next()` on success or `next(err)` on failure. `cleanup(fn)` sets a function that runs after the group (with the error object `{ group, test, err }` when a test failed). `start([callback])` runs all groups. A failure calls the group cleanup and the callback of `start()` with the error, then throws an Error with the group and test names. Passed tests print `[OK]`, the end prints `[DONE] in N ms`; `options.silent` hides these lines.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nSends a virtual request to a route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The method and the path, e.g. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | The body of the request. |\n| `callback` | `Function(err, response)` | no |  | Called with the response. |\n\nReturns: `Controller` The controller of the request, or `undefined` when no route matches.\n\n`url` is `'METHOD /path/'`, with an optional query string. The prefix `+` runs the request as authorized, `-` as unauthorized. `'API /url/ schema'` calls a Route API action. The request has the header `x-test: 1` and the IP of the server. `data` becomes the body. The callback receives the result of the route (`err, response`), or `'404'` when no route matches. Returns the controller, so you can set `user`, `session` or `query` before it runs.\n\nExample: Authorized request\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nRuns a list of virtual requests and reports the result.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Declares the requests. |\n| `done` | `Function(errors, output)|Controller` | no |  | Receives the result. |\n\nReturns: `Object` The test instance.\n\n`add(url, name)` adds a request (see `ACTION()`) and returns a test action. The requests run one after another. `response` collects responses of actions with `id()`. `done` is a function `(errors, output)`, or a controller: it then answers with status `200` or `409` and the output as JSON (XHR) or as an HTML page. `output` is `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: A test route\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nSets the body of a test request.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | The body. |\n\nReturns: `Object` The test action.\n\n`body()` is an alias. The other setters are `query(obj)`, `user(obj)`, `session(obj)` and `url(url)`. Each returns the action, so you can chain them.\n\nExample: Chain\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nMarks the request as failed unless `fn` returns `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Returns `true` when the response is correct. |\n\nReturns: `Object` The test action.\n\n`res` has `err` (also `error`), `value`, `response` (all collected responses) and `name`. `res.invalid(err)` (also `throw()`) sets the error shown in the output. `fail(fn)` is the opposite: the request fails when `fn` returns `true`. Without `pass` or `fail`, the request fails when the route returns an error.\n\nExample: Check the value\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nPrepares a test request just before it runs.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Changes the action before it runs. |\n\nReturns: `Object` The test action.\n\nUse it to build the request from earlier responses, for example an id saved with `id(name)`. Return `false` to skip the request. `done(fn(value))` runs on success, `callback(fn(err, value))` always, and `log(fn(err, value))` before the check.\n\nExample: Use an earlier response\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafRp21vd60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Tests","summary":"TESTER(), TEST(), ACTION() und die Methoden eines Test-Requests.","markdown":"---\ntitle: Tests\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Tests\n\n> TESTER(), TEST(), ACTION() und die Methoden eines Test-Requests.\n\nDie Testwerkzeuge von Total.js 4. Der Guide [Tests](../../guides/testing/) erklärt mit Beispielen, wie du sie verwendest.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nFührt Testgruppen der Reihe nach aus und hält beim ersten Fehler an.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Deklariert die Gruppen und ruft `start()` auf. |\n| `options` | `Object` | no |  | `{ silent: true }` blendet die Konsolenausgabe aus. |\n\n`group(name, fn(test, cleanup))` deklariert eine Gruppe. Darin deklariert `test([name], fn(next))` einen Test; rufe bei Erfolg `next()` oder bei einem Fehler `next(err)` auf. `cleanup(fn)` setzt eine Funktion, die nach der Gruppe läuft (mit dem Fehlerobjekt `{ group, test, err }`, wenn ein Test fehlgeschlagen ist). `start([callback])` führt alle Gruppen aus. Ein Fehler ruft das Cleanup der Gruppe und den Callback von `start()` mit dem Fehler auf und wirft dann einen Error mit den Namen der Gruppe und des Tests. Bestandene Tests geben `[OK]` aus, das Ende gibt `[DONE] in N ms` aus; `options.silent` blendet diese Zeilen aus.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nSendet einen virtuellen Request an eine Route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die Methode und der Pfad, z. B. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | Der Body des Requests. |\n| `callback` | `Function(err, response)` | no |  | Wird mit der Response aufgerufen. |\n\nReturns: `Controller` Der Controller des Requests oder `undefined`, wenn keine Route passt.\n\n`url` ist `'METHOD /path/'`, optional mit einem Query-String. Das Präfix `+` führt den Request als autorisiert aus, `-` als nicht autorisiert. `'API /url/ schema'` ruft eine Route-API-Action auf. Der Request hat den Header `x-test: 1` und die IP des Servers. `data` wird zum Body. Der Callback erhält das Ergebnis der Route (`err, response`) oder `'404'`, wenn keine Route passt. Gibt den Controller zurück, sodass du `user`, `session` oder `query` setzen kannst, bevor er läuft.\n\nExample: Autorisierter Request\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nFührt eine Liste virtueller Requests aus und meldet das Ergebnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Deklariert die Requests. |\n| `done` | `Function(errors, output)|Controller` | no |  | Erhält das Ergebnis. |\n\nReturns: `Object` Die Test-Instanz.\n\n`add(url, name)` fügt einen Request hinzu (siehe `ACTION()`) und gibt eine Test-Action zurück. Die Requests laufen nacheinander. `response` sammelt die Responses von Actions mit `id()`. `done` ist eine Funktion `(errors, output)` oder ein Controller: Er antwortet dann mit dem Status `200` oder `409` und der Ausgabe als JSON (XHR) oder als HTML-Seite. `output` ist `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: Eine Test-Route\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nSetzt den Body eines Test-Requests.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | Der Body. |\n\nReturns: `Object` Die Test-Action.\n\n`body()` ist ein Alias. Die anderen Setter sind `query(obj)`, `user(obj)`, `session(obj)` und `url(url)`. Jeder gibt die Action zurück, sodass du sie verketten kannst.\n\nExample: Verketten\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nMarkiert den Request als fehlgeschlagen, außer `fn` gibt `true` zurück.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Gibt `true` zurück, wenn die Response korrekt ist. |\n\nReturns: `Object` Die Test-Action.\n\n`res` hat `err` (auch `error`), `value`, `response` (alle gesammelten Responses) und `name`. `res.invalid(err)` (auch `throw()`) setzt den Fehler, der in der Ausgabe angezeigt wird. `fail(fn)` ist das Gegenteil: Der Request schlägt fehl, wenn `fn` `true` zurückgibt. Ohne `pass` oder `fail` schlägt der Request fehl, wenn die Route einen Fehler zurückgibt.\n\nExample: Den Wert prüfen\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nBereitet einen Test-Request direkt vor seiner Ausführung vor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Ändert die Action, bevor sie läuft. |\n\nReturns: `Object` Die Test-Action.\n\nVerwende es, um den Request aus früheren Responses aufzubauen, zum Beispiel mit einer per `id(name)` gespeicherten ID. Gib `false` zurück, um den Request zu überspringen. `done(fn(value))` läuft bei Erfolg, `callback(fn(err, value))` immer und `log(fn(err, value))` vor der Prüfung.\n\nExample: Eine frühere Response verwenden\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafRp21vd60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Pruebas","summary":"TESTER(), TEST(), ACTION() y los métodos de una petición de prueba.","markdown":"---\ntitle: Pruebas\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Pruebas\n\n> TESTER(), TEST(), ACTION() y los métodos de una petición de prueba.\n\nLas herramientas de pruebas de Total.js 4. La guía [Pruebas](../../guides/testing/) explica cómo usarlas con ejemplos.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nEjecuta grupos de pruebas en orden y se detiene en el primer fallo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Declara los grupos y llama a `start()`. |\n| `options` | `Object` | no |  | `{ silent: true }` oculta la salida de la consola. |\n\n`group(name, fn(test, cleanup))` declara un grupo. Dentro de él, `test([name], fn(next))` declara una prueba; llama a `next()` si tiene éxito o a `next(err)` si falla. `cleanup(fn)` define una función que se ejecuta después del grupo (con el objeto de error `{ group, test, err }` cuando una prueba falló). `start([callback])` ejecuta todos los grupos. Un fallo llama a la limpieza del grupo y al callback de `start()` con el error, y después lanza un Error con los nombres del grupo y de la prueba. Las pruebas superadas imprimen `[OK]`, el final imprime `[DONE] in N ms`; `options.silent` oculta estas líneas.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nEnvía una petición virtual a una ruta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | El método y la ruta, p. ej. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | El cuerpo de la petición. |\n| `callback` | `Function(err, response)` | no |  | Se llama con la respuesta. |\n\nReturns: `Controller` El controlador de la petición, o `undefined` cuando ninguna ruta coincide.\n\n`url` es `'METHOD /path/'`, con un query string opcional. El prefijo `+` ejecuta la petición como autorizada, `-` como no autorizada. `'API /url/ schema'` llama a una acción de Route API. La petición tiene la cabecera `x-test: 1` y la IP del servidor. `data` se convierte en el cuerpo. El callback recibe el resultado de la ruta (`err, response`), o `'404'` cuando ninguna ruta coincide. Devuelve el controlador, así que puedes definir `user`, `session` o `query` antes de que se ejecute.\n\nExample: Petición autorizada\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nEjecuta una lista de peticiones virtuales e informa del resultado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Declara las peticiones. |\n| `done` | `Function(errors, output)|Controller` | no |  | Recibe el resultado. |\n\nReturns: `Object` La instancia de la prueba.\n\n`add(url, name)` añade una petición (consulta `ACTION()`) y devuelve una acción de prueba. Las peticiones se ejecutan una tras otra. `response` recoge las respuestas de las acciones con `id()`. `done` es una función `(errors, output)`, o un controlador: en ese caso responde con el estado `200` o `409` y la salida como JSON (XHR) o como página HTML. `output` es `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: Una ruta de prueba\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nDefine el cuerpo de una petición de prueba.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | El cuerpo. |\n\nReturns: `Object` La acción de prueba.\n\n`body()` es un alias. Los demás setters son `query(obj)`, `user(obj)`, `session(obj)` y `url(url)`. Cada uno devuelve la acción, así que puedes encadenarlos.\n\nExample: Encadenar\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nMarca la petición como fallida salvo que `fn` devuelva `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Devuelve `true` cuando la respuesta es correcta. |\n\nReturns: `Object` La acción de prueba.\n\n`res` tiene `err` (también `error`), `value`, `response` (todas las respuestas recogidas) y `name`. `res.invalid(err)` (también `throw()`) define el error que se muestra en la salida. `fail(fn)` es lo contrario: la petición falla cuando `fn` devuelve `true`. Sin `pass` ni `fail`, la petición falla cuando la ruta devuelve un error.\n\nExample: Comprobar el valor\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nPrepara una petición de prueba justo antes de que se ejecute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Cambia la acción antes de que se ejecute. |\n\nReturns: `Object` La acción de prueba.\n\nÚsalo para construir la petición a partir de respuestas anteriores, por ejemplo un id guardado con `id(name)`. Devuelve `false` para omitir la petición. `done(fn(value))` se ejecuta si tiene éxito, `callback(fn(err, value))` siempre y `log(fn(err, value))` antes de la comprobación.\n\nExample: Usar una respuesta anterior\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafRp21vd60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Tests","summary":"TESTER(), TEST(), ACTION() et les méthodes d'une requête de test.","markdown":"---\ntitle: Tests\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Tests\n\n> TESTER(), TEST(), ACTION() et les méthodes d'une requête de test.\n\nLes outils de test de Total.js 4. Le guide [Tests](../../guides/testing/) explique comment les utiliser avec des exemples.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nExécute des groupes de tests dans l'ordre et s'arrête au premier échec.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Déclare les groupes et appelle `start()`. |\n| `options` | `Object` | no |  | `{ silent: true }` masque la sortie de la console. |\n\n`group(name, fn(test, cleanup))` déclare un groupe. À l'intérieur, `test([name], fn(next))` déclare un test ; appelle `next()` en cas de succès ou `next(err)` en cas d'échec. `cleanup(fn)` définit une fonction qui s'exécute après le groupe (avec l'objet d'erreur `{ group, test, err }` lorsqu'un test a échoué). `start([callback])` exécute tous les groupes. Un échec appelle le nettoyage du groupe et le callback de `start()` avec l'erreur, puis lève une Error avec les noms du groupe et du test. Les tests réussis affichent `[OK]`, la fin affiche `[DONE] in N ms` ; `options.silent` masque ces lignes.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nEnvoie une requête virtuelle à une route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La méthode et le chemin, par ex. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | Le corps de la requête. |\n| `callback` | `Function(err, response)` | no |  | Appelé avec la réponse. |\n\nReturns: `Controller` Le contrôleur de la requête, ou `undefined` lorsqu'aucune route ne correspond.\n\n`url` est `'METHOD /path/'`, avec une query string facultative. Le préfixe `+` exécute la requête comme autorisée, `-` comme non autorisée. `'API /url/ schema'` appelle une action de Route API. La requête possède l'en-tête `x-test: 1` et l'IP du serveur. `data` devient le corps. Le callback reçoit le résultat de la route (`err, response`), ou `'404'` lorsqu'aucune route ne correspond. Renvoie le contrôleur, tu peux donc définir `user`, `session` ou `query` avant son exécution.\n\nExample: Requête autorisée\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nExécute une liste de requêtes virtuelles et rapporte le résultat.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Déclare les requêtes. |\n| `done` | `Function(errors, output)|Controller` | no |  | Reçoit le résultat. |\n\nReturns: `Object` L'instance de test.\n\n`add(url, name)` ajoute une requête (voir `ACTION()`) et renvoie une action de test. Les requêtes s'exécutent l'une après l'autre. `response` collecte les réponses des actions avec `id()`. `done` est une fonction `(errors, output)`, ou un contrôleur : il répond alors avec le statut `200` ou `409` et la sortie en JSON (XHR) ou sous forme de page HTML. `output` est `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: Une route de test\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nDéfinit le corps d'une requête de test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | Le corps. |\n\nReturns: `Object` L'action de test.\n\n`body()` est un alias. Les autres setters sont `query(obj)`, `user(obj)`, `session(obj)` et `url(url)`. Chacun renvoie l'action, tu peux donc les enchaîner.\n\nExample: Enchaîner\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nMarque la requête comme échouée sauf si `fn` renvoie `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Renvoie `true` lorsque la réponse est correcte. |\n\nReturns: `Object` L'action de test.\n\n`res` possède `err` (aussi `error`), `value`, `response` (toutes les réponses collectées) et `name`. `res.invalid(err)` (aussi `throw()`) définit l'erreur affichée dans la sortie. `fail(fn)` est l'inverse : la requête échoue lorsque `fn` renvoie `true`. Sans `pass` ni `fail`, la requête échoue lorsque la route renvoie une erreur.\n\nExample: Vérifier la valeur\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nPrépare une requête de test juste avant son exécution.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Modifie l'action avant son exécution. |\n\nReturns: `Object` L'action de test.\n\nUtilise-la pour construire la requête à partir des réponses précédentes, par exemple un id enregistré avec `id(name)`. Renvoie `false` pour ignorer la requête. `done(fn(value))` s'exécute en cas de succès, `callback(fn(err, value))` toujours, et `log(fn(err, value))` avant la vérification.\n\nExample: Utiliser une réponse précédente\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafRp21vd60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Test","summary":"TESTER(), TEST(), ACTION() e i metodi di una richiesta di test.","markdown":"---\ntitle: Test\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Test\n\n> TESTER(), TEST(), ACTION() e i metodi di una richiesta di test.\n\nGli strumenti di test di Total.js 4. La guida [Test](../../guides/testing/) spiega come usarli con esempi.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nEsegue gruppi di test in ordine e si ferma al primo fallimento.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Dichiara i gruppi e chiama `start()`. |\n| `options` | `Object` | no |  | `{ silent: true }` nasconde l'output della console. |\n\n`group(name, fn(test, cleanup))` dichiara un gruppo. Al suo interno, `test([name], fn(next))` dichiara un test; chiama `next()` in caso di successo o `next(err)` in caso di fallimento. `cleanup(fn)` imposta una funzione che viene eseguita dopo il gruppo (con l'oggetto errore `{ group, test, err }` quando un test è fallito). `start([callback])` esegue tutti i gruppi. Un fallimento chiama il cleanup del gruppo e la callback di `start()` con l'errore, poi lancia un Error con i nomi del gruppo e del test. I test superati stampano `[OK]`, la fine stampa `[DONE] in N ms`; `options.silent` nasconde queste righe.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nInvia una richiesta virtuale a una route.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Il metodo e il percorso, ad es. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | Il body della richiesta. |\n| `callback` | `Function(err, response)` | no |  | Chiamata con la risposta. |\n\nReturns: `Controller` Il controller della richiesta, oppure `undefined` quando nessuna route corrisponde.\n\n`url` è `'METHOD /path/'`, con una query string facoltativa. Il prefisso `+` esegue la richiesta come autorizzata, `-` come non autorizzata. `'API /url/ schema'` chiama un'azione di Route API. La richiesta ha l'header `x-test: 1` e l'IP del server. `data` diventa il body. La callback riceve il risultato della route (`err, response`), oppure `'404'` quando nessuna route corrisponde. Restituisce il controller, così puoi impostare `user`, `session` o `query` prima che venga eseguito.\n\nExample: Richiesta autorizzata\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nEsegue un elenco di richieste virtuali e riporta il risultato.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Dichiara le richieste. |\n| `done` | `Function(errors, output)|Controller` | no |  | Riceve il risultato. |\n\nReturns: `Object` L'istanza del test.\n\n`add(url, name)` aggiunge una richiesta (vedi `ACTION()`) e restituisce un'azione di test. Le richieste vengono eseguite una dopo l'altra. `response` raccoglie le risposte delle azioni con `id()`. `done` è una funzione `(errors, output)`, oppure un controller: in quel caso risponde con lo stato `200` o `409` e l'output come JSON (XHR) o come pagina HTML. `output` è `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: Una route di test\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nImposta il body di una richiesta di test.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | Il body. |\n\nReturns: `Object` L'azione di test.\n\n`body()` è un alias. Gli altri setter sono `query(obj)`, `user(obj)`, `session(obj)` e `url(url)`. Ognuno restituisce l'azione, così puoi concatenarli.\n\nExample: Concatenare\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nSegna la richiesta come fallita a meno che `fn` non restituisca `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Restituisce `true` quando la risposta è corretta. |\n\nReturns: `Object` L'azione di test.\n\n`res` ha `err` (anche `error`), `value`, `response` (tutte le risposte raccolte) e `name`. `res.invalid(err)` (anche `throw()`) imposta l'errore mostrato nell'output. `fail(fn)` è l'opposto: la richiesta fallisce quando `fn` restituisce `true`. Senza `pass` o `fail`, la richiesta fallisce quando la route restituisce un errore.\n\nExample: Verificare il valore\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nPrepara una richiesta di test subito prima che venga eseguita.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Modifica l'azione prima che venga eseguita. |\n\nReturns: `Object` L'azione di test.\n\nUsalo per costruire la richiesta a partire da risposte precedenti, per esempio un id salvato con `id(name)`. Restituisci `false` per saltare la richiesta. `done(fn(value))` viene eseguito in caso di successo, `callback(fn(err, value))` sempre e `log(fn(err, value))` prima della verifica.\n\nExample: Usare una risposta precedente\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafRp21vd60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/testing/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Testovanie","summary":"TESTER(), TEST(), ACTION() a metódy testovacej požiadavky.","markdown":"---\ntitle: Testovanie\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/testing/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Testovanie\n\n> TESTER(), TEST(), ACTION() a metódy testovacej požiadavky.\n\nNástroje na testovanie v Total.js 4. Príručka [Testovanie](../../guides/testing/) vysvetľuje ich použitie na príkladoch.\n\n## API\n\n### TESTER(callback(group, start), [options])\n\nType: `method`\n\nSpúšťa skupiny testov v poradí a zastaví sa pri prvom zlyhaní.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `callback` | `Function(group, start)` | yes |  | Deklaruje skupiny a zavolá `start()`. |\n| `options` | `Object` | no |  | `{ silent: true }` skryje výstup do konzoly. |\n\n`group(name, fn(test, cleanup))` deklaruje skupinu. V nej `test([name], fn(next))` deklaruje test; pri úspechu zavolaj `next()`, pri zlyhaní `next(err)`. `cleanup(fn)` nastaví funkciu, ktorá sa spustí po skupine (s chybovým objektom `{ group, test, err }`, keď test zlyhal). `start([callback])` spustí všetky skupiny. Zlyhanie zavolá cleanup skupiny a callback z `start()` s chybou a potom vyhodí Error s názvami skupiny a testu. Úspešné testy vypíšu `[OK]`, koniec vypíše `[DONE] in N ms`; `options.silent` tieto riadky skryje.\n\nExample: tests/index.js\n```js\nrequire('total4');\n\nLOAD('config,definitions,schemas,controllers', function() {\n\tTESTER(function(group, start) {\n\n\t\tgroup('Users', function(test, cleanup) {\n\n\t\t\ttest('Create', function(next) {\n\t\t\t\tACTION('POST /api/users/', { name: 'Peter' }, function(err) {\n\t\t\t\t\tnext(err);\n\t\t\t\t});\n\t\t\t});\n\n\t\t\tcleanup(function(err) {\n\t\t\t\t// remove test data\n\t\t\t});\n\t\t});\n\n\t\tstart(function() {\n\t\t\tprocess.exit(0);\n\t\t});\n\t});\n});\n```\n\n### ACTION(url, [data], [callback])\n\nType: `method` · Since: `0.0.96`\n\nPošle virtuálnu požiadavku na trasu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Metóda a cesta, napr. `'GET /api/products/'`. |\n| `data` | `Object` | no |  | Telo požiadavky. |\n| `callback` | `Function(err, response)` | no |  | Volá sa s odpoveďou. |\n\nReturns: `Controller` Kontrolér požiadavky alebo `undefined`, keď žiadna trasa nezodpovedá.\n\n`url` je `'METHOD /path/'` s voliteľným query stringom. Prefix `+` spustí požiadavku ako autorizovanú, `-` ako neautorizovanú. `'API /url/ schema'` zavolá akciu Route API. Požiadavka má hlavičku `x-test: 1` a IP servera. `data` sa stanú telom. Callback dostane výsledok trasy (`err, response`) alebo `'404'`, keď žiadna trasa nezodpovedá. Vráti kontrolér, takže môžeš nastaviť `user`, `session` alebo `query` predtým, ako sa spustí.\n\nExample: Autorizovaná požiadavka\n```js\nvar ctrl = ACTION('+POST /api/orders/', { product: 'A1' }, function(err, response) {\n\tconsole.log(err, response);\n});\nctrl.user = { id: 'test' };\n```\n\n### TEST(fn(add, response), [done])\n\nType: `method` · Since: `0.0.96`\n\nSpustí zoznam virtuálnych požiadaviek a oznámi výsledok.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(add, response)` | yes |  | Deklaruje požiadavky. |\n| `done` | `Function(errors, output)|Controller` | no |  | Dostane výsledok. |\n\nReturns: `Object` Inštancia testu.\n\n`add(url, name)` pridá požiadavku (pozri `ACTION()`) a vráti testovaciu akciu. Požiadavky sa spúšťajú jedna po druhej. `response` zbiera odpovede akcií s `id()`. `done` je funkcia `(errors, output)` alebo kontrolér: ten potom odpovie stavom `200` alebo `409` a výstupom ako JSON (XHR) alebo ako HTML stránka. `output` je `{ items: [{ failed, name, error, ts }], failed }`.\n\nExample: Testovacia trasa\n```js\nexports.install = function() {\n\tROUTE('GET /tests/', tests);\n};\n\nfunction tests() {\n\tTEST(function(add, response) {\n\t\tadd('POST /api/products/', 'Create a product').data({ name: 'Test' }).id('product');\n\t\tadd('GET /api/products/', 'List products').pass(function(res) {\n\t\t\treturn res.value instanceof Array;\n\t\t});\n\t}, this);\n}\n```\n\n### action.data(body)\n\nType: `method` · Since: `0.0.96`\n\nNastaví telo testovacej požiadavky.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `body` | `Object` | yes |  | Telo. |\n\nReturns: `Object` Testovacia akcia.\n\n`body()` je alias. Ostatné settery sú `query(obj)`, `user(obj)`, `session(obj)` a `url(url)`. Každý vracia akciu, takže ich môžeš reťaziť.\n\nExample: Reťazenie\n```js\nadd('+POST /api/orders/', 'Order').data({ product: 'A1' }).user({ id: 'admin', sa: true });\n```\n\n### action.pass(fn(res))\n\nType: `method` · Since: `0.0.96`\n\nOznačí požiadavku ako neúspešnú, pokiaľ `fn` nevráti `true`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(res)` | yes |  | Vráti `true`, keď je odpoveď správna. |\n\nReturns: `Object` Testovacia akcia.\n\n`res` má `err` (aj `error`), `value`, `response` (všetky zozbierané odpovede) a `name`. `res.invalid(err)` (aj `throw()`) nastaví chybu zobrazenú vo výstupe. `fail(fn)` je opak: požiadavka zlyhá, keď `fn` vráti `true`. Bez `pass` alebo `fail` požiadavka zlyhá, keď trasa vráti chybu.\n\nExample: Kontrola hodnoty\n```js\nadd('GET /api/products/', 'Products').pass(function(res) {\n\tif (!res.value.length)\n\t\tres.invalid('Empty list');\n\treturn res.value.length > 0;\n});\n```\n\n### action.make(fn(action, response))\n\nType: `method` · Since: `0.0.96`\n\nPripraví testovaciu požiadavku tesne pred jej spustením.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(action, response)` | yes |  | Zmení akciu pred jej spustením. |\n\nReturns: `Object` Testovacia akcia.\n\nPouži ju na zostavenie požiadavky z predchádzajúcich odpovedí, napríklad z id uloženého cez `id(name)`. Vráť `false`, ak chceš požiadavku preskočiť. `done(fn(value))` sa spustí pri úspechu, `callback(fn(err, value))` vždy a `log(fn(err, value))` pred kontrolou.\n\nExample: Použitie predchádzajúcej odpovede\n```js\nadd('POST /api/products/', 'Create').data({ name: 'A' }).id('created');\nadd('', 'Read').make(function(action, response) {\n\t// response.created is the response of the request with id('created')\n\taction.url('GET /api/products/' + response.created.id + '/');\n});\n```\n","entries":[{"type":"method","name":"TESTER()","signature":"TESTER(callback(group, start), [options])","since":"","deprecated":false},{"type":"method","name":"ACTION()","signature":"ACTION(url, [data], [callback])","since":"0.0.96","deprecated":false},{"type":"method","name":"TEST()","signature":"TEST(fn(add, response), [done])","since":"0.0.96","deprecated":false},{"type":"method","name":"test.data()","signature":"action.data(body)","since":"0.0.96","deprecated":false},{"type":"method","name":"test.pass()","signature":"action.pass(fn(res))","since":"0.0.96","deprecated":false},{"type":"method","name":"test.make()","signature":"action.make(fn(action, response))","since":"0.0.96","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"LDAP","summary":"LDAP() and its options.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() and its options.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nReads persons, groups or one user profile from an LDAP server (for example Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` of the server. The port defaults to `389`. |\n| `opt.user` | `String` | yes |  | The DN or user name used to bind. |\n| `opt.password` | `String` | yes |  | The password used to bind. |\n| `opt.type` | `String` | yes |  | `person`, `group` or `profile` (searched as `objectClass`). |\n| `opt.dn` | `String` | no |  | The base DN of the search, for example `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | The `sAMAccountName` of the user, required for the `profile` type. |\n| `opt.noauth` | `Boolean` | no | `false` | Skips the bind and searches anonymously. |\n| `callback` | `Function(err, response)` | no |  | Receives an array of entries, or one object for `profile`. |\n\nReturns: `Promise` Only when the callback is not used.\n\nOpens a TCP connection to `opt.ldap`, binds with `opt.user` and `opt.password` (unless `opt.noauth` is `true`) and searches `opt.dn` (subtree scope) for entries with `objectClass` equal to `opt.type`.\n\nThe `profile` type searches for one `person` whose `sAMAccountName` equals `opt.login` and returns a single object (or `null`). When `opt.dn` is empty, the framework uses `opt.user` as the base DN and returns the profile of the bound user.\n\nEach entry is an object with attribute names as keys. An attribute with more values becomes an array; `objectGUID` and `objectSid` are returned as hex strings. Without a callback the method returns a Promise. The changelog marks the method as experimental.\n\nExample: Read all groups\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Load one profile with a Promise\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"LDAP","summary":"LDAP() und seine Optionen.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() und seine Optionen.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nLiest Personen, Gruppen oder ein Benutzerprofil von einem LDAP-Server (zum Beispiel Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` des Servers. Der Port ist standardmäßig `389`. |\n| `opt.user` | `String` | yes |  | Die DN oder der Benutzername für den Bind. |\n| `opt.password` | `String` | yes |  | Das Passwort für den Bind. |\n| `opt.type` | `String` | yes |  | `person`, `group` oder `profile` (gesucht als `objectClass`). |\n| `opt.dn` | `String` | no |  | Die Basis-DN der Suche, zum Beispiel `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | Der `sAMAccountName` des Benutzers, erforderlich für den Typ `profile`. |\n| `opt.noauth` | `Boolean` | no | `false` | Überspringt den Bind und sucht anonym. |\n| `callback` | `Function(err, response)` | no |  | Erhält ein Array von Einträgen oder bei `profile` ein Objekt. |\n\nReturns: `Promise` Nur wenn der Callback nicht verwendet wird.\n\nÖffnet eine TCP-Verbindung zu `opt.ldap`, meldet sich mit `opt.user` und `opt.password` an (Bind; außer `opt.noauth` ist `true`) und durchsucht `opt.dn` (Subtree-Scope) nach Einträgen, deren `objectClass` gleich `opt.type` ist.\n\nDer Typ `profile` sucht nach einer `person`, deren `sAMAccountName` gleich `opt.login` ist, und gibt ein einzelnes Objekt (oder `null`) zurück. Ist `opt.dn` leer, verwendet das Framework `opt.user` als Basis-DN und gibt das Profil des angemeldeten Benutzers zurück.\n\nJeder Eintrag ist ein Objekt mit Attributnamen als Schlüsseln. Ein Attribut mit mehreren Werten wird zu einem Array; `objectGUID` und `objectSid` werden als Hex-Strings zurückgegeben. Ohne Callback gibt die Methode eine Promise zurück. Das Changelog kennzeichnet die Methode als experimentell.\n\nExample: Alle Gruppen lesen\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Ein Profil mit einer Promise laden\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"LDAP","summary":"LDAP() y sus opciones.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() y sus opciones.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nLee personas, grupos o el perfil de un usuario de un servidor LDAP (por ejemplo Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` del servidor. El puerto por defecto es `389`. |\n| `opt.user` | `String` | yes |  | El DN o nombre de usuario usado para autenticarse. |\n| `opt.password` | `String` | yes |  | La contraseña usada para autenticarse. |\n| `opt.type` | `String` | yes |  | `person`, `group` o `profile` (se busca como `objectClass`). |\n| `opt.dn` | `String` | no |  | El DN base de la búsqueda, por ejemplo `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | El `sAMAccountName` del usuario, obligatorio para el tipo `profile`. |\n| `opt.noauth` | `Boolean` | no | `false` | Omite la autenticación y busca de forma anónima. |\n| `callback` | `Function(err, response)` | no |  | Recibe un array de entradas, o un objeto para `profile`. |\n\nReturns: `Promise` Solo cuando no se usa el callback.\n\nAbre una conexión TCP a `opt.ldap`, se autentica con `opt.user` y `opt.password` (salvo que `opt.noauth` sea `true`) y busca en `opt.dn` (ámbito de subárbol) entradas con `objectClass` igual a `opt.type`.\n\nEl tipo `profile` busca una `person` cuyo `sAMAccountName` sea igual a `opt.login` y devuelve un único objeto (o `null`). Cuando `opt.dn` está vacío, el framework usa `opt.user` como DN base y devuelve el perfil del usuario autenticado.\n\nCada entrada es un objeto con los nombres de los atributos como claves. Un atributo con varios valores se convierte en un array; `objectGUID` y `objectSid` se devuelven como strings hexadecimales. Sin callback, el método devuelve una promesa. El changelog marca el método como experimental.\n\nExample: Leer todos los grupos\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Cargar un perfil con una promesa\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"LDAP","summary":"LDAP() et ses options.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() et ses options.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nLit des personnes, des groupes ou un profil utilisateur depuis un serveur LDAP (par exemple Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` du serveur. Le port vaut `389` par défaut. |\n| `opt.user` | `String` | yes |  | Le DN ou le nom d'utilisateur utilisé pour le bind. |\n| `opt.password` | `String` | yes |  | Le mot de passe utilisé pour le bind. |\n| `opt.type` | `String` | yes |  | `person`, `group` ou `profile` (recherché comme `objectClass`). |\n| `opt.dn` | `String` | no |  | Le DN de base de la recherche, par exemple `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | Le `sAMAccountName` de l'utilisateur, obligatoire pour le type `profile`. |\n| `opt.noauth` | `Boolean` | no | `false` | Ignore le bind et effectue une recherche anonyme. |\n| `callback` | `Function(err, response)` | no |  | Reçoit un tableau d'entrées, ou un objet pour `profile`. |\n\nReturns: `Promise` Uniquement lorsque le callback n'est pas utilisé.\n\nOuvre une connexion TCP vers `opt.ldap`, effectue le bind avec `opt.user` et `opt.password` (sauf si `opt.noauth` vaut `true`) et recherche dans `opt.dn` (portée subtree) les entrées dont l'`objectClass` est égal à `opt.type`.\n\nLe type `profile` recherche une seule `person` dont le `sAMAccountName` est égal à `opt.login` et renvoie un objet unique (ou `null`). Lorsque `opt.dn` est vide, le framework utilise `opt.user` comme DN de base et renvoie le profil de l'utilisateur connecté.\n\nChaque entrée est un objet dont les clés sont les noms d'attributs. Un attribut à plusieurs valeurs devient un tableau ; `objectGUID` et `objectSid` sont renvoyés sous forme de chaînes hexadécimales. Sans callback, la méthode renvoie une Promise. Le changelog marque la méthode comme expérimentale.\n\nExample: Lire tous les groupes\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Charger un profil avec une Promise\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"LDAP","summary":"LDAP() e le sue opzioni.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() e le sue opzioni.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nLegge persone, gruppi o un profilo utente da un server LDAP (ad esempio Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` del server. La porta predefinita è `389`. |\n| `opt.user` | `String` | yes |  | Il DN o il nome utente usato per il bind. |\n| `opt.password` | `String` | yes |  | La password usata per il bind. |\n| `opt.type` | `String` | yes |  | `person`, `group` o `profile` (cercato come `objectClass`). |\n| `opt.dn` | `String` | no |  | Il DN di base della ricerca, ad esempio `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | Il `sAMAccountName` dell'utente, obbligatorio per il tipo `profile`. |\n| `opt.noauth` | `Boolean` | no | `false` | Salta il bind ed effettua una ricerca anonima. |\n| `callback` | `Function(err, response)` | no |  | Riceve un array di voci, oppure un oggetto per `profile`. |\n\nReturns: `Promise` Solo quando la callback non viene usata.\n\nApre una connessione TCP verso `opt.ldap`, effettua il bind con `opt.user` e `opt.password` (a meno che `opt.noauth` non sia `true`) e cerca in `opt.dn` (ambito subtree) le voci con `objectClass` uguale a `opt.type`.\n\nIl tipo `profile` cerca una `person` il cui `sAMAccountName` è uguale a `opt.login` e restituisce un singolo oggetto (oppure `null`). Quando `opt.dn` è vuoto, il framework usa `opt.user` come DN di base e restituisce il profilo dell'utente con cui è stato effettuato il bind.\n\nOgni voce è un oggetto con i nomi degli attributi come chiavi. Un attributo con più valori diventa un array; `objectGUID` e `objectSid` vengono restituiti come stringhe esadecimali. Senza callback il metodo restituisce una Promise. Il changelog indica il metodo come sperimentale.\n\nExample: Leggere tutti i gruppi\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Caricare un profilo con una Promise\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafj7X6ru60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/ldap/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"LDAP","summary":"LDAP() a jeho voľby.","markdown":"---\ntitle: LDAP\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/ldap/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# LDAP\n\n> LDAP() a jeho voľby.\n\n## API\n\n### LDAP(opt, [callback])\n\nType: `method`\n\nNačíta osoby, skupiny alebo jeden používateľský profil z LDAP servera (napríklad z Active Directory).\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.ldap` | `Object` | yes |  | `{ host: String, port: Number }` servera. Port je predvolene `389`. |\n| `opt.user` | `String` | yes |  | DN alebo používateľské meno použité na bind. |\n| `opt.password` | `String` | yes |  | Heslo použité na bind. |\n| `opt.type` | `String` | yes |  | `person`, `group` alebo `profile` (hľadá sa ako `objectClass`). |\n| `opt.dn` | `String` | no |  | Základné DN vyhľadávania, napríklad `OU=Users,DC=company,DC=local`. |\n| `opt.login` | `String` | no |  | `sAMAccountName` používateľa, povinné pre typ `profile`. |\n| `opt.noauth` | `Boolean` | no | `false` | Preskočí bind a vyhľadáva anonymne. |\n| `callback` | `Function(err, response)` | no |  | Dostane pole záznamov alebo jeden objekt pri `profile`. |\n\nReturns: `Promise` Iba vtedy, keď sa nepoužije callback.\n\nOtvorí TCP spojenie na `opt.ldap`, prihlási sa (bind) cez `opt.user` a `opt.password` (pokiaľ `opt.noauth` nie je `true`) a v `opt.dn` (rozsah subtree) vyhľadá záznamy s `objectClass` rovnou `opt.type`.\n\nTyp `profile` vyhľadá jednu `person`, ktorej `sAMAccountName` sa rovná `opt.login`, a vráti jeden objekt (alebo `null`). Keď je `opt.dn` prázdne, framework použije `opt.user` ako základné DN a vráti profil prihláseného používateľa.\n\nKaždý záznam je objekt s názvami atribútov ako kľúčmi. Atribút s viacerými hodnotami sa stane poľom; `objectGUID` a `objectSid` sa vracajú ako hex reťazce. Bez callbacku metóda vráti Promise. Changelog označuje metódu ako experimentálnu.\n\nExample: Načítanie všetkých skupín\n```js\nLDAP({ ldap: { host: '10.0.0.5' }, user: 'CN=reader,DC=company,DC=local', password: CONF.ldap_password, type: 'group', dn: 'DC=company,DC=local' }, function(err, groups) {\n\tif (err)\n\t\treturn;\n\tfor (var group of groups)\n\t\tconsole.log(group.cn, group.member);\n});\n```\n\nExample: Načítanie jedného profilu cez Promise\n```js\nvar user = await LDAP({ ldap: { host: '10.0.0.5', port: 389 }, user: 'reader@company.local', password: CONF.ldap_password, type: 'profile', dn: 'DC=company,DC=local', login: 'peter' });\nconsole.log(user ? user.displayName : 'not found');\n```\n","entries":[{"type":"method","name":"LDAP()","signature":"LDAP(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjGs4Q061f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Markdown","summary":"String.markdown() and its options.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() and its options.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nConverts a Markdown string to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Options: `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` and the feature switches listed above. |\n\nReturns: `String` HTML.\n\nThe framework loads the parser at start, so every string has this method. HTML tags in the source are encoded. Every block gets the class `markdown-line` and its line number in `data-line` (`data-index` for headlines). By default the output is wrapped in `<div class=\"markdown markdown-container\">` and tabs become four spaces.\n\nEach feature can be turned off with `false` in `opt`: `headlines`, `ul` (lists), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` and `emptynewline`. Bullet lists can start with `-`, `*` or `+`. Links to an e-mail address or a phone number become `mailto:` and `tel:` links.\n\nExample: Render a README\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Only basic formatting\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nWraps the output in a `div` container.\n\nReturns: `Boolean` Default `true`.\n\nWith `true` the output is `<div class=\"markdown markdown-container\">...</div>`. Use `false` to insert the HTML into your own element.\n\nExample: Without the container\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nThe tag of a normal paragraph line.\n\nReturns: `String` Default `'p'`.\n\nEach line that is not a headline, list, table or other block is wrapped in this tag. An empty string writes the lines without a tag.\n\nExample: Lines as div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nAdds an `id` (a slug of the text) to headlines.\n\nReturns: `Boolean` Default `true`.\n\n`# Hello world` becomes `<h1 id=\"hello-world\" ...>`, so you can link to `#hello-world`. Set `false` to leave the `id` out.\n\nExample: Headlines without id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nA prefix for the `id` of headlines.\n\nReturns: `String` Default `''`.\n\nUseful when more Markdown documents are on one page and their headlines would get the same `id`.\n\nExample: Prefixed bookmarks\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nChanges the HTML of a block before it is written.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | The content of the block. |\n| `type` | `String` | yes |  | The block type. |\n\nReturns: `String` The new content.\n\nCalled with the content and the block type: `#` to `#####` for headlines, `li`, `blockquote`, `section`, `block` or the value of `linetag` for normal lines. Return the new content.\n\nExample: Upper-case h1\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nChanges each raw line before the inline formatting is applied.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | One line of the source. |\n\nReturns: `String` The new line.\n\nUse it for your own inline syntax. The line is already HTML-encoded. Return the new line.\n\nExample: Replace a placeholder\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjGs4Q061f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Markdown","summary":"String.markdown() und seine Optionen.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() und seine Optionen.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nWandelt einen Markdown-String in HTML um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Optionen: `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` und die oben aufgeführten Schalter für Funktionen. |\n\nReturns: `String` HTML.\n\nDas Framework lädt den Parser beim Start, daher hat jeder String diese Methode. HTML-Tags im Quelltext werden kodiert. Jeder Block bekommt die Klasse `markdown-line` und seine Zeilennummer in `data-line` (`data-index` bei Überschriften). Standardmäßig wird die Ausgabe in `<div class=\"markdown markdown-container\">` eingeschlossen, und Tabs werden zu vier Leerzeichen.\n\nJede Funktion lässt sich mit `false` in `opt` abschalten: `headlines`, `ul` (Listen), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` und `emptynewline`. Aufzählungslisten können mit `-`, `*` oder `+` beginnen. Links zu einer E-Mail-Adresse oder einer Telefonnummer werden zu `mailto:`- und `tel:`-Links.\n\nExample: Eine README rendern\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Nur einfache Formatierung\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nSchließt die Ausgabe in einen `div`-Container ein.\n\nReturns: `Boolean` Standard `true`.\n\nMit `true` ist die Ausgabe `<div class=\"markdown markdown-container\">...</div>`. Nutze `false`, um das HTML in dein eigenes Element einzufügen.\n\nExample: Ohne Container\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nDas Tag einer normalen Absatzzeile.\n\nReturns: `String` Standard `'p'`.\n\nJede Zeile, die keine Überschrift, Liste, Tabelle oder kein anderer Block ist, wird in dieses Tag eingeschlossen. Ein leerer String schreibt die Zeilen ohne Tag.\n\nExample: Zeilen als div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nFügt Überschriften eine `id` hinzu (ein Slug des Textes).\n\nReturns: `Boolean` Standard `true`.\n\n`# Hello world` wird zu `<h1 id=\"hello-world\" ...>`, sodass du auf `#hello-world` verlinken kannst. Setze `false`, um die `id` wegzulassen.\n\nExample: Überschriften ohne id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nEin Präfix für die `id` von Überschriften.\n\nReturns: `String` Standard `''`.\n\nNützlich, wenn mehrere Markdown-Dokumente auf einer Seite stehen und ihre Überschriften dieselbe `id` bekämen.\n\nExample: Lesezeichen mit Präfix\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nÄndert das HTML eines Blocks, bevor es geschrieben wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Der Inhalt des Blocks. |\n| `type` | `String` | yes |  | Der Blocktyp. |\n\nReturns: `String` Der neue Inhalt.\n\nWird mit dem Inhalt und dem Blocktyp aufgerufen: `#` bis `#####` für Überschriften, `li`, `blockquote`, `section`, `block` oder der Wert von `linetag` für normale Zeilen. Gib den neuen Inhalt zurück.\n\nExample: h1 in Großbuchstaben\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nÄndert jede rohe Zeile, bevor die Inline-Formatierung angewendet wird.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Eine Zeile der Quelle. |\n\nReturns: `String` Die neue Zeile.\n\nNutze es für deine eigene Inline-Syntax. Die Zeile ist bereits HTML-kodiert. Gib die neue Zeile zurück.\n\nExample: Einen Platzhalter ersetzen\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjGs4Q061f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Markdown","summary":"String.markdown() y sus opciones.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() y sus opciones.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nConvierte un string Markdown en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Opciones: `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` y los interruptores de funcionalidades listados arriba. |\n\nReturns: `String` HTML.\n\nEl framework carga el parser al arrancar, así que todo string tiene este método. Las etiquetas HTML del código fuente se codifican. Cada bloque recibe la clase `markdown-line` y su número de línea en `data-line` (`data-index` para los títulos). Por defecto la salida se envuelve en `<div class=\"markdown markdown-container\">` y los tabuladores se convierten en cuatro espacios.\n\nCada funcionalidad se puede desactivar con `false` en `opt`: `headlines`, `ul` (listas), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` y `emptynewline`. Las listas con viñetas pueden empezar con `-`, `*` o `+`. Los enlaces a una dirección de e-mail o a un número de teléfono se convierten en enlaces `mailto:` y `tel:`.\n\nExample: Renderizar un README\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Solo formato básico\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nEnvuelve la salida en un contenedor `div`.\n\nReturns: `Boolean` Por defecto `true`.\n\nCon `true`, la salida es `<div class=\"markdown markdown-container\">...</div>`. Usa `false` para insertar el HTML en tu propio elemento.\n\nExample: Sin el contenedor\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nLa etiqueta de una línea de párrafo normal.\n\nReturns: `String` Por defecto `'p'`.\n\nCada línea que no es un título, una lista, una tabla u otro bloque se envuelve en esta etiqueta. Un string vacío escribe las líneas sin etiqueta.\n\nExample: Líneas como div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nAñade un `id` (un slug del texto) a los encabezados.\n\nReturns: `Boolean` Por defecto `true`.\n\n`# Hello world` se convierte en `<h1 id=\"hello-world\" ...>`, así que puedes enlazar a `#hello-world`. Defínelo como `false` para omitir el `id`.\n\nExample: Encabezados sin id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nUn prefijo para el `id` de los encabezados.\n\nReturns: `String` Por defecto `''`.\n\nÚtil cuando hay varios documentos Markdown en una página y sus encabezados recibirían el mismo `id`.\n\nExample: Marcadores con prefijo\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nCambia el HTML de un bloque antes de escribirlo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | El contenido del bloque. |\n| `type` | `String` | yes |  | El tipo de bloque. |\n\nReturns: `String` El nuevo contenido.\n\nSe llama con el contenido y el tipo de bloque: `#` a `#####` para los títulos, `li`, `blockquote`, `section`, `block` o el valor de `linetag` para las líneas normales. Devuelve el nuevo contenido.\n\nExample: h1 en mayúsculas\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nCambia cada línea en bruto antes de aplicar el formato inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Una línea del origen. |\n\nReturns: `String` La nueva línea.\n\nÚsalo para tu propia sintaxis inline. La línea ya está codificada en HTML. Devuelve la nueva línea.\n\nExample: Reemplazar un placeholder\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjGs4Q061f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Markdown","summary":"String.markdown() et ses options.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() et ses options.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nConvertit une chaîne Markdown en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Options : `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` et les interrupteurs de fonctionnalités listés ci-dessus. |\n\nReturns: `String` HTML.\n\nLe framework charge le parseur au démarrage ; chaque chaîne possède donc cette méthode. Les balises HTML de la source sont encodées. Chaque bloc reçoit la classe `markdown-line` et son numéro de ligne dans `data-line` (`data-index` pour les titres). Par défaut, la sortie est enveloppée dans `<div class=\"markdown markdown-container\">` et les tabulations deviennent quatre espaces.\n\nChaque fonctionnalité peut être désactivée avec `false` dans `opt` : `headlines`, `ul` (listes), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` et `emptynewline`. Les listes à puces peuvent commencer par `-`, `*` ou `+`. Les liens vers une adresse e-mail ou un numéro de téléphone deviennent des liens `mailto:` et `tel:`.\n\nExample: Afficher un README\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Formatage de base uniquement\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nEnveloppe le résultat dans un conteneur `div`.\n\nReturns: `Boolean` Par défaut `true`.\n\nAvec `true`, le résultat est `<div class=\"markdown markdown-container\">...</div>`. Utilise `false` pour insérer le HTML dans ton propre élément.\n\nExample: Sans le conteneur\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nLa balise d'une ligne de paragraphe normale.\n\nReturns: `String` Par défaut `'p'`.\n\nChaque ligne qui n'est ni un titre, ni une liste, ni un tableau, ni un autre bloc est enveloppée dans cette balise. Une chaîne vide écrit les lignes sans balise.\n\nExample: Lignes en div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nAjoute un `id` (un slug du texte) aux titres.\n\nReturns: `Boolean` Par défaut `true`.\n\n`# Hello world` devient `<h1 id=\"hello-world\" ...>`, tu peux donc faire un lien vers `#hello-world`. Définis `false` pour omettre l'`id`.\n\nExample: Titres sans id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nUn préfixe pour l'`id` des titres.\n\nReturns: `String` Par défaut `''`.\n\nUtile lorsque plusieurs documents Markdown se trouvent sur une même page et que leurs titres recevraient le même `id`.\n\nExample: Signets préfixés\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nModifie le HTML d'un bloc avant son écriture.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Le contenu du bloc. |\n| `type` | `String` | yes |  | Le type de bloc. |\n\nReturns: `String` Le nouveau contenu.\n\nAppelée avec le contenu et le type de bloc : `#` à `#####` pour les titres, `li`, `blockquote`, `section`, `block` ou la valeur de `linetag` pour les lignes normales. Renvoie le nouveau contenu.\n\nExample: h1 en majuscules\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nModifie chaque ligne brute avant l'application du formatage inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Une ligne de la source. |\n\nReturns: `String` La nouvelle ligne.\n\nUtilise-la pour ta propre syntaxe inline. La ligne est déjà encodée en HTML. Renvoie la nouvelle ligne.\n\nExample: Remplacer un placeholder\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjGs4Q061f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Markdown","summary":"String.markdown() e le sue opzioni.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() e le sue opzioni.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nConverte una stringa Markdown in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Opzioni: `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` e gli interruttori delle funzionalità elencati sopra. |\n\nReturns: `String` HTML.\n\nIl framework carica il parser all'avvio, quindi ogni stringa ha questo metodo. I tag HTML nel sorgente vengono codificati. Ogni blocco riceve la classe `markdown-line` e il suo numero di riga in `data-line` (`data-index` per i titoli). Per impostazione predefinita l'output è racchiuso in `<div class=\"markdown markdown-container\">` e le tabulazioni diventano quattro spazi.\n\nOgni funzionalità può essere disattivata con `false` in `opt`: `headlines`, `ul` (elenchi), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` ed `emptynewline`. Gli elenchi puntati possono iniziare con `-`, `*` o `+`. I link a un indirizzo e-mail o a un numero di telefono diventano link `mailto:` e `tel:`.\n\nExample: Renderizzare un README\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Solo formattazione di base\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nRacchiude l'output in un contenitore `div`.\n\nReturns: `Boolean` Predefinito `true`.\n\nCon `true` l'output è `<div class=\"markdown markdown-container\">...</div>`. Usa `false` per inserire l'HTML in un tuo elemento.\n\nExample: Senza il contenitore\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nIl tag di una normale riga di paragrafo.\n\nReturns: `String` Predefinito `'p'`.\n\nOgni riga che non è un titolo, un elenco, una tabella o un altro blocco viene racchiusa in questo tag. Una stringa vuota scrive le righe senza tag.\n\nExample: Righe come div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nAggiunge un `id` (uno slug del testo) ai titoli.\n\nReturns: `Boolean` Predefinito `true`.\n\n`# Hello world` diventa `<h1 id=\"hello-world\" ...>`, così puoi creare un link a `#hello-world`. Imposta `false` per omettere l'`id`.\n\nExample: Titoli senza id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nUn prefisso per l'`id` dei titoli.\n\nReturns: `String` Predefinito `''`.\n\nUtile quando più documenti Markdown si trovano su una stessa pagina e i loro titoli riceverebbero lo stesso `id`.\n\nExample: Segnalibri con prefisso\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nModifica l'HTML di un blocco prima che venga scritto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Il contenuto del blocco. |\n| `type` | `String` | yes |  | Il tipo di blocco. |\n\nReturns: `String` Il nuovo contenuto.\n\nViene chiamata con il contenuto e il tipo di blocco: da `#` a `#####` per i titoli, `li`, `blockquote`, `section`, `block` o il valore di `linetag` per le righe normali. Restituisci il nuovo contenuto.\n\nExample: h1 in maiuscolo\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nModifica ogni riga grezza prima che venga applicata la formattazione inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Una riga del sorgente. |\n\nReturns: `String` La nuova riga.\n\nUsala per una tua sintassi inline. La riga è già codificata in HTML. Restituisci la nuova riga.\n\nExample: Sostituire un segnaposto\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjGs4Q061f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/markdown/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Markdown","summary":"String.markdown() a jeho voľby.","markdown":"---\ntitle: Markdown\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/markdown/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Markdown\n\n> String.markdown() a jeho voľby.\n\n## API\n\n### String.markdown([opt])\n\nType: `method`\n\nPrevedie Markdown reťazec na HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | no | `{}` | Voľby: `wrap`, `linetag`, `bookmarks`, `prefix`, `html`, `custom` a prepínače funkcií uvedené vyššie. |\n\nReturns: `String` HTML.\n\nFramework načíta parser pri štarte, takže každý reťazec má túto metódu. HTML tagy v zdroji sa kódujú. Každý blok dostane triedu `markdown-line` a číslo svojho riadku v `data-line` (`data-index` pri nadpisoch). Predvolene je výstup zabalený do `<div class=\"markdown markdown-container\">` a tabulátory sa menia na štyri medzery.\n\nKaždú funkciu môžeš vypnúť hodnotou `false` v `opt`: `headlines`, `ul` (zoznamy), `code`, `images`, `links`, `formatting`, `icons`, `tables`, `br`, `hr`, `blockquotes`, `sections`, `blocks`, `footnotes`, `urlify`, `keywords` a `emptynewline`. Odrážkové zoznamy môžu začínať na `-`, `*` alebo `+`. Odkazy na e-mailovú adresu alebo telefónne číslo sa stanú odkazmi `mailto:` a `tel:`.\n\nExample: Vykreslenie README\n```js\nvar html = '# Hello\\n\\n- one\\n- two\\n\\nWrite to [us](info@company.com).'.markdown();\n```\n\nExample: Len základné formátovanie\n```js\nvar html = text.markdown({ tables: false, code: false, images: false, wrap: false });\n```\n\n### String.markdown({ wrap: Boolean })\n\nType: `property`\n\nZabalí výstup do kontajnera `div`.\n\nReturns: `Boolean` Predvolene `true`.\n\nS `true` je výstup `<div class=\"markdown markdown-container\">...</div>`. Použi `false`, ak chceš HTML vložiť do vlastného elementu.\n\nExample: Bez kontajnera\n```js\nvar html = '**Bold** text'.markdown({ wrap: false });\n// <p class=\"markdown-line\" data-line=\"0\"><strong>Bold</strong> text</p>\n```\n\n### String.markdown({ linetag: String })\n\nType: `property`\n\nTag bežného riadku odseku.\n\nReturns: `String` Predvolene `'p'`.\n\nKaždý riadok, ktorý nie je nadpis, zoznam, tabuľka ani iný blok, sa zabalí do tohto tagu. Prázdny reťazec vypíše riadky bez tagu.\n\nExample: Riadky ako div\n```js\nvar html = text.markdown({ linetag: 'div' });\n```\n\n### String.markdown({ bookmarks: Boolean })\n\nType: `property` · Since: `0.0.96`\n\nPridá nadpisom `id` (slug textu).\n\nReturns: `Boolean` Predvolene `true`.\n\n`# Hello world` sa stane `<h1 id=\"hello-world\" ...>`, takže môžeš odkazovať na `#hello-world`. Nastav `false`, ak chceš `id` vynechať.\n\nExample: Nadpisy bez id\n```js\nvar html = '# Title'.markdown({ bookmarks: false, wrap: false });\n// <h1 class=\"markdown-line\" data-index=\"0\">Title</h1>\n```\n\n### String.markdown({ prefix: String })\n\nType: `property` · Since: `0.0.96`\n\nPrefix pre `id` nadpisov.\n\nReturns: `String` Predvolene `''`.\n\nUžitočné, keď je na jednej stránke viac dokumentov Markdown a ich nadpisy by dostali rovnaké `id`.\n\nExample: Záložky s prefixom\n```js\nvar html = '# Hello world'.markdown({ prefix: 'doc-' });\n// <h1 id=\"doc-hello-world\" ...>\n```\n\n### String.markdown({ html: function(line, type) })\n\nType: `delegate`\n\nZmení HTML bloku predtým, ako sa zapíše.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Obsah bloku. |\n| `type` | `String` | yes |  | Typ bloku. |\n\nReturns: `String` Nový obsah.\n\nVolá sa s obsahom a typom bloku: `#` až `#####` pre nadpisy, `li`, `blockquote`, `section`, `block` alebo hodnota `linetag` pre bežné riadky. Vráť nový obsah.\n\nExample: h1 veľkými písmenami\n```js\nvar html = text.markdown({ html: function(line, type) {\n\treturn type === '#' ? line.toUpperCase() : line;\n}});\n```\n\n### String.markdown({ custom: function(line) })\n\nType: `delegate`\n\nZmení každý surový riadok pred použitím inline formátovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `line` | `String` | yes |  | Jeden riadok zdroja. |\n\nReturns: `String` Nový riadok.\n\nPouži ju pre vlastnú inline syntax. Riadok je už zakódovaný pre HTML. Vráť nový riadok.\n\nExample: Nahradenie zástupného symbolu\n```js\nvar html = text.markdown({ custom: function(line) {\n\treturn line.replace(/\\{year\\}/g, NOW.getFullYear());\n}});\n```\n","entries":[{"type":"method","name":"String.markdown()","signature":"String.markdown([opt])","since":"","deprecated":false},{"type":"property","name":"opt.wrap","signature":"String.markdown({ wrap: Boolean })","since":"","deprecated":false},{"type":"property","name":"opt.linetag","signature":"String.markdown({ linetag: String })","since":"","deprecated":false},{"type":"property","name":"opt.bookmarks","signature":"String.markdown({ bookmarks: Boolean })","since":"0.0.96","deprecated":false},{"type":"property","name":"opt.prefix","signature":"String.markdown({ prefix: String })","since":"0.0.96","deprecated":false},{"type":"delegate","name":"opt.html","signature":"String.markdown({ html: function(line, type) })","since":"","deprecated":false},{"type":"delegate","name":"opt.custom","signature":"String.markdown({ custom: function(line) })","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"HTML parser","summary":"String.parseHTML(), HTMLElement and the methods of a node.","markdown":"---\ntitle: HTML parser\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# HTML parser\n\n> String.parseHTML(), HTMLElement and the methods of a node.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nParses an HTML string into a tree of `HTMLElement` nodes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Trims text nodes and skips empty ones. |\n\nReturns: `HTMLElement` The root element.\n\nReturns a root element without a tag name; its `children` are the top-level nodes. Comments, `<!DOCTYPE>` and `<?xml ?>` declarations are skipped. A missing end tag closes at the end of the input. Void tags (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) have no children.\n\nExample: Find all links\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nA node of a parsed HTML tree.\n\nProperties: `tagName` (upper case, `TEXT` for text nodes), `raw` (the tag name as written), `attrs` (an object of attributes), `children`, `parentNode`, `textContent` (text nodes only), `unpair` (`true` for void tags), `innerHTML` and `innerText` (getters). A tag with a namespace (`<g:item>`) also has `prefix` (`G:`). All changing methods return the element, so you can chain them.\n\nExample: Read and change a node\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nFinds the descendant elements that match a selector.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | The selector. |\n\nReturns: `Array` The matching elements.\n\nSupported selectors: a tag name (`div`), `*`, `#id`, `.class`, an attribute value (`[name=\"value\"]`), a descendant (`div p`) and a direct child (`div > p`). Separate more selectors with a comma. A namespace prefix ending with a colon (`g:`) matches all tags of that namespace. The result is an array with the extra methods of [elements.html()](#elements-html).\n\nExample: Selectors\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nFinds the ancestors that match a selector.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | The selector. |\n\nReturns: `Array` The matching ancestors.\n\nSearches from the parent up to the root.\n\nExample: Find the parent form\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nReturns the parent element.\n\nReturns: `HTMLElement`\n\nThe same as `node.parentNode`.\n\nExample: Parent\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nWalks through all descendant elements.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Called for each element. |\n| `reverse` | `Boolean` | no | `false` | Walks to the ancestors instead. |\n\nReturns: `HTMLElement` The element itself.\n\nThe function is called for each element (text nodes are skipped). Return `true` to skip the children of that element. With `reverse` it walks up through the ancestors.\n\nExample: Count elements\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nReads or sets an attribute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The attribute name. |\n| `value` | `String` | no |  | The new value. |\n\nReturns: `String|HTMLElement` The value when reading, otherwise the element.\n\nWithout `value` it returns the attribute. `null` or an empty string removes the attribute; any other value is stored as a string.\n\nExample: Set alt\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nReads or sets a `data-` attribute.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The name without `data-`. |\n| `value` | `String` | no |  | The new value. |\n\nReturns: `String|HTMLElement`\n\nThe same as `node.attr('data-' + name, value)`.\n\nExample: Read data-id\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nAdds CSS classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | The class names. |\n\nReturns: `HTMLElement`\n\nMore classes can be separated by a space or a comma.\n\nExample: Add classes\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nRemoves CSS classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | The class names. |\n\nReturns: `HTMLElement`\n\nMore classes can be separated by a space or a comma.\n\nExample: Remove a class\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nToggles CSS classes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | The class names. |\n| `value` | `Boolean` | no |  | Forces adding or removing. |\n\nReturns: `HTMLElement`\n\nWithout `value` it adds missing classes and removes present ones. With `value` it adds the classes when `value` is truthy and removes them when it is falsy.\n\nExample: Toggle by condition\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nChecks a CSS class.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | One class name. |\n\nReturns: `Boolean`\n\nReturns `true` when the element has the class.\n\nExample: Check\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nSets inline styles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | The property, or an object `{ property: value }`. |\n| `value` | `String` | no |  | The value. |\n\nReturns: `HTMLElement`\n\nAccepts a property and a value, or an object of properties. An empty value removes the property. The result is written to the `style` attribute.\n\nExample: Styles\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nRemoves the element from its parent.\n\nReturns: `HTMLElement` The removed element.\n\nExample: Remove all scripts\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nParses HTML and adds it to the end of the children.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | The HTML to add. |\n\nReturns: `HTMLElement|Array`\n\nReturns the new element, or an array when the HTML has more top-level nodes.\n\nExample: Append\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nParses HTML and adds it to the beginning of the children.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | The HTML to add. |\n\nReturns: `HTMLElement`\n\nReturns the root of the parsed HTML (not the new element).\n\nExample: Prepend\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nReturns the text of the element without tags.\n\nReturns: `String`\n\nHTML entities are decoded (`&amp;` becomes `&`). `node.innerText` returns the text without decoding.\n\nExample: Read text\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nSerializes the element back to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indents the output. |\n\nReturns: `String`\n\nFor the root it serializes the children. `formatted` puts each node on its own line with tab indentation. `node.toString()` is the same method. Empty `class`, `id` and `data-` attributes are left out.\n\nExample: Change and save\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSerializes all found elements to one HTML string.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Puts each element on its own line. |\n\nReturns: `String`\n\nThe array returned by `find()` and `closest()` also has `aclass()`, `rclass()`, `tclass()`, `attr()` and `attrd()`, which apply to each element and return the array. `toString()` is an alias of `html()`.\n\nExample: Work with all results\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"HTML-Parser","summary":"String.parseHTML(), HTMLElement und die Methoden eines Knotens.","markdown":"---\ntitle: HTML-Parser\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# HTML-Parser\n\n> String.parseHTML(), HTMLElement und die Methoden eines Knotens.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nParst einen HTML-String in einen Baum von `HTMLElement`-Knoten.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Kürzt Textknoten und überspringt leere. |\n\nReturns: `HTMLElement` Das Wurzelelement.\n\nGibt ein Wurzelelement ohne Tag-Namen zurück; seine `children` sind die Knoten der obersten Ebene. Kommentare, `<!DOCTYPE>` und `<?xml ?>`-Deklarationen werden übersprungen. Ein fehlendes End-Tag wird am Ende der Eingabe geschlossen. Leere Tags (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) haben keine Kinder.\n\nExample: Alle Links finden\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nEin Knoten eines geparsten HTML-Baums.\n\nEigenschaften: `tagName` (in Großbuchstaben, `TEXT` bei Textknoten), `raw` (der Tag-Name wie geschrieben), `attrs` (ein Objekt mit Attributen), `children`, `parentNode`, `textContent` (nur Textknoten), `unpair` (`true` bei leeren Tags), `innerHTML` und `innerText` (Getter). Ein Tag mit Namespace (`<g:item>`) hat außerdem `prefix` (`G:`). Alle ändernden Methoden geben das Element zurück, sodass du sie verketten kannst.\n\nExample: Einen Knoten lesen und ändern\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nFindet die Nachfahren-Elemente, die zu einem Selektor passen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Der Selektor. |\n\nReturns: `Array` Die passenden Elemente.\n\nUnterstützte Selektoren: ein Tag-Name (`div`), `*`, `#id`, `.class`, ein Attributwert (`[name=\"value\"]`), ein Nachfahre (`div p`) und ein direktes Kind (`div > p`). Trenne mehrere Selektoren mit einem Komma. Ein Namespace-Präfix, das mit einem Doppelpunkt endet (`g:`), passt auf alle Tags dieses Namespace. Das Ergebnis ist ein Array mit den zusätzlichen Methoden von [elements.html()](#elements-html).\n\nExample: Selektoren\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nFindet die Vorfahren, die zu einem Selektor passen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Der Selektor. |\n\nReturns: `Array` Die passenden Vorfahren.\n\nSucht vom Elternelement aufwärts bis zur Wurzel.\n\nExample: Das übergeordnete Formular finden\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nGibt das Elternelement zurück.\n\nReturns: `HTMLElement`\n\nDasselbe wie `node.parentNode`.\n\nExample: Elternelement\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nDurchläuft alle Nachfahren-Elemente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Wird für jedes Element aufgerufen. |\n| `reverse` | `Boolean` | no | `false` | Läuft stattdessen zu den Vorfahren. |\n\nReturns: `HTMLElement` Das Element selbst.\n\nDie Funktion wird für jedes Element aufgerufen (Textknoten werden übersprungen). Gib `true` zurück, um die Kinder dieses Elements zu überspringen. Mit `reverse` läuft es aufwärts durch die Vorfahren.\n\nExample: Elemente zählen\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nLiest oder setzt ein Attribut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Attributname. |\n| `value` | `String` | no |  | Der neue Wert. |\n\nReturns: `String|HTMLElement` Beim Lesen der Wert, sonst das Element.\n\nOhne `value` gibt es das Attribut zurück. `null` oder ein leerer String entfernt das Attribut; jeder andere Wert wird als String gespeichert.\n\nExample: alt setzen\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nLiest oder setzt ein `data-`-Attribut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name ohne `data-`. |\n| `value` | `String` | no |  | Der neue Wert. |\n\nReturns: `String|HTMLElement`\n\nDasselbe wie `node.attr('data-' + name, value)`.\n\nExample: data-id lesen\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nFügt CSS-Klassen hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Die Klassennamen. |\n\nReturns: `HTMLElement`\n\nMehrere Klassen können durch ein Leerzeichen oder ein Komma getrennt werden.\n\nExample: Klassen hinzufügen\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nEntfernt CSS-Klassen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Die Klassennamen. |\n\nReturns: `HTMLElement`\n\nMehrere Klassen können durch ein Leerzeichen oder ein Komma getrennt werden.\n\nExample: Eine Klasse entfernen\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nSchaltet CSS-Klassen um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Die Klassennamen. |\n| `value` | `Boolean` | no |  | Erzwingt Hinzufügen oder Entfernen. |\n\nReturns: `HTMLElement`\n\nOhne `value` fügt es fehlende Klassen hinzu und entfernt vorhandene. Mit `value` fügt es die Klassen hinzu, wenn `value` truthy ist, und entfernt sie, wenn es falsy ist.\n\nExample: Nach Bedingung umschalten\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nPrüft eine CSS-Klasse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Ein Klassenname. |\n\nReturns: `Boolean`\n\nGibt `true` zurück, wenn das Element die Klasse hat.\n\nExample: Prüfen\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nSetzt Inline-Styles.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | Die Eigenschaft oder ein Objekt `{ property: value }`. |\n| `value` | `String` | no |  | Der Wert. |\n\nReturns: `HTMLElement`\n\nAkzeptiert eine Eigenschaft und einen Wert oder ein Objekt mit Eigenschaften. Ein leerer Wert entfernt die Eigenschaft. Das Ergebnis wird in das Attribut `style` geschrieben.\n\nExample: Styles\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nEntfernt das Element aus seinem Elternelement.\n\nReturns: `HTMLElement` Das entfernte Element.\n\nExample: Alle Skripte entfernen\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nParst HTML und fügt es am Ende der Kinder hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Das hinzuzufügende HTML. |\n\nReturns: `HTMLElement|Array`\n\nGibt das neue Element zurück, oder ein Array, wenn das HTML mehrere Knoten auf oberster Ebene hat.\n\nExample: Anhängen\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nParst HTML und fügt es am Anfang der Kinder hinzu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Das hinzuzufügende HTML. |\n\nReturns: `HTMLElement`\n\nGibt die Wurzel des geparsten HTML zurück (nicht das neue Element).\n\nExample: Voranstellen\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nGibt den Text des Elements ohne Tags zurück.\n\nReturns: `String`\n\nHTML-Entities werden dekodiert (`&amp;` wird zu `&`). `node.innerText` gibt den Text ohne Dekodierung zurück.\n\nExample: Text lesen\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nSerialisiert das Element zurück in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Rückt die Ausgabe ein. |\n\nReturns: `String`\n\nBei der Wurzel serialisiert es die Kinder. `formatted` setzt jeden Knoten in eine eigene Zeile mit Tab-Einrückung. `node.toString()` ist dieselbe Methode. Leere Attribute `class`, `id` und `data-` werden weggelassen.\n\nExample: Ändern und speichern\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSerialisiert alle gefundenen Elemente in einen HTML-String.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Setzt jedes Element in eine eigene Zeile. |\n\nReturns: `String`\n\nDas von `find()` und `closest()` zurückgegebene Array hat außerdem `aclass()`, `rclass()`, `tclass()`, `attr()` und `attrd()`, die auf jedes Element wirken und das Array zurückgeben. `toString()` ist ein Alias von `html()`.\n\nExample: Mit allen Ergebnissen arbeiten\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Parser de HTML","summary":"String.parseHTML(), HTMLElement y los métodos de un nodo.","markdown":"---\ntitle: Parser de HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Parser de HTML\n\n> String.parseHTML(), HTMLElement y los métodos de un nodo.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nParsea un string HTML en un árbol de nodos `HTMLElement`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Recorta los nodos de texto y omite los vacíos. |\n\nReturns: `HTMLElement` El elemento raíz.\n\nDevuelve un elemento raíz sin nombre de etiqueta; sus `children` son los nodos de nivel superior. Los comentarios, `<!DOCTYPE>` y las declaraciones `<?xml ?>` se omiten. Una etiqueta de cierre que falta se cierra al final de la entrada. Las etiquetas vacías (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) no tienen hijos.\n\nExample: Encontrar todos los enlaces\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nUn nodo de un árbol HTML parseado.\n\nPropiedades: `tagName` (en mayúsculas, `TEXT` para los nodos de texto), `raw` (el nombre de la etiqueta tal como se escribió), `attrs` (un objeto con los atributos), `children`, `parentNode`, `textContent` (solo nodos de texto), `unpair` (`true` para las etiquetas vacías), `innerHTML` e `innerText` (getters). Una etiqueta con espacio de nombres (`<g:item>`) también tiene `prefix` (`G:`). Todos los métodos que modifican devuelven el elemento, así que puedes encadenarlos.\n\nExample: Leer y modificar un nodo\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nEncuentra los elementos descendientes que coinciden con un selector.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | El selector. |\n\nReturns: `Array` Los elementos coincidentes.\n\nSelectores admitidos: un nombre de etiqueta (`div`), `*`, `#id`, `.class`, un valor de atributo (`[name=\"value\"]`), un descendiente (`div p`) y un hijo directo (`div > p`). Separa varios selectores con una coma. Un prefijo de espacio de nombres terminado en dos puntos (`g:`) coincide con todas las etiquetas de ese espacio de nombres. El resultado es un array con los métodos adicionales de [elements.html()](#elements-html).\n\nExample: Selectores\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nEncuentra los ancestros que coinciden con un selector.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | El selector. |\n\nReturns: `Array` Los ancestros coincidentes.\n\nBusca desde el padre hasta la raíz.\n\nExample: Encontrar el formulario padre\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nDevuelve el elemento padre.\n\nReturns: `HTMLElement`\n\nLo mismo que `node.parentNode`.\n\nExample: Padre\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nRecorre todos los elementos descendientes.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Se llama para cada elemento. |\n| `reverse` | `Boolean` | no | `false` | Recorre los ancestros en su lugar. |\n\nReturns: `HTMLElement` El propio elemento.\n\nLa función se llama para cada elemento (los nodos de texto se omiten). Devuelve `true` para omitir los hijos de ese elemento. Con `reverse`, sube por los ancestros.\n\nExample: Contar elementos\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nLee o asigna un atributo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del atributo. |\n| `value` | `String` | no |  | El nuevo valor. |\n\nReturns: `String|HTMLElement` El valor al leer; si no, el elemento.\n\nSin `value`, devuelve el atributo. `null` o un string vacío elimina el atributo; cualquier otro valor se guarda como string.\n\nExample: Asignar alt\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nLee o asigna un atributo `data-`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre sin `data-`. |\n| `value` | `String` | no |  | El nuevo valor. |\n\nReturns: `String|HTMLElement`\n\nLo mismo que `node.attr('data-' + name, value)`.\n\nExample: Leer data-id\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nAñade clases CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Los nombres de las clases. |\n\nReturns: `HTMLElement`\n\nVarias clases se pueden separar con un espacio o una coma.\n\nExample: Añadir clases\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nElimina clases CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Los nombres de las clases. |\n\nReturns: `HTMLElement`\n\nVarias clases se pueden separar con un espacio o una coma.\n\nExample: Eliminar una clase\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nAlterna clases CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Los nombres de las clases. |\n| `value` | `Boolean` | no |  | Fuerza añadir o eliminar. |\n\nReturns: `HTMLElement`\n\nSin `value`, añade las clases que faltan y elimina las presentes. Con `value`, añade las clases cuando `value` es truthy y las elimina cuando es falsy.\n\nExample: Alternar según una condición\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nComprueba una clase CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Un nombre de clase. |\n\nReturns: `Boolean`\n\nDevuelve `true` cuando el elemento tiene la clase.\n\nExample: Comprobar\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nDefine estilos en línea.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | La propiedad, o un objeto `{ property: value }`. |\n| `value` | `String` | no |  | El valor. |\n\nReturns: `HTMLElement`\n\nAcepta una propiedad y un valor, o un objeto de propiedades. Un valor vacío elimina la propiedad. El resultado se escribe en el atributo `style`.\n\nExample: Estilos\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nElimina el elemento de su padre.\n\nReturns: `HTMLElement` El elemento eliminado.\n\nExample: Eliminar todos los scripts\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nParsea HTML y lo añade al final de los hijos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | El HTML a añadir. |\n\nReturns: `HTMLElement|Array`\n\nDevuelve el nuevo elemento, o un array cuando el HTML tiene varios nodos de primer nivel.\n\nExample: Append\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nParsea HTML y lo añade al principio de los hijos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | El HTML a añadir. |\n\nReturns: `HTMLElement`\n\nDevuelve la raíz del HTML parseado (no el nuevo elemento).\n\nExample: Prepend\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nDevuelve el texto del elemento sin etiquetas.\n\nReturns: `String`\n\nLas entidades HTML se decodifican (`&amp;` se convierte en `&`). `node.innerText` devuelve el texto sin decodificar.\n\nExample: Leer texto\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nVuelve a serializar el elemento a HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Sangra la salida. |\n\nReturns: `String`\n\nPara la raíz, serializa los hijos. `formatted` pone cada nodo en su propia línea con sangría de tabuladores. `node.toString()` es el mismo método. Los atributos `class`, `id` y `data-` vacíos se dejan fuera.\n\nExample: Modificar y guardar\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSerializa todos los elementos encontrados en un único string HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Pone cada elemento en su propia línea. |\n\nReturns: `String`\n\nEl array que devuelven `find()` y `closest()` también tiene `aclass()`, `rclass()`, `tclass()`, `attr()` y `attrd()`, que se aplican a cada elemento y devuelven el array. `toString()` es un alias de `html()`.\n\nExample: Trabajar con todos los resultados\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Parseur HTML","summary":"String.parseHTML(), HTMLElement et les méthodes d'un nœud.","markdown":"---\ntitle: Parseur HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Parseur HTML\n\n> String.parseHTML(), HTMLElement et les méthodes d'un nœud.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nAnalyse une chaîne HTML en un arbre de nœuds `HTMLElement`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Supprime les espaces des nœuds texte et ignore les nœuds vides. |\n\nReturns: `HTMLElement` L'élément racine.\n\nRenvoie un élément racine sans nom de balise ; ses `children` sont les nœuds de premier niveau. Les commentaires, `<!DOCTYPE>` et les déclarations `<?xml ?>` sont ignorés. Une balise de fin manquante est fermée à la fin de l'entrée. Les balises vides (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) n'ont pas d'enfants.\n\nExample: Trouver tous les liens\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nUn nœud d'un arbre HTML analysé.\n\nPropriétés : `tagName` (en majuscules, `TEXT` pour les nœuds texte), `raw` (le nom de la balise tel qu'il est écrit), `attrs` (un objet d'attributs), `children`, `parentNode`, `textContent` (nœuds texte uniquement), `unpair` (`true` pour les balises vides), `innerHTML` et `innerText` (getters). Une balise avec un namespace (`<g:item>`) possède aussi `prefix` (`G:`). Toutes les méthodes de modification renvoient l'élément ; tu peux donc les enchaîner.\n\nExample: Lire et modifier un nœud\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nTrouve les éléments descendants qui correspondent à un sélecteur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Le sélecteur. |\n\nReturns: `Array` Les éléments correspondants.\n\nSélecteurs pris en charge : un nom de balise (`div`), `*`, `#id`, `.class`, une valeur d'attribut (`[name=\"value\"]`), un descendant (`div p`) et un enfant direct (`div > p`). Sépare plusieurs sélecteurs par une virgule. Un préfixe de namespace terminé par deux-points (`g:`) correspond à toutes les balises de ce namespace. Le résultat est un tableau doté des méthodes supplémentaires de [elements.html()](#elements-html).\n\nExample: Sélecteurs\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nTrouve les ancêtres qui correspondent à un sélecteur.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Le sélecteur. |\n\nReturns: `Array` Les ancêtres correspondants.\n\nRecherche depuis le parent jusqu'à la racine.\n\nExample: Trouver le formulaire parent\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nRenvoie l'élément parent.\n\nReturns: `HTMLElement`\n\nIdentique à `node.parentNode`.\n\nExample: Parent\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nParcourt tous les éléments descendants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Appelée pour chaque élément. |\n| `reverse` | `Boolean` | no | `false` | Parcourt plutôt les ancêtres. |\n\nReturns: `HTMLElement` L'élément lui-même.\n\nLa fonction est appelée pour chaque élément (les nœuds texte sont ignorés). Renvoie `true` pour ignorer les enfants de cet élément. Avec `reverse`, elle remonte à travers les ancêtres.\n\nExample: Compter les éléments\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nLit ou définit un attribut.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom de l'attribut. |\n| `value` | `String` | no |  | La nouvelle valeur. |\n\nReturns: `String|HTMLElement` La valeur en lecture, sinon l'élément.\n\nSans `value`, elle renvoie l'attribut. `null` ou une chaîne vide supprime l'attribut ; toute autre valeur est stockée sous forme de chaîne.\n\nExample: Définir alt\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nLit ou définit un attribut `data-`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom sans `data-`. |\n| `value` | `String` | no |  | La nouvelle valeur. |\n\nReturns: `String|HTMLElement`\n\nIdentique à `node.attr('data-' + name, value)`.\n\nExample: Lire data-id\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nAjoute des classes CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Les noms de classes. |\n\nReturns: `HTMLElement`\n\nPlusieurs classes peuvent être séparées par un espace ou une virgule.\n\nExample: Ajouter des classes\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nSupprime des classes CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Les noms de classes. |\n\nReturns: `HTMLElement`\n\nPlusieurs classes peuvent être séparées par un espace ou une virgule.\n\nExample: Supprimer une classe\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nBascule des classes CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Les noms de classes. |\n| `value` | `Boolean` | no |  | Force l'ajout ou la suppression. |\n\nReturns: `HTMLElement`\n\nSans `value`, elle ajoute les classes absentes et supprime celles qui sont présentes. Avec `value`, elle ajoute les classes lorsque `value` est truthy et les supprime lorsqu'il est falsy.\n\nExample: Basculer selon une condition\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nVérifie une classe CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Un nom de classe. |\n\nReturns: `Boolean`\n\nRenvoie `true` lorsque l'élément possède la classe.\n\nExample: Vérifier\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nDéfinit des styles en ligne.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | La propriété, ou un objet `{ property: value }`. |\n| `value` | `String` | no |  | La valeur. |\n\nReturns: `HTMLElement`\n\nAccepte une propriété et une valeur, ou un objet de propriétés. Une valeur vide supprime la propriété. Le résultat est écrit dans l'attribut `style`.\n\nExample: Styles\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nSupprime l'élément de son parent.\n\nReturns: `HTMLElement` L'élément supprimé.\n\nExample: Supprimer tous les scripts\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nAnalyse du HTML et l'ajoute à la fin des enfants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML à ajouter. |\n\nReturns: `HTMLElement|Array`\n\nRenvoie le nouvel élément, ou un tableau lorsque le HTML contient plusieurs nœuds de premier niveau.\n\nExample: Append\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nAnalyse du HTML et l'ajoute au début des enfants.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML à ajouter. |\n\nReturns: `HTMLElement`\n\nRenvoie la racine du HTML analysé (pas le nouvel élément).\n\nExample: Prepend\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nRenvoie le texte de l'élément sans les balises.\n\nReturns: `String`\n\nLes entités HTML sont décodées (`&amp;` devient `&`). `node.innerText` renvoie le texte sans décodage.\n\nExample: Lire le texte\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nSérialise l'élément en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indente le résultat. |\n\nReturns: `String`\n\nPour la racine, elle sérialise les enfants. `formatted` place chaque nœud sur sa propre ligne avec une indentation par tabulations. `node.toString()` est la même méthode. Les attributs `class`, `id` et `data-` vides sont omis.\n\nExample: Modifier et enregistrer\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSérialise tous les éléments trouvés en une seule chaîne HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Place chaque élément sur sa propre ligne. |\n\nReturns: `String`\n\nLe tableau renvoyé par `find()` et `closest()` possède aussi `aclass()`, `rclass()`, `tclass()`, `attr()` et `attrd()`, qui s'appliquent à chaque élément et renvoient le tableau. `toString()` est un alias de `html()`.\n\nExample: Travailler avec tous les résultats\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Parser HTML","summary":"String.parseHTML(), HTMLElement e i metodi di un nodo.","markdown":"---\ntitle: Parser HTML\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Parser HTML\n\n> String.parseHTML(), HTMLElement e i metodi di un nodo.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nInterpreta una stringa HTML in un albero di nodi `HTMLElement`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Elimina gli spazi dai nodi di testo e salta quelli vuoti. |\n\nReturns: `HTMLElement` L'elemento radice.\n\nRestituisce un elemento radice senza nome di tag; i suoi `children` sono i nodi di primo livello. I commenti, `<!DOCTYPE>` e le dichiarazioni `<?xml ?>` vengono ignorati. Un tag di chiusura mancante si chiude alla fine dell'input. I tag void (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) non hanno figli.\n\nExample: Trovare tutti i link\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nUn nodo di un albero HTML interpretato.\n\nProprietà: `tagName` (in maiuscolo, `TEXT` per i nodi di testo), `raw` (il nome del tag come è scritto), `attrs` (un oggetto di attributi), `children`, `parentNode`, `textContent` (solo nodi di testo), `unpair` (`true` per i tag void), `innerHTML` e `innerText` (getter). Un tag con un namespace (`<g:item>`) ha anche `prefix` (`G:`). Tutti i metodi che modificano restituiscono l'elemento, così puoi concatenarli.\n\nExample: Leggere e modificare un nodo\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nTrova gli elementi discendenti che corrispondono a un selettore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Il selettore. |\n\nReturns: `Array` Gli elementi corrispondenti.\n\nSelettori supportati: un nome di tag (`div`), `*`, `#id`, `.class`, il valore di un attributo (`[name=\"value\"]`), un discendente (`div p`) e un figlio diretto (`div > p`). Separa più selettori con una virgola. Un prefisso di namespace che termina con due punti (`g:`) corrisponde a tutti i tag di quel namespace. Il risultato è un array con i metodi aggiuntivi di [elements.html()](#elements-html).\n\nExample: Selettori\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nTrova gli antenati che corrispondono a un selettore.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Il selettore. |\n\nReturns: `Array` Gli antenati corrispondenti.\n\nCerca dal genitore fino alla radice.\n\nExample: Trovare il form genitore\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nRestituisce l'elemento genitore.\n\nReturns: `HTMLElement`\n\nUguale a `node.parentNode`.\n\nExample: Genitore\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nPercorre tutti gli elementi discendenti.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Chiamata per ogni elemento. |\n| `reverse` | `Boolean` | no | `false` | Percorre invece gli antenati. |\n\nReturns: `HTMLElement` L'elemento stesso.\n\nLa funzione viene chiamata per ogni elemento (i nodi di testo vengono saltati). Restituisci `true` per saltare i figli di quell'elemento. Con `reverse` risale attraverso gli antenati.\n\nExample: Contare gli elementi\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nLegge o imposta un attributo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'attributo. |\n| `value` | `String` | no |  | Il nuovo valore. |\n\nReturns: `String|HTMLElement` Il valore in lettura, altrimenti l'elemento.\n\nSenza `value` restituisce l'attributo. `null` o una stringa vuota rimuovono l'attributo; qualsiasi altro valore viene memorizzato come stringa.\n\nExample: Impostare alt\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nLegge o imposta un attributo `data-`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome senza `data-`. |\n| `value` | `String` | no |  | Il nuovo valore. |\n\nReturns: `String|HTMLElement`\n\nUguale a `node.attr('data-' + name, value)`.\n\nExample: Leggere data-id\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nAggiunge classi CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | I nomi delle classi. |\n\nReturns: `HTMLElement`\n\nPiù classi possono essere separate da uno spazio o da una virgola.\n\nExample: Aggiungere classi\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nRimuove classi CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | I nomi delle classi. |\n\nReturns: `HTMLElement`\n\nPiù classi possono essere separate da uno spazio o da una virgola.\n\nExample: Rimuovere una classe\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nAlterna classi CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | I nomi delle classi. |\n| `value` | `Boolean` | no |  | Forza l'aggiunta o la rimozione. |\n\nReturns: `HTMLElement`\n\nSenza `value` aggiunge le classi mancanti e rimuove quelle presenti. Con `value` aggiunge le classi quando `value` è truthy e le rimuove quando è falsy.\n\nExample: Alternare in base a una condizione\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nControlla una classe CSS.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Un nome di classe. |\n\nReturns: `Boolean`\n\nRestituisce `true` quando l'elemento ha la classe.\n\nExample: Controllo\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nImposta gli stili inline.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | La proprietà, oppure un oggetto `{ property: value }`. |\n| `value` | `String` | no |  | Il valore. |\n\nReturns: `HTMLElement`\n\nAccetta una proprietà e un valore, oppure un oggetto di proprietà. Un valore vuoto rimuove la proprietà. Il risultato viene scritto nell'attributo `style`.\n\nExample: Stili\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nRimuove l'elemento dal suo genitore.\n\nReturns: `HTMLElement` L'elemento rimosso.\n\nExample: Rimuovere tutti gli script\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nInterpreta HTML e lo aggiunge alla fine dei figli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | L'HTML da aggiungere. |\n\nReturns: `HTMLElement|Array`\n\nRestituisce il nuovo elemento, oppure un array quando l'HTML ha più nodi di primo livello.\n\nExample: Append\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nInterpreta HTML e lo aggiunge all'inizio dei figli.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | L'HTML da aggiungere. |\n\nReturns: `HTMLElement`\n\nRestituisce la radice dell'HTML interpretato (non il nuovo elemento).\n\nExample: Prepend\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nRestituisce il testo dell'elemento senza tag.\n\nReturns: `String`\n\nLe entità HTML vengono decodificate (`&amp;` diventa `&`). `node.innerText` restituisce il testo senza decodifica.\n\nExample: Leggere il testo\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nSerializza di nuovo l'elemento in HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Indenta l'output. |\n\nReturns: `String`\n\nPer la radice serializza i figli. `formatted` mette ogni nodo su una riga propria con indentazione a tabulazioni. `node.toString()` è lo stesso metodo. Gli attributi `class`, `id` e `data-` vuoti vengono esclusi.\n\nExample: Modificare e salvare\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSerializza tutti gli elementi trovati in un'unica stringa HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Mette ogni elemento su una riga propria. |\n\nReturns: `String`\n\nL'array restituito da `find()` e `closest()` ha anche `aclass()`, `rclass()`, `tclass()`, `attr()` e `attrd()`, che si applicano a ogni elemento e restituiscono l'array. `toString()` è un alias di `html()`.\n\nExample: Lavorare con tutti i risultati\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjQB5BX60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/html-parser/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"HTML parser","summary":"String.parseHTML(), HTMLElement a metódy uzla.","markdown":"---\ntitle: HTML parser\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/html-parser/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# HTML parser\n\n> String.parseHTML(), HTMLElement a metódy uzla.\n\n## API\n\n### String.parseHTML([trim])\n\nType: `method`\n\nParsuje HTML reťazec do stromu uzlov `HTMLElement`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `trim` | `Boolean` | no | `false` | Oreže textové uzly a preskočí prázdne. |\n\nReturns: `HTMLElement` Koreňový element.\n\nVráti koreňový element bez názvu tagu; jeho `children` sú uzly najvyššej úrovne. Komentáre, `<!DOCTYPE>` a deklarácie `<?xml ?>` sa preskočia. Chýbajúci koncový tag sa uzavrie na konci vstupu. Nepárové tagy (`br`, `hr`, `img`, `input`, `meta`, `link`, `source`, `area`, `col`, `embed`, `track`) nemajú deti.\n\nExample: Nájdenie všetkých odkazov\n```js\nvar dom = html.parseHTML(true);\nvar links = dom.find('a');\nfor (var a of links)\n\tconsole.log(a.attr('href'), a.text());\n```\n\n### HTMLElement\n\nType: `class`\n\nUzol parsovaného HTML stromu.\n\nVlastnosti: `tagName` (veľkými písmenami, `TEXT` pre textové uzly), `raw` (názov tagu tak, ako je napísaný), `attrs` (objekt atribútov), `children`, `parentNode`, `textContent` (len textové uzly), `unpair` (`true` pre nepárové tagy), `innerHTML` a `innerText` (gettery). Tag s menným priestorom (`<g:item>`) má aj `prefix` (`G:`). Všetky meniace metódy vracajú element, takže ich môžeš reťaziť.\n\nExample: Čítanie a zmena uzla\n```js\nvar dom = '<div class=\"box\"><p data-id=\"1\">Hello</p></div>'.parseHTML();\nvar p = dom.find('p')[0];\nconsole.log(p.tagName, p.attrs, p.parentNode.tagName);\n// P { 'data-id': '1' } DIV\n```\n\n### node.find(selector)\n\nType: `method`\n\nNájde elementy potomkov, ktoré zodpovedajú selektoru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Selektor. |\n\nReturns: `Array` Zodpovedajúce elementy.\n\nPodporované selektory: názov tagu (`div`), `*`, `#id`, `.class`, hodnota atribútu (`[name=\"value\"]`), potomok (`div p`) a priame dieťa (`div > p`). Viac selektorov oddeľ čiarkou. Predpona menného priestoru končiaca dvojbodkou (`g:`) zodpovedá všetkým tagom daného menného priestoru. Výsledkom je pole s metódami navyše z [elements.html()](#elements-html).\n\nExample: Selektory\n```js\nvar dom = html.parseHTML();\nvar images = dom.find('img[alt=\"Logo\"]');\nvar items = dom.find('ul.menu > li');\nvar both = dom.find('h1, h2');\n```\n\n### node.closest(selector)\n\nType: `method`\n\nNájde predkov, ktorí zodpovedajú selektoru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `selector` | `String` | yes |  | Selektor. |\n\nReturns: `Array` Zodpovedajúci predkovia.\n\nHľadá od rodiča až po koreň.\n\nExample: Nájdenie nadradeného formulára\n```js\nvar form = input.closest('form')[0];\n```\n\n### node.parent()\n\nType: `method`\n\nVráti rodičovský element.\n\nReturns: `HTMLElement`\n\nTo isté ako `node.parentNode`.\n\nExample: Rodič\n```js\nvar li = dom.find('a')[0].parent();\n```\n\n### node.browse(fn, [reverse])\n\nType: `method`\n\nPrejde všetky elementy potomkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `fn` | `Function(node)` | yes |  | Volá sa pre každý element. |\n| `reverse` | `Boolean` | no | `false` | Namiesto toho prechádza k predkom. |\n\nReturns: `HTMLElement` Samotný element.\n\nFunkcia sa volá pre každý element (textové uzly sa preskakujú). Vráť `true`, ak chceš preskočiť potomkov daného elementu. S `reverse` prechádza nahor cez predkov.\n\nExample: Počítanie elementov\n```js\nvar count = 0;\ndom.browse(function(node) {\n\tcount++;\n});\n```\n\n### node.attr(name, [value])\n\nType: `method`\n\nNačíta alebo nastaví atribút.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov atribútu. |\n| `value` | `String` | no |  | Nová hodnota. |\n\nReturns: `String|HTMLElement` Pri čítaní hodnota, inak element.\n\nBez `value` vráti atribút. `null` alebo prázdny reťazec atribút odstráni; každá iná hodnota sa uloží ako reťazec.\n\nExample: Nastavenie alt\n```js\ndom.find('img')[0].attr('alt', 'Logo');\n```\n\n### node.attrd(name, [value])\n\nType: `method`\n\nNačíta alebo nastaví atribút `data-`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov bez `data-`. |\n| `value` | `String` | no |  | Nová hodnota. |\n\nReturns: `String|HTMLElement`\n\nTo isté ako `node.attr('data-' + name, value)`.\n\nExample: Čítanie data-id\n```js\nvar id = node.attrd('id');\n```\n\n### node.aclass(cls)\n\nType: `method`\n\nPridá CSS triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n\nReturns: `HTMLElement`\n\nViac tried môžeš oddeliť medzerou alebo čiarkou.\n\nExample: Pridanie tried\n```js\nnode.aclass('active highlighted');\n```\n\n### node.rclass(cls)\n\nType: `method`\n\nOdstráni CSS triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n\nReturns: `HTMLElement`\n\nViac tried môžeš oddeliť medzerou alebo čiarkou.\n\nExample: Odstránenie triedy\n```js\nnode.rclass('hidden');\n```\n\n### node.tclass(cls, [value])\n\nType: `method`\n\nPrepne CSS triedy.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Názvy tried. |\n| `value` | `Boolean` | no |  | Vynúti pridanie alebo odstránenie. |\n\nReturns: `HTMLElement`\n\nBez `value` pridá chýbajúce triedy a odstráni prítomné. S `value` triedy pridá, keď je `value` pravdivé, a odstráni ich, keď je nepravdivé.\n\nExample: Prepnutie podľa podmienky\n```js\nnode.tclass('selected', item.id === current);\n```\n\n### node.hclass(cls)\n\nType: `method`\n\nOverí CSS triedu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `cls` | `String` | yes |  | Jeden názov triedy. |\n\nReturns: `Boolean`\n\nVráti `true`, keď element má danú triedu.\n\nExample: Overenie\n```js\nif (node.hclass('external'))\n\tnode.attr('target', '_blank');\n```\n\n### node.css(key, [value])\n\nType: `method`\n\nNastaví inline štýly.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `key` | `String|Object` | yes |  | Vlastnosť alebo objekt `{ property: value }`. |\n| `value` | `String` | no |  | Hodnota. |\n\nReturns: `HTMLElement`\n\nAkceptuje vlastnosť a hodnotu alebo objekt vlastností. Prázdna hodnota vlastnosť odstráni. Výsledok sa zapíše do atribútu `style`.\n\nExample: Štýly\n```js\nnode.css('color', 'red');\nnode.css({ 'font-weight': 'bold', color: '' });\n```\n\n### node.remove()\n\nType: `method`\n\nOdstráni element z jeho rodiča.\n\nReturns: `HTMLElement` Odstránený element.\n\nExample: Odstránenie všetkých skriptov\n```js\nfor (var script of dom.find('script'))\n\tscript.remove();\n```\n\n### node.append(html)\n\nType: `method`\n\nParsuje HTML a pridá ho na koniec potomkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML, ktoré sa pridá. |\n\nReturns: `HTMLElement|Array`\n\nVráti nový element alebo pole, keď má HTML viac uzlov najvyššej úrovne.\n\nExample: Append\n```js\nvar li = dom.find('ul')[0].append('<li>New</li>');\n```\n\n### node.prepend(html)\n\nType: `method`\n\nParsuje HTML a pridá ho na začiatok potomkov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML, ktoré sa pridá. |\n\nReturns: `HTMLElement`\n\nVráti koreň parsovaného HTML (nie nový element).\n\nExample: Prepend\n```js\ndom.find('body')[0].prepend('<header>Top</header>');\n```\n\n### node.text()\n\nType: `method`\n\nVráti text elementu bez tagov.\n\nReturns: `String`\n\nHTML entity sa dekódujú (`&amp;` sa zmení na `&`). `node.innerText` vráti text bez dekódovania.\n\nExample: Čítanie textu\n```js\n'<p>A &amp; B</p>'.parseHTML().find('p')[0].text();\n// A & B\n```\n\n### node.html([formatted])\n\nType: `method`\n\nSerializuje element späť do HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Odsadí výstup. |\n\nReturns: `String`\n\nPri koreni serializuje potomkov. `formatted` dá každý uzol na samostatný riadok s odsadením tabulátormi. `node.toString()` je tá istá metóda. Prázdne atribúty `class`, `id` a `data-` sa vynechajú.\n\nExample: Zmena a uloženie\n```js\nvar dom = html.parseHTML();\ndom.find('img').attr('loading', 'lazy');\nvar output = dom.html();\n```\n\n### elements.html([formatted])\n\nType: `method` · Since: `0.0.98`\n\nSerializuje všetky nájdené elementy do jedného HTML reťazca.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `formatted` | `Boolean` | no | `false` | Dá každý element na samostatný riadok. |\n\nReturns: `String`\n\nPole vrátené z `find()` a `closest()` má aj `aclass()`, `rclass()`, `tclass()`, `attr()` a `attrd()`, ktoré sa použijú na každý element a vrátia pole. `toString()` je alias `html()`.\n\nExample: Práca so všetkými výsledkami\n```js\nvar items = dom.find('li');\nitems.aclass('item').attrd('ready', '1');\nconsole.log(items.html());\n```\n","entries":[{"type":"method","name":"String.parseHTML()","signature":"String.parseHTML([trim])","since":"","deprecated":false},{"type":"class","name":"HTMLElement","signature":"HTMLElement","since":"","deprecated":false},{"type":"method","name":"node.find()","signature":"node.find(selector)","since":"","deprecated":false},{"type":"method","name":"node.closest()","signature":"node.closest(selector)","since":"","deprecated":false},{"type":"method","name":"node.parent()","signature":"node.parent()","since":"","deprecated":false},{"type":"method","name":"node.browse()","signature":"node.browse(fn, [reverse])","since":"","deprecated":false},{"type":"method","name":"node.attr()","signature":"node.attr(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.attrd()","signature":"node.attrd(name, [value])","since":"","deprecated":false},{"type":"method","name":"node.aclass()","signature":"node.aclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.rclass()","signature":"node.rclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.tclass()","signature":"node.tclass(cls, [value])","since":"","deprecated":false},{"type":"method","name":"node.hclass()","signature":"node.hclass(cls)","since":"","deprecated":false},{"type":"method","name":"node.css()","signature":"node.css(key, [value])","since":"","deprecated":false},{"type":"method","name":"node.remove()","signature":"node.remove()","since":"","deprecated":false},{"type":"method","name":"node.append()","signature":"node.append(html)","since":"","deprecated":false},{"type":"method","name":"node.prepend()","signature":"node.prepend(html)","since":"","deprecated":false},{"type":"method","name":"node.text()","signature":"node.text()","since":"","deprecated":false},{"type":"method","name":"node.html()","signature":"node.html([formatted])","since":"","deprecated":false},{"type":"method","name":"elements.html()","signature":"elements.html([formatted])","since":"0.0.98","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"JafjSZ1t760f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Macros","summary":"NEWMACRO() and the function it returns.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Macros\n\n> NEWMACRO() and the function it returns.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nCompiles a simple macro script into a JavaScript function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | The macro source. |\n| `nocompile` | `Boolean` | no | `false` | Returns the generated JavaScript code as a string. |\n| `isasync` | `Boolean` | no | `false` | Creates an async function. |\n\nReturns: `Function|String` A `Function(model, helpers)`, or the code with `nocompile`.\n\nMacros let users write small rules without JavaScript. Supported: `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, quoted values, helper calls `NAME(args)`, private variables `#name` and comments `//`. Keywords are case-insensitive. Model properties and helper names are converted to lower case, so keys in the model and helpers must be lower case. Avoid property names that contain `if` or `else` (for example `verified`), because the compiler replaces those letters as keywords. More statements can be on one line separated by `;`.\n\nThe compiled function has the signature `fn(model, helpers)`; helpers run with the model as `this`. With `isasync` every helper call is awaited and the function returns a Promise.\n\nExample: Price rule\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Async helpers\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nThe function returned by `NEWMACRO()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | The data. |\n| `helpers` | `Object` | no |  | Functions used by the macro. |\n\nReturns: `Object|Promise` The value of `RETURN`.\n\n`model` gives the values of properties; `helpers` is an object of functions called by name from the macro. Private `#variables` live only during one call.\n\nExample: Run\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjSZ1t760f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Makros","summary":"NEWMACRO() und die Funktion, die es zurückgibt.","markdown":"---\ntitle: Makros\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Makros\n\n> NEWMACRO() und die Funktion, die es zurückgibt.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nKompiliert ein einfaches Makro-Skript in eine JavaScript-Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Der Quelltext des Makros. |\n| `nocompile` | `Boolean` | no | `false` | Gibt den erzeugten JavaScript-Code als String zurück. |\n| `isasync` | `Boolean` | no | `false` | Erstellt eine asynchrone Funktion. |\n\nReturns: `Function|String` Eine `Function(model, helpers)` oder mit `nocompile` der Code.\n\nMit Makros können Benutzer kleine Regeln ohne JavaScript schreiben. Unterstützt: `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, Werte in Anführungszeichen, Helper-Aufrufe `NAME(args)`, private Variablen `#name` und Kommentare `//`. Bei Schlüsselwörtern wird Groß- und Kleinschreibung nicht unterschieden. Modelleigenschaften und Helper-Namen werden in Kleinbuchstaben umgewandelt, also müssen Schlüssel im Modell und Helper kleingeschrieben sein. Vermeide Eigenschaftsnamen, die `if` oder `else` enthalten (zum Beispiel `verified`), weil der Compiler diese Buchstaben als Schlüsselwörter ersetzt. Mehrere Anweisungen können in einer Zeile stehen, getrennt durch `;`.\n\nDie kompilierte Funktion hat die Signatur `fn(model, helpers)`; Helper laufen mit dem Modell als `this`. Mit `isasync` wird auf jeden Helper-Aufruf gewartet (await), und die Funktion gibt eine Promise zurück.\n\nExample: Preisregel\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Asynchrone Helper\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nDie von `NEWMACRO()` zurückgegebene Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Die Daten. |\n| `helpers` | `Object` | no |  | Vom Makro verwendete Funktionen. |\n\nReturns: `Object|Promise` Der Wert von `RETURN`.\n\n`model` liefert die Werte der Eigenschaften; `helpers` ist ein Objekt mit Funktionen, die vom Makro über ihren Namen aufgerufen werden. Private `#variables` existieren nur während eines Aufrufs.\n\nExample: Ausführen\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjSZ1t760f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Macros","summary":"NEWMACRO() y la función que devuelve.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Macros\n\n> NEWMACRO() y la función que devuelve.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nCompila un script de macro sencillo en una función JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | El código fuente de la macro. |\n| `nocompile` | `Boolean` | no | `false` | Devuelve el código JavaScript generado como string. |\n| `isasync` | `Boolean` | no | `false` | Crea una función async. |\n\nReturns: `Function|String` Una `Function(model, helpers)`, o el código con `nocompile`.\n\nLas macros permiten a los usuarios escribir reglas pequeñas sin JavaScript. Se admite: `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, valores entre comillas, llamadas a helpers `NAME(args)`, variables privadas `#name` y comentarios `//`. Las palabras clave no distinguen mayúsculas de minúsculas. Las propiedades del modelo y los nombres de los helpers se convierten a minúsculas, así que las claves del modelo y los helpers deben estar en minúsculas. Evita nombres de propiedades que contengan `if` o `else` (por ejemplo `verified`), porque el compilador sustituye esas letras como palabras clave. Puede haber varias sentencias en una línea separadas por `;`.\n\nLa función compilada tiene la firma `fn(model, helpers)`; los helpers se ejecutan con el modelo como `this`. Con `isasync`, cada llamada a un helper se espera con await y la función devuelve una promesa.\n\nExample: Regla de precio\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Helpers async\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nLa función devuelta por `NEWMACRO()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Los datos. |\n| `helpers` | `Object` | no |  | Funciones usadas por la macro. |\n\nReturns: `Object|Promise` El valor de `RETURN`.\n\n`model` aporta los valores de las propiedades; `helpers` es un objeto de funciones que la macro llama por su nombre. Las `#variables` privadas solo existen durante una llamada.\n\nExample: Ejecutar\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjSZ1t760f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Macros","summary":"NEWMACRO() et la fonction qu'il renvoie.","markdown":"---\ntitle: Macros\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Macros\n\n> NEWMACRO() et la fonction qu'il renvoie.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nCompile un script de macro simple en une fonction JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | La source de la macro. |\n| `nocompile` | `Boolean` | no | `false` | Renvoie le code JavaScript généré sous forme de chaîne. |\n| `isasync` | `Boolean` | no | `false` | Crée une fonction async. |\n\nReturns: `Function|String` Une `Function(model, helpers)`, ou le code avec `nocompile`.\n\nLes macros permettent aux utilisateurs d'écrire de petites règles sans JavaScript. Pris en charge : `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, les valeurs entre guillemets, les appels de helpers `NAME(args)`, les variables privées `#name` et les commentaires `//`. Les mots-clés ne sont pas sensibles à la casse. Les propriétés du modèle et les noms des helpers sont convertis en minuscules ; les clés du modèle et des helpers doivent donc être en minuscules. Évite les noms de propriétés contenant `if` ou `else` (par exemple `verified`), car le compilateur remplace ces lettres comme des mots-clés. Plusieurs instructions peuvent figurer sur une ligne, séparées par `;`.\n\nLa fonction compilée a la signature `fn(model, helpers)` ; les helpers s'exécutent avec le modèle comme `this`. Avec `isasync`, chaque appel de helper est attendu (await) et la fonction renvoie une Promise.\n\nExample: Règle de prix\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Helpers async\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nLa fonction renvoyée par `NEWMACRO()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Les données. |\n| `helpers` | `Object` | no |  | Fonctions utilisées par la macro. |\n\nReturns: `Object|Promise` La valeur de `RETURN`.\n\n`model` fournit les valeurs des propriétés ; `helpers` est un objet de fonctions appelées par leur nom depuis la macro. Les `#variables` privées n'existent que pendant un appel.\n\nExample: Exécuter\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjSZ1t760f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Macro","summary":"NEWMACRO() e la funzione che restituisce.","markdown":"---\ntitle: Macro\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Macro\n\n> NEWMACRO() e la funzione che restituisce.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nCompila un semplice script macro in una funzione JavaScript.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Il sorgente della macro. |\n| `nocompile` | `Boolean` | no | `false` | Restituisce il codice JavaScript generato come stringa. |\n| `isasync` | `Boolean` | no | `false` | Crea una funzione async. |\n\nReturns: `Function|String` Una `Function(model, helpers)`, oppure il codice con `nocompile`.\n\nLe macro permettono agli utenti di scrivere piccole regole senza JavaScript. Supportati: `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, valori tra virgolette, chiamate di helper `NAME(args)`, variabili private `#name` e commenti `//`. Le parole chiave non distinguono tra maiuscole e minuscole. Le proprietà del modello e i nomi degli helper vengono convertiti in minuscolo, quindi le chiavi del modello e gli helper devono essere in minuscolo. Evita nomi di proprietà che contengono `if` o `else` (ad esempio `verified`), perché il compilatore sostituisce quelle lettere come parole chiave. Più istruzioni possono stare su una riga, separate da `;`.\n\nLa funzione compilata ha la firma `fn(model, helpers)`; gli helper vengono eseguiti con il modello come `this`. Con `isasync` ogni chiamata di helper viene attesa con await e la funzione restituisce una Promise.\n\nExample: Regola di prezzo\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Helper async\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nLa funzione restituita da `NEWMACRO()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | I dati. |\n| `helpers` | `Object` | no |  | Funzioni usate dalla macro. |\n\nReturns: `Object|Promise` Il valore di `RETURN`.\n\n`model` fornisce i valori delle proprietà; `helpers` è un oggetto di funzioni chiamate per nome dalla macro. Le `#variables` private esistono solo durante una chiamata.\n\nExample: Esecuzione\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjSZ1t760f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/macros/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Makrá","summary":"NEWMACRO() a funkcia, ktorú vráti.","markdown":"---\ntitle: \"Makrá\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/macros/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Makrá\n\n> NEWMACRO() a funkcia, ktorú vráti.\n\n## API\n\n### NEWMACRO(str, [nocompile], [isasync])\n\nType: `method`\n\nSkompiluje jednoduchý skript makra do JavaScript funkcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `str` | `String` | yes |  | Zdrojový kód makra. |\n| `nocompile` | `Boolean` | no | `false` | Vráti vygenerovaný JavaScript kód ako reťazec. |\n| `isasync` | `Boolean` | no | `false` | Vytvorí asynchrónnu funkciu. |\n\nReturns: `Function|String` `Function(model, helpers)` alebo kód pri `nocompile`.\n\nMakrá umožňujú používateľom písať malé pravidlá bez JavaScriptu. Podporované: `IF`, `ELSE IF`, `ELSE`, `FI`, `RETURN`, `AND`, `OR`, `TRUE`/`FALSE`/`YES`/`NO`/`OK`, `NULL`, hodnoty v úvodzovkách, volania pomocných funkcií `NAME(args)`, súkromné premenné `#name` a komentáre `//`. V kľúčových slovách sa nerozlišujú veľké a malé písmená. Vlastnosti modelu a názvy pomocných funkcií sa prevádzajú na malé písmená, takže kľúče v modeli a pomocné funkcie musia byť malými písmenami. Vyhni sa názvom vlastností, ktoré obsahujú `if` alebo `else` (napríklad `verified`), pretože kompilátor tieto písmená nahrádza ako kľúčové slová. Viac príkazov môže byť na jednom riadku oddelených `;`.\n\nSkompilovaná funkcia má signatúru `fn(model, helpers)`; pomocné funkcie bežia s modelom ako `this`. S `isasync` sa na každé volanie pomocnej funkcie čaká (await) a funkcia vráti Promise.\n\nExample: Cenové pravidlo\n```js\nvar fn = NEWMACRO('IF price > 100\\n\\tRETURN \"expensive\"\\nFI\\nRETURN discount(price)');\nfn({ price: 200 }, {}); // expensive\nfn({ price: 50 }, { discount: function(price) { return price * 0.9; } }); // 45\n```\n\nExample: Asynchrónne pomocné funkcie\n```js\nvar fn = NEWMACRO('#total = price * count\\nRETURN rate(#total)', false, true);\nvar value = await fn({ price: 2, count: 3 }, { rate: async function(val) { return val * 1.2; } });\n```\n\n### fn(model, [helpers])\n\nType: `delegate`\n\nFunkcia vrátená z `NEWMACRO()`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `model` | `Object` | yes |  | Dáta. |\n| `helpers` | `Object` | no |  | Funkcie, ktoré makro používa. |\n\nReturns: `Object|Promise` Hodnota z `RETURN`.\n\n`model` poskytuje hodnoty vlastností; `helpers` je objekt funkcií, ktoré makro volá podľa názvu. Súkromné `#variables` existujú iba počas jedného volania.\n\nExample: Spustenie\n```js\nvar check = NEWMACRO('IF age >= 18 AND active\\nRETURN TRUE\\nFI\\nRETURN FALSE');\ncheck({ age: 20, active: true }); // true\n```\n","entries":[{"type":"method","name":"NEWMACRO()","signature":"NEWMACRO(str, [nocompile], [isasync])","since":"","deprecated":false},{"type":"delegate","name":"fn()","signature":"fn(model, [helpers])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"CMS compiler","summary":"CMSCOMPILER(), CMSRender and the methods of a compiled page.","markdown":"---\ntitle: CMS compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# CMS compiler\n\n> CMSCOMPILER(), CMSRender and the methods of a compiled page.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nCompiles HTML of a page built with the Total.js CMS editor into a fast renderer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | The HTML. |\n| `widgets` | `Array|Object` | yes |  | Widgets: `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Collects CSS and JS only of the used widgets. |\n\nReturns: `CMSRender` The compiled page.\n\nWidgets are elements with `data-cms=\"ID__CONFIG\"`, where `CONFIG` is URL-encoded JSON. A widget without `render` is kept as static HTML; a widget that is not found is removed. Elements with the class `CMS_trash` or `CMS_editor` are removed, `CMS_unwrap` elements are replaced by their content, and other `CMS_` classes are cleaned (except `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` and `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` and `<script type=\"text/breadcrumb\">` contain Tangular templates. The element with `id=\"CMS\"` marks where a page goes when the result is used as a layout.\n\nWithout `used`, the CSS and JS of all widgets go to the result; with `used` only of the widgets in the HTML. The `widgets` object form (keyed by id) works only with `used`.\n\nExample: Compile and render\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nThe compiled page returned by `CMSCOMPILER()`.\n\nProperties: `css` and `js` (the minified code of widgets as strings), `widgets` (compiled widget instances), `tangular` (navigation and breadcrumb templates), `expressions` and `multiple` (elements with the `CMS_expression` and `CMS_multiple` classes) and `cache` (output of widgets cached with `next(html, replace, true)`). Keep the instance in memory and call `render()` for each request.\n\nExample: Cache the compiled page\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nRenders the compiled page to HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Data for widgets. |\n| `layout` | `CMSRender` | no |  | A compiled layout. |\n| `callback` | `Function(err, html)` | no |  | Receives the HTML. |\n\nReturns: `Promise` Only without a callback.\n\nCalls `render` of each widget in order, then the navigation and breadcrumb templates. `meta` is passed to widgets; the framework reads `meta.url`, `meta.body` (the content for a layout), `meta.navigation` (a `function(id)` returning the items of a navigation), `meta.breadcrumb` (an array), `meta.widgets` (widgets that replace the compiled ones by id; `cache: 'url'` caches per URL) and `meta.inlinecache` (an object that caches the rendered navigation). With `layout` (another `CMSRender`) the page is inserted into the layout. Without a callback it returns a Promise.\n\nExample: Page in a layout\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navigation\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nInserts CSS before `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML to insert. |\n\nReturns: `CMSRender`\n\nWithout `value` it inserts `<style>` with the CSS of widgets (nothing when there is none). Without `</head>` the value is added to the beginning.\n\nExample: Own stylesheet\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nInserts JavaScript before `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML to insert. |\n\nReturns: `CMSRender`\n\nWithout `value` it inserts `<script>` with the JS of widgets (nothing when there is none). Without `</body>` the value is added to the end.\n\nExample: Widget scripts\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nInserts HTML before `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML to insert. |\n\nReturns: `CMSRender`\n\nUse it for `<title>` and `<meta>` tags. Nothing happens when the HTML has no `</head>`.\n\nExample: Title\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nRenders one widget instance.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | The instance data. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Returns the output. |\n\n`opt` contains the keys of `meta` and `id` (the instance id), `widget` (the widget id), `config` (the parsed configuration), `body` (the cleaned HTML of the instance), `html` (its inner HTML) and `version`. Call `next(html, [replace], [cache])`: without `replace` the HTML goes inside the widget element; with `replace` it replaces the whole element. With `cache` the output is cached in the compiled page.\n\nExample: Widget with cache\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"CMS-Compiler","summary":"CMSCOMPILER(), CMSRender und die Methoden einer kompilierten Seite.","markdown":"---\ntitle: CMS-Compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# CMS-Compiler\n\n> CMSCOMPILER(), CMSRender und die Methoden einer kompilierten Seite.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nKompiliert das HTML einer mit dem Total.js-CMS-Editor erstellten Seite in einen schnellen Renderer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Das HTML. |\n| `widgets` | `Array|Object` | yes |  | Widgets: `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Sammelt CSS und JS nur der verwendeten Widgets. |\n\nReturns: `CMSRender` Die kompilierte Seite.\n\nWidgets sind Elemente mit `data-cms=\"ID__CONFIG\"`, wobei `CONFIG` URL-kodiertes JSON ist. Ein Widget ohne `render` bleibt als statisches HTML erhalten; ein nicht gefundenes Widget wird entfernt. Elemente mit der Klasse `CMS_trash` oder `CMS_editor` werden entfernt, `CMS_unwrap`-Elemente werden durch ihren Inhalt ersetzt, und andere `CMS_`-Klassen werden bereinigt (außer `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` und `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` und `<script type=\"text/breadcrumb\">` enthalten Tangular-Templates. Das Element mit `id=\"CMS\"` markiert, wohin eine Seite kommt, wenn das Ergebnis als Layout verwendet wird.\n\nOhne `used` gehen CSS und JS aller Widgets ins Ergebnis; mit `used` nur die der Widgets im HTML. Die Objektform von `widgets` (nach ID verschlüsselt) funktioniert nur mit `used`.\n\nExample: Kompilieren und rendern\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nDie von `CMSCOMPILER()` zurückgegebene kompilierte Seite.\n\nEigenschaften: `css` und `js` (der minifizierte Code der Widgets als Strings), `widgets` (kompilierte Widget-Instanzen), `tangular` (Navigations- und Breadcrumb-Templates), `expressions` und `multiple` (Elemente mit den Klassen `CMS_expression` und `CMS_multiple`) und `cache` (mit `next(html, replace, true)` gecachte Ausgabe von Widgets). Halte die Instanz im Speicher und rufe `render()` für jeden Request auf.\n\nExample: Die kompilierte Seite cachen\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nRendert die kompilierte Seite zu HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Daten für Widgets. |\n| `layout` | `CMSRender` | no |  | Ein kompiliertes Layout. |\n| `callback` | `Function(err, html)` | no |  | Erhält das HTML. |\n\nReturns: `Promise` Nur ohne Callback.\n\nRuft `render` jedes Widgets der Reihe nach auf, dann die Navigations- und Breadcrumb-Templates. `meta` wird an die Widgets übergeben; das Framework liest `meta.url`, `meta.body` (der Inhalt für ein Layout), `meta.navigation` (eine `function(id)`, die die Einträge einer Navigation zurückgibt), `meta.breadcrumb` (ein Array), `meta.widgets` (Widgets, die die kompilierten nach ID ersetzen; `cache: 'url'` cacht pro URL) und `meta.inlinecache` (ein Objekt, das die gerenderte Navigation cacht). Mit `layout` (einem weiteren `CMSRender`) wird die Seite in das Layout eingefügt. Ohne Callback gibt es eine Promise zurück.\n\nExample: Seite in einem Layout\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navigation\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nFügt CSS vor `</head>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Einzufügendes HTML. |\n\nReturns: `CMSRender`\n\nOhne `value` fügt es `<style>` mit dem CSS der Widgets ein (nichts, wenn es keines gibt). Ohne `</head>` wird der Wert am Anfang hinzugefügt.\n\nExample: Eigenes Stylesheet\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nFügt JavaScript vor `</body>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | Einzufügendes HTML. |\n\nReturns: `CMSRender`\n\nOhne `value` fügt es `<script>` mit dem JS der Widgets ein (nichts, wenn es keines gibt). Ohne `</body>` wird der Wert am Ende hinzugefügt.\n\nExample: Widget-Skripte\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nFügt HTML vor `</head>` ein.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | Einzufügendes HTML. |\n\nReturns: `CMSRender`\n\nNutze es für `<title>`- und `<meta>`-Tags. Es passiert nichts, wenn das HTML kein `</head>` hat.\n\nExample: Titel\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nRendert eine Widget-Instanz.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Die Daten der Instanz. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Gibt die Ausgabe zurück. |\n\n`opt` enthält die Schlüssel von `meta` sowie `id` (die Instanz-ID), `widget` (die Widget-ID), `config` (die geparste Konfiguration), `body` (das bereinigte HTML der Instanz), `html` (ihr inneres HTML) und `version`. Rufe `next(html, [replace], [cache])` auf: Ohne `replace` kommt das HTML in das Widget-Element; mit `replace` ersetzt es das ganze Element. Mit `cache` wird die Ausgabe in der kompilierten Seite gecacht.\n\nExample: Widget mit Cache\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Compilador de CMS","summary":"CMSCOMPILER(), CMSRender y los métodos de una página compilada.","markdown":"---\ntitle: Compilador de CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilador de CMS\n\n> CMSCOMPILER(), CMSRender y los métodos de una página compilada.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nCompila el HTML de una página creada con el editor de Total.js CMS en un renderizador rápido.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | El HTML. |\n| `widgets` | `Array|Object` | yes |  | Widgets: `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Reúne el CSS y el JS solo de los widgets usados. |\n\nReturns: `CMSRender` La página compilada.\n\nLos widgets son elementos con `data-cms=\"ID__CONFIG\"`, donde `CONFIG` es JSON codificado como URL. Un widget sin `render` se mantiene como HTML estático; un widget que no se encuentra se elimina. Los elementos con la clase `CMS_trash` o `CMS_editor` se eliminan, los elementos `CMS_unwrap` se reemplazan por su contenido y las demás clases `CMS_` se limpian (excepto `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` y `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` y `<script type=\"text/breadcrumb\">` contienen plantillas de Tangular. El elemento con `id=\"CMS\"` marca dónde va una página cuando el resultado se usa como plantilla (layout).\n\nSin `used`, el CSS y el JS de todos los widgets van al resultado; con `used`, solo los de los widgets presentes en el HTML. La forma de objeto de `widgets` (indexado por id) solo funciona con `used`.\n\nExample: Compilar y renderizar\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nLa página compilada devuelta por `CMSCOMPILER()`.\n\nPropiedades: `css` y `js` (el código minificado de los widgets como strings), `widgets` (instancias de widgets compiladas), `tangular` (plantillas de navegación y migas de pan), `expressions` y `multiple` (elementos con las clases `CMS_expression` y `CMS_multiple`) y `cache` (salida de los widgets cacheada con `next(html, replace, true)`). Mantén la instancia en memoria y llama a `render()` en cada petición.\n\nExample: Cachear la página compilada\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nRenderiza la página compilada a HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Datos para los widgets. |\n| `layout` | `CMSRender` | no |  | Una plantilla compilada. |\n| `callback` | `Function(err, html)` | no |  | Recibe el HTML. |\n\nReturns: `Promise` Solo sin callback.\n\nLlama a `render` de cada widget en orden y después a las plantillas de navegación y migas de pan. `meta` se pasa a los widgets; el framework lee `meta.url`, `meta.body` (el contenido para una plantilla), `meta.navigation` (una `function(id)` que devuelve los elementos de una navegación), `meta.breadcrumb` (un array), `meta.widgets` (widgets que reemplazan a los compilados por id; `cache: 'url'` cachea por URL) y `meta.inlinecache` (un objeto que cachea la navegación renderizada). Con `layout` (otro `CMSRender`), la página se inserta en la plantilla. Sin callback, devuelve una promesa.\n\nExample: Página en una plantilla\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navegación\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nInserta CSS antes de `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML a insertar. |\n\nReturns: `CMSRender`\n\nSin `value`, inserta `<style>` con el CSS de los widgets (nada cuando no hay). Sin `</head>`, el valor se añade al principio.\n\nExample: Hoja de estilos propia\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nInserta JavaScript antes de `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML a insertar. |\n\nReturns: `CMSRender`\n\nSin `value`, inserta `<script>` con el JS de los widgets (nada cuando no hay). Sin `</body>`, el valor se añade al final.\n\nExample: Scripts de los widgets\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nInserta HTML antes de `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML a insertar. |\n\nReturns: `CMSRender`\n\nÚsalo para las etiquetas `<title>` y `<meta>`. No ocurre nada cuando el HTML no tiene `</head>`.\n\nExample: Título\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nRenderiza una instancia de widget.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Los datos de la instancia. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Devuelve la salida. |\n\n`opt` contiene las claves de `meta` e `id` (el id de la instancia), `widget` (el id del widget), `config` (la configuración parseada), `body` (el HTML limpio de la instancia), `html` (su HTML interior) y `version`. Llama a `next(html, [replace], [cache])`: sin `replace`, el HTML va dentro del elemento del widget; con `replace`, reemplaza todo el elemento. Con `cache`, la salida se cachea en la página compilada.\n\nExample: Widget con caché\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Compilateur CMS","summary":"CMSCOMPILER(), CMSRender et les méthodes d'une page compilée.","markdown":"---\ntitle: Compilateur CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilateur CMS\n\n> CMSCOMPILER(), CMSRender et les méthodes d'une page compilée.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nCompile le HTML d'une page créée avec l'éditeur Total.js CMS en un moteur de rendu rapide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | Le HTML. |\n| `widgets` | `Array|Object` | yes |  | Widgets : `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Collecte le CSS et le JS uniquement des widgets utilisés. |\n\nReturns: `CMSRender` La page compilée.\n\nLes widgets sont des éléments avec `data-cms=\"ID__CONFIG\"`, où `CONFIG` est du JSON encodé en URL. Un widget sans `render` est conservé en HTML statique ; un widget introuvable est supprimé. Les éléments avec la classe `CMS_trash` ou `CMS_editor` sont supprimés, les éléments `CMS_unwrap` sont remplacés par leur contenu, et les autres classes `CMS_` sont nettoyées (sauf `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` et `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` et `<script type=\"text/breadcrumb\">` contiennent des templates Tangular. L'élément avec `id=\"CMS\"` indique où placer une page lorsque le résultat est utilisé comme layout.\n\nSans `used`, le CSS et le JS de tous les widgets vont dans le résultat ; avec `used`, uniquement ceux des widgets présents dans le HTML. La forme objet de `widgets` (indexée par id) ne fonctionne qu'avec `used`.\n\nExample: Compiler et rendre\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nLa page compilée renvoyée par `CMSCOMPILER()`.\n\nPropriétés : `css` et `js` (le code minifié des widgets sous forme de chaînes), `widgets` (instances de widgets compilées), `tangular` (templates de navigation et de fil d'Ariane), `expressions` et `multiple` (éléments avec les classes `CMS_expression` et `CMS_multiple`) et `cache` (résultat des widgets mis en cache avec `next(html, replace, true)`). Conserve l'instance en mémoire et appelle `render()` pour chaque requête.\n\nExample: Mettre la page compilée en cache\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nRend la page compilée en HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Données pour les widgets. |\n| `layout` | `CMSRender` | no |  | Un layout compilé. |\n| `callback` | `Function(err, html)` | no |  | Reçoit le HTML. |\n\nReturns: `Promise` Uniquement sans callback.\n\nAppelle `render` de chaque widget dans l'ordre, puis les templates de navigation et de fil d'Ariane. `meta` est transmis aux widgets ; le framework lit `meta.url`, `meta.body` (le contenu pour un layout), `meta.navigation` (une `function(id)` qui renvoie les éléments d'une navigation), `meta.breadcrumb` (un tableau), `meta.widgets` (widgets qui remplacent les widgets compilés par id ; `cache: 'url'` met en cache par URL) et `meta.inlinecache` (un objet qui met en cache la navigation rendue). Avec `layout` (un autre `CMSRender`), la page est insérée dans le layout. Sans callback, elle renvoie une Promise.\n\nExample: Page dans un layout\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navigation\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nInsère du CSS avant `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML à insérer. |\n\nReturns: `CMSRender`\n\nSans `value`, elle insère un `<style>` avec le CSS des widgets (rien s'il n'y en a pas). Sans `</head>`, la valeur est ajoutée au début.\n\nExample: Feuille de style personnalisée\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nInsère du JavaScript avant `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML à insérer. |\n\nReturns: `CMSRender`\n\nSans `value`, elle insère un `<script>` avec le JS des widgets (rien s'il n'y en a pas). Sans `</body>`, la valeur est ajoutée à la fin.\n\nExample: Scripts des widgets\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nInsère du HTML avant `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML à insérer. |\n\nReturns: `CMSRender`\n\nUtilise-la pour les balises `<title>` et `<meta>`. Rien ne se passe lorsque le HTML ne contient pas de `</head>`.\n\nExample: Titre\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nRend une instance de widget.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Les données de l'instance. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Renvoie le résultat. |\n\n`opt` contient les clés de `meta` ainsi que `id` (l'id de l'instance), `widget` (l'id du widget), `config` (la configuration analysée), `body` (le HTML nettoyé de l'instance), `html` (son HTML interne) et `version`. Appelle `next(html, [replace], [cache])` : sans `replace`, le HTML va à l'intérieur de l'élément du widget ; avec `replace`, il remplace l'élément entier. Avec `cache`, le résultat est mis en cache dans la page compilée.\n\nExample: Widget avec cache\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Compilatore CMS","summary":"CMSCOMPILER(), CMSRender e i metodi di una pagina compilata.","markdown":"---\ntitle: Compilatore CMS\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilatore CMS\n\n> CMSCOMPILER(), CMSRender e i metodi di una pagina compilata.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nCompila l'HTML di una pagina creata con l'editor di Total.js CMS in un renderer veloce.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | L'HTML. |\n| `widgets` | `Array|Object` | yes |  | Widget: `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Raccoglie CSS e JS solo dei widget usati. |\n\nReturns: `CMSRender` La pagina compilata.\n\nI widget sono elementi con `data-cms=\"ID__CONFIG\"`, dove `CONFIG` è JSON codificato per URL. Un widget senza `render` viene mantenuto come HTML statico; un widget non trovato viene rimosso. Gli elementi con la classe `CMS_trash` o `CMS_editor` vengono rimossi, gli elementi `CMS_unwrap` vengono sostituiti dal loro contenuto e le altre classi `CMS_` vengono ripulite (tranne `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` e `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` e `<script type=\"text/breadcrumb\">` contengono template Tangular. L'elemento con `id=\"CMS\"` indica dove va una pagina quando il risultato viene usato come layout.\n\nSenza `used`, il CSS e il JS di tutti i widget finiscono nel risultato; con `used` solo quelli dei widget presenti nell'HTML. La forma a oggetto di `widgets` (con chiave l'id) funziona solo con `used`.\n\nExample: Compilare e renderizzare\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nLa pagina compilata restituita da `CMSCOMPILER()`.\n\nProprietà: `css` e `js` (il codice minificato dei widget come stringhe), `widgets` (le istanze compilate dei widget), `tangular` (i template di navigazione e breadcrumb), `expressions` e `multiple` (gli elementi con le classi `CMS_expression` e `CMS_multiple`) e `cache` (l'output dei widget messo in cache con `next(html, replace, true)`). Tieni l'istanza in memoria e chiama `render()` per ogni richiesta.\n\nExample: Mettere in cache la pagina compilata\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nRenderizza in HTML la pagina compilata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Dati per i widget. |\n| `layout` | `CMSRender` | no |  | Un layout compilato. |\n| `callback` | `Function(err, html)` | no |  | Riceve l'HTML. |\n\nReturns: `Promise` Solo senza callback.\n\nChiama `render` di ogni widget in ordine, poi i template di navigazione e breadcrumb. `meta` viene passato ai widget; il framework legge `meta.url`, `meta.body` (il contenuto per un layout), `meta.navigation` (una `function(id)` che restituisce gli elementi di una navigazione), `meta.breadcrumb` (un array), `meta.widgets` (widget che sostituiscono quelli compilati per id; `cache: 'url'` mette in cache per URL) e `meta.inlinecache` (un oggetto che mette in cache la navigazione renderizzata). Con `layout` (un altro `CMSRender`) la pagina viene inserita nel layout. Senza callback restituisce una Promise.\n\nExample: Pagina in un layout\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navigazione\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nInserisce CSS prima di `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML da inserire. |\n\nReturns: `CMSRender`\n\nSenza `value` inserisce `<style>` con il CSS dei widget (niente quando non ce n'è). Senza `</head>` il valore viene aggiunto all'inizio.\n\nExample: Foglio di stile personalizzato\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nInserisce JavaScript prima di `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML da inserire. |\n\nReturns: `CMSRender`\n\nSenza `value` inserisce `<script>` con il JS dei widget (niente quando non ce n'è). Senza `</body>` il valore viene aggiunto alla fine.\n\nExample: Script dei widget\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nInserisce HTML prima di `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML da inserire. |\n\nReturns: `CMSRender`\n\nUsalo per i tag `<title>` e `<meta>`. Non succede nulla quando l'HTML non ha `</head>`.\n\nExample: Titolo\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nRenderizza un'istanza di widget.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | I dati dell'istanza. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Restituisce l'output. |\n\n`opt` contiene le chiavi di `meta` e `id` (l'id dell'istanza), `widget` (l'id del widget), `config` (la configurazione interpretata), `body` (l'HTML ripulito dell'istanza), `html` (il suo HTML interno) e `version`. Chiama `next(html, [replace], [cache])`: senza `replace` l'HTML va all'interno dell'elemento del widget; con `replace` sostituisce l'intero elemento. Con `cache` l'output viene messo in cache nella pagina compilata.\n\nExample: Widget con cache\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"JafjWl2x760f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/cms/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"CMS kompilátor","summary":"CMSCOMPILER(), CMSRender a metódy skompilovanej stránky.","markdown":"---\ntitle: \"CMS kompilátor\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/cms/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# CMS kompilátor\n\n> CMSCOMPILER(), CMSRender a metódy skompilovanej stránky.\n\n## API\n\n### CMSCOMPILER(html, widgets, [used])\n\nType: `method`\n\nSkompiluje HTML stránky vytvorenej v editore Total.js CMS do rýchleho renderera.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `html` | `String` | yes |  | HTML. |\n| `widgets` | `Array|Object` | yes |  | Widgety: `{ id, css, js, ui: { css, js }, render }`. |\n| `used` | `Boolean` | no | `false` | Zbiera CSS a JS iba použitých widgetov. |\n\nReturns: `CMSRender` Skompilovaná stránka.\n\nWidgety sú elementy s `data-cms=\"ID__CONFIG\"`, kde `CONFIG` je JSON zakódovaný pre URL. Widget bez `render` sa ponechá ako statické HTML; widget, ktorý sa nenájde, sa odstráni. Elementy s triedou `CMS_trash` alebo `CMS_editor` sa odstránia, elementy `CMS_unwrap` sa nahradia svojím obsahom a ostatné triedy `CMS_` sa vyčistia (okrem `CMS_hidden`, `CMS_mv`, `CMS_mh`, `CMS_expression`, `CMS_multiple`, `CMS_keyword` a `CMS_monospace`). `<script type=\"text/navigation\" name=\"...\">` a `<script type=\"text/breadcrumb\">` obsahujú šablóny Tangular. Element s `id=\"CMS\"` označuje miesto, kam ide stránka, keď sa výsledok použije ako layout.\n\nBez `used` ide do výsledku CSS a JS všetkých widgetov; s `used` iba widgetov v HTML. Forma objektu `widgets` (s kľúčmi podľa id) funguje iba s `used`.\n\nExample: Kompilácia a renderovanie\n```js\nvar widgets = [{ id: 'hello', css: '.hello{color:red}', render: function(opt, next) {\n\tnext('<b>Hello ' + opt.config.name + '</b>');\n}}];\n\nvar page = CMSCOMPILER(html, widgets);\npage.importcss().importjs();\n\nvar output = await page.render({ url: '/' });\n```\n\n### CMSRender\n\nType: `class`\n\nSkompilovaná stránka vrátená z `CMSCOMPILER()`.\n\nVlastnosti: `css` a `js` (minifikovaný kód widgetov ako reťazce), `widgets` (skompilované inštancie widgetov), `tangular` (šablóny navigácie a drobčekovej navigácie), `expressions` a `multiple` (elementy s triedami `CMS_expression` a `CMS_multiple`) a `cache` (výstup widgetov uložený do cache cez `next(html, replace, true)`). Inštanciu drž v pamäti a pre každú požiadavku zavolaj `render()`.\n\nExample: Uloženie skompilovanej stránky do cache\n```js\nvar pages = {};\n\nfunction getpage(id, html) {\n\treturn pages[id] || (pages[id] = CMSCOMPILER(html, MAIN.widgets).importcss().importjs());\n}\n```\n\n### cms.render(meta, [layout], [callback])\n\nType: `method`\n\nVyrenderuje skompilovanú stránku do HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `meta` | `Object` | yes |  | Dáta pre widgety. |\n| `layout` | `CMSRender` | no |  | Skompilovaný layout. |\n| `callback` | `Function(err, html)` | no |  | Dostane HTML. |\n\nReturns: `Promise` Iba bez callbacku.\n\nPostupne zavolá `render` každého widgetu, potom šablóny navigácie a drobčekovej navigácie. `meta` sa odovzdá widgetom; framework číta `meta.url`, `meta.body` (obsah pre layout), `meta.navigation` (`function(id)`, ktorá vracia položky navigácie), `meta.breadcrumb` (pole), `meta.widgets` (widgety, ktoré podľa id nahradia skompilované; `cache: 'url'` ukladá do cache pre každú URL) a `meta.inlinecache` (objekt, ktorý ukladá vyrenderovanú navigáciu do cache). S `layout` (iným `CMSRender`) sa stránka vloží do layoutu. Bez callbacku vráti Promise.\n\nExample: Stránka v layoute\n```js\nvar layout = CMSCOMPILER('<html><body><main id=\"CMS\"></main></body></html>', []);\nvar page = CMSCOMPILER('<p>Page</p>', []);\n\npage.render({ url: '/' }, layout, function(err, html) {\n\t// <html><body><main id=\"CMS\"><p>Page</p></main></body></html>\n});\n```\n\nExample: Navigácia\n```js\nvar html = await page.render({ url: '/', breadcrumb: [{ name: 'Home', url: '/' }], navigation: function(id) {\n\treturn MAIN.navigations[id];\n}});\n```\n\n### cms.importcss([value])\n\nType: `method`\n\nVloží CSS pred `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML na vloženie. |\n\nReturns: `CMSRender`\n\nBez `value` vloží `<style>` s CSS widgetov (nič, keď žiadne nie je). Bez `</head>` sa hodnota pridá na začiatok.\n\nExample: Vlastný štýl\n```js\npage.importcss('<link rel=\"stylesheet\" href=\"/css/default.css\" />');\n```\n\n### cms.importjs([value])\n\nType: `method`\n\nVloží JavaScript pred `</body>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | no |  | HTML na vloženie. |\n\nReturns: `CMSRender`\n\nBez `value` vloží `<script>` s JS widgetov (nič, keď žiadne nie je). Bez `</body>` sa hodnota pridá na koniec.\n\nExample: Skripty widgetov\n```js\npage.importjs();\n```\n\n### cms.importmeta(value)\n\nType: `method`\n\nVloží HTML pred `</head>`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `String` | yes |  | HTML na vloženie. |\n\nReturns: `CMSRender`\n\nPouži ju pre tagy `<title>` a `<meta>`. Keď HTML nemá `</head>`, nič sa nestane.\n\nExample: Titulok\n```js\npage.importmeta('<title>' + page_title.encode() + '</title>');\n```\n\n### widget.render(opt, next)\n\nType: `delegate`\n\nVyrenderuje jednu inštanciu widgetu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt` | `Object` | yes |  | Dáta inštancie. |\n| `next` | `Function(html, [replace], [cache])` | yes |  | Vráti výstup. |\n\n`opt` obsahuje kľúče z `meta` a `id` (id inštancie), `widget` (id widgetu), `config` (parsovanú konfiguráciu), `body` (vyčistené HTML inštancie), `html` (jej vnútorné HTML) a `version`. Zavolaj `next(html, [replace], [cache])`: bez `replace` ide HTML dovnútra elementu widgetu; s `replace` nahradí celý element. S `cache` sa výstup uloží do cache v skompilovanej stránke.\n\nExample: Widget s cache\n```js\nvar widget = { id: 'news', render: async function(opt, next) {\n\tvar items = await DATA.find('nosql/news').take(opt.config.count || 5).promise();\n\tnext(items.map(n => '<li>' + n.name.encode() + '</li>').join(''), false, true);\n}};\n```\n","entries":[{"type":"method","name":"CMSCOMPILER()","signature":"CMSCOMPILER(html, widgets, [used])","since":"","deprecated":false},{"type":"class","name":"CMSRender","signature":"CMSRender","since":"","deprecated":false},{"type":"method","name":"cms.render()","signature":"cms.render(meta, [layout], [callback])","since":"","deprecated":false},{"type":"method","name":"cms.importcss()","signature":"cms.importcss([value])","since":"","deprecated":false},{"type":"method","name":"cms.importjs()","signature":"cms.importjs([value])","since":"","deprecated":false},{"type":"method","name":"cms.importmeta()","signature":"cms.importmeta(value)","since":"","deprecated":false},{"type":"delegate","name":"widget.render()","signature":"widget.render(opt, next)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"UI Builder compiler","summary":"F.uibuildercompiler().","markdown":"---\ntitle: UI Builder compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# UI Builder compiler\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nCompiles a UI Builder schema so it can be rendered without the designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | The UI Builder schema (JSON string or object). |\n| `opt.origin` | `String` | no |  | The origin for relative component URLs. |\n| `opt.download` | `Boolean` | no | `false` | Embeds the component HTML. |\n| `opt.local` | `Boolean` | no | `false` | Skips resolving components. |\n| `callback` | `Function(err, response)` | no |  | Receives the compiled schema. |\n\nReturns: `Promise` Only without a callback.\n\nFinds the components used in the schema and resolves their render URLs from `schema.components` (relative URLs use `opt.origin` or `schema.origin`; a `.json` value is a list of more components). With `opt.download` the HTML of each component is downloaded and embedded as `base64`. With `opt.local` the components are not downloaded at all. The result is the schema without the editor data, with `compiled: true` and `css` taken from `cssoutput`. Without a callback it returns a Promise.\n\nExample: Compile and store\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"UI-Builder-Compiler","summary":"F.uibuildercompiler().","markdown":"---\ntitle: UI-Builder-Compiler\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# UI-Builder-Compiler\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nKompiliert ein UI-Builder-Schema, sodass es ohne den Designer gerendert werden kann.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | Das UI-Builder-Schema (JSON-String oder Objekt). |\n| `opt.origin` | `String` | no |  | Der Origin für relative Komponenten-URLs. |\n| `opt.download` | `Boolean` | no | `false` | Bettet das HTML der Komponenten ein. |\n| `opt.local` | `Boolean` | no | `false` | Überspringt das Auflösen der Komponenten. |\n| `callback` | `Function(err, response)` | no |  | Erhält das kompilierte Schema. |\n\nReturns: `Promise` Nur ohne Callback.\n\nFindet die im Schema verwendeten Komponenten und löst ihre Render-URLs aus `schema.components` auf (relative URLs verwenden `opt.origin` oder `schema.origin`; ein `.json`-Wert ist eine Liste weiterer Komponenten). Mit `opt.download` wird das HTML jeder Komponente heruntergeladen und als `base64` eingebettet. Mit `opt.local` werden die Komponenten gar nicht heruntergeladen. Das Ergebnis ist das Schema ohne die Editor-Daten, mit `compiled: true` und `css` aus `cssoutput`. Ohne Callback gibt es eine Promise zurück.\n\nExample: Kompilieren und speichern\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Compilador de UI Builder","summary":"F.uibuildercompiler().","markdown":"---\ntitle: Compilador de UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilador de UI Builder\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nCompila un esquema de UI Builder para poder renderizarlo sin el diseñador.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | El esquema de UI Builder (string JSON u objeto). |\n| `opt.origin` | `String` | no |  | El origen para las URL relativas de los componentes. |\n| `opt.download` | `Boolean` | no | `false` | Incrusta el HTML de los componentes. |\n| `opt.local` | `Boolean` | no | `false` | Omite la resolución de componentes. |\n| `callback` | `Function(err, response)` | no |  | Recibe el esquema compilado. |\n\nReturns: `Promise` Solo sin callback.\n\nEncuentra los componentes usados en el esquema y resuelve sus URL de renderizado desde `schema.components` (las URL relativas usan `opt.origin` o `schema.origin`; un valor `.json` es una lista de más componentes). Con `opt.download`, el HTML de cada componente se descarga y se incrusta como `base64`. Con `opt.local`, los componentes no se descargan en absoluto. El resultado es el esquema sin los datos del editor, con `compiled: true` y `css` tomado de `cssoutput`. Sin callback, devuelve una promesa.\n\nExample: Compilar y guardar\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Compilateur UI Builder","summary":"F.uibuildercompiler().","markdown":"---\ntitle: Compilateur UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilateur UI Builder\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nCompile un schéma UI Builder afin qu'il puisse être rendu sans le designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | Le schéma UI Builder (chaîne JSON ou objet). |\n| `opt.origin` | `String` | no |  | L'origine pour les URL relatives des composants. |\n| `opt.download` | `Boolean` | no | `false` | Intègre le HTML des composants. |\n| `opt.local` | `Boolean` | no | `false` | Ignore la résolution des composants. |\n| `callback` | `Function(err, response)` | no |  | Reçoit le schéma compilé. |\n\nReturns: `Promise` Uniquement sans callback.\n\nTrouve les composants utilisés dans le schéma et résout leurs URL de rendu à partir de `schema.components` (les URL relatives utilisent `opt.origin` ou `schema.origin` ; une valeur `.json` est une liste d'autres composants). Avec `opt.download`, le HTML de chaque composant est téléchargé et intégré en `base64`. Avec `opt.local`, les composants ne sont pas téléchargés du tout. Le résultat est le schéma sans les données de l'éditeur, avec `compiled: true` et `css` tiré de `cssoutput`. Sans callback, elle renvoie une Promise.\n\nExample: Compiler et stocker\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Compilatore UI Builder","summary":"F.uibuildercompiler().","markdown":"---\ntitle: Compilatore UI Builder\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# Compilatore UI Builder\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nCompila uno schema UI Builder in modo che possa essere renderizzato senza il designer.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | Lo schema UI Builder (stringa JSON o oggetto). |\n| `opt.origin` | `String` | no |  | L'origine per gli URL relativi dei componenti. |\n| `opt.download` | `Boolean` | no | `false` | Incorpora l'HTML dei componenti. |\n| `opt.local` | `Boolean` | no | `false` | Salta la risoluzione dei componenti. |\n| `callback` | `Function(err, response)` | no |  | Riceve lo schema compilato. |\n\nReturns: `Promise` Solo senza callback.\n\nTrova i componenti usati nello schema e risolve i loro URL di rendering da `schema.components` (gli URL relativi usano `opt.origin` o `schema.origin`; un valore `.json` è un elenco di altri componenti). Con `opt.download` l'HTML di ogni componente viene scaricato e incorporato come `base64`. Con `opt.local` i componenti non vengono scaricati affatto. Il risultato è lo schema senza i dati dell'editor, con `compiled: true` e `css` preso da `cssoutput`. Senza callback restituisce una Promise.\n\nExample: Compilare e salvare\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjba1fg60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/ui-builder-compiler/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"UI Builder kompilátor","summary":"F.uibuildercompiler().","markdown":"---\ntitle: \"UI Builder kompilátor\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/ui-builder-compiler/\nupdated: 2026-11-18T16:57:44.579Z\n---\n\n# UI Builder kompilátor\n\n> F.uibuildercompiler().\n\n## API\n\n### F.uibuildercompiler(opt, [callback])\n\nType: `method`\n\nSkompiluje schému UI Builder, aby sa dala renderovať bez návrhára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `opt.schema` | `String|Object` | yes |  | Schéma UI Builder (JSON reťazec alebo objekt). |\n| `opt.origin` | `String` | no |  | Origin pre relatívne URL komponentov. |\n| `opt.download` | `Boolean` | no | `false` | Vloží HTML komponentov. |\n| `opt.local` | `Boolean` | no | `false` | Preskočí vyriešenie komponentov. |\n| `callback` | `Function(err, response)` | no |  | Dostane skompilovanú schému. |\n\nReturns: `Promise` Iba bez callbacku.\n\nNájde komponenty použité v schéme a vyrieši ich renderovacie URL zo `schema.components` (relatívne URL používajú `opt.origin` alebo `schema.origin`; hodnota `.json` je zoznam ďalších komponentov). S `opt.download` sa HTML každého komponentu stiahne a vloží ako `base64`. S `opt.local` sa komponenty vôbec nesťahujú. Výsledkom je schéma bez dát editora, s `compiled: true` a s `css` prevzatým z `cssoutput`. Bez callbacku vráti Promise.\n\nExample: Kompilácia a uloženie\n```js\nvar app = await F.uibuildercompiler({ schema: body, download: true });\nPATH.fs.writeFile(PATH.databases('app.json'), JSON.stringify(app), NOOP);\n```\n","entries":[{"type":"method","name":"F.uibuildercompiler()","signature":"F.uibuildercompiler(opt, [callback])","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:44.579Z"}
{"id":"Jafjhv3Pg60f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers and Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers and Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompiles and renders a Tangular template in one step.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | The template. |\n| `model` | `Object` | no | `{}` | The data. |\n| `repository` | `Object` | no |  | Extra data available as `$`. |\n| `helpers` | `Object` | no |  | Private helpers for this call. |\n\nReturns: `String` The output.\n\nThe framework loads Tangular (v5) at start as the globals `Tangular` and `Ta`. In the template, `{{ name }}` writes an encoded value of the model, `{{ $.key }}` reads the repository, `{{ value | helper(args) }}` pipes the value through helpers. Use `compile()` when you render the same template more times.\n\nExample: Render\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompiles a template into a reusable function.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | The template. |\n| `tagbeg` | `String` | no | `{{` | The opening tag (regular expression source). |\n| `tagend` | `String` | no | `}}` | The closing tag. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nThe function has the signature `fn(model, [repository], [helpers])`. Errors in the template are written to the console and the function returns `undefined`. `tagbeg` and `tagend` replace `{{` and `}}`; they are used in a regular expression, so escape special characters.\n\nExample: Reuse a template\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Own tags\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nRegisters a global helper.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | The helper name. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | The helper. |\n\nReturns: `Object` `Tangular`.\n\nThe helper gets the piped value as the first argument and the helper arguments after it; `this` is the model. The same as `Thelpers[name] = fn`.\n\nExample: Upper-case helper\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nThe object of global Tangular helpers.\n\nReturns: `Object`\n\nAlso available as `Tangular.helpers`. Built-in helpers: `encode`, `raw`, `format`, `pluralize`, `empty` (alias `def`) and `currency`. A value without a helper is passed through `encode`; a missing helper writes a warning and returns the value.\n\nExample: Add a helper\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nEncodes a value for HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n| `type` | `String|Function` | no |  | The encoding. |\n\nReturns: `String`\n\nWithout `type` it escapes `&`, `<`, `>` and `\"`. Types: `json`, `json2` (indented JSON), `url` or `urlencoded`, `querify`, or a function that does the encoding.\n\nExample: JSON in an attribute\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nWrites the value without encoding.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n\nReturns: `Object`\n\nUse it only for trusted HTML.\n\nExample: Trusted HTML\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormats a number or a date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | The value. |\n| `format` | `Number|String` | no |  | Decimals for numbers, a pattern for dates. |\n| `a` | `String` | no |  | The thousands separator for numbers. |\n| `b` | `String` | no |  | The decimal separator for numbers. |\n\nReturns: `String`\n\nNumbers call `Number.format(decimals, separator, decimalSeparator)`, dates call `Date.format(format)`. A string that looks like a date is parsed and formatted (default `dd.MM.yyyy`), other strings are parsed as numbers. `null` writes an empty string. The number `0` is formatted like any other number.\n\nExample: Numbers and dates\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nChooses a text by a number.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | The number. |\n| `zero` | `String` | yes |  | Text for 0. |\n| `one` | `String` | yes |  | Text for 1. |\n| `few` | `String` | yes |  | Text for 2 to 4. |\n| `other` | `String` | yes |  | Text for other numbers. |\n\nReturns: `String`\n\nCalls `Number.pluralize()`. `#` in the text is replaced by the number.\n\nExample: Items\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nWrites a default text for an empty value.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | The value. |\n| `def` | `String` | no | `---` | The text for an empty value. |\n\nReturns: `String`\n\nA non-empty value is encoded. The alias is `def`.\n\nExample: Default\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nFormats a number as a currency.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | The amount. |\n| `currency` | `String` | no |  | The key in `DEF.currencies`. |\n\nReturns: `String`\n\nCalls `Number.currency(currency)`, which uses formatters registered in `DEF.currencies` (the `default` key when `currency` is empty). Without a formatter it writes the number with two decimals. Other types write an empty string.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nConverts an object to an array of `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | The object. |\n\nReturns: `Array`\n\n`foreach` uses it when the value is an object, so you can loop over the keys of an object.\n\nExample: Loop over an object\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jafjhv3Pg60f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers und Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers und Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nKompiliert und rendert ein Tangular-Template in einem Schritt.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Das Template. |\n| `model` | `Object` | no | `{}` | Die Daten. |\n| `repository` | `Object` | no |  | Zusätzliche Daten, verfügbar als `$`. |\n| `helpers` | `Object` | no |  | Private Helper für diesen Aufruf. |\n\nReturns: `String` Die Ausgabe.\n\nDas Framework lädt Tangular (v5) beim Start als die Globals `Tangular` und `Ta`. Im Template schreibt `{{ name }}` einen kodierten Wert des Modells, `{{ $.key }}` liest das Repository, `{{ value | helper(args) }}` leitet den Wert durch Helper. Nutze `compile()`, wenn du dasselbe Template mehrmals renderst.\n\nExample: Rendern\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nKompiliert ein Template in eine wiederverwendbare Funktion.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Das Template. |\n| `tagbeg` | `String` | no | `{{` | Das öffnende Tag (Quelltext eines regulären Ausdrucks). |\n| `tagend` | `String` | no | `}}` | Das schließende Tag. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nDie Funktion hat die Signatur `fn(model, [repository], [helpers])`. Fehler im Template werden in die Konsole geschrieben, und die Funktion gibt `undefined` zurück. `tagbeg` und `tagend` ersetzen `{{` und `}}`; sie werden in einem regulären Ausdruck verwendet, also maskiere Sonderzeichen.\n\nExample: Ein Template wiederverwenden\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Eigene Tags\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nRegistriert einen globalen Helper.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Der Name des Helpers. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | Der Helper. |\n\nReturns: `Object` `Tangular`.\n\nDer Helper erhält den durchgeleiteten Wert als erstes Argument und danach die Helper-Argumente; `this` ist das Modell. Dasselbe wie `Thelpers[name] = fn`.\n\nExample: Helper für Großbuchstaben\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nDas Objekt der globalen Tangular-Helper.\n\nReturns: `Object`\n\nAuch verfügbar als `Tangular.helpers`. Eingebaute Helper: `encode`, `raw`, `format`, `pluralize`, `empty` (Alias `def`) und `currency`. Ein Wert ohne Helper wird durch `encode` geleitet; ein fehlender Helper schreibt eine Warnung und gibt den Wert zurück.\n\nExample: Einen Helper hinzufügen\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nKodiert einen Wert für HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n| `type` | `String|Function` | no |  | Die Kodierung. |\n\nReturns: `String`\n\nOhne `type` maskiert es `&`, `<`, `>` und `\"`. Typen: `json`, `json2` (eingerücktes JSON), `url` oder `urlencoded`, `querify` oder eine Funktion, die die Kodierung übernimmt.\n\nExample: JSON in einem Attribut\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nSchreibt den Wert ohne Kodierung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n\nReturns: `Object`\n\nNutze es nur für vertrauenswürdiges HTML.\n\nExample: Vertrauenswürdiges HTML\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormatiert eine Zahl oder ein Datum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | Der Wert. |\n| `format` | `Number|String` | no |  | Dezimalstellen bei Zahlen, ein Muster bei Datumswerten. |\n| `a` | `String` | no |  | Das Tausendertrennzeichen bei Zahlen. |\n| `b` | `String` | no |  | Das Dezimaltrennzeichen bei Zahlen. |\n\nReturns: `String`\n\nZahlen rufen `Number.format(decimals, separator, decimalSeparator)` auf, Datumswerte `Date.format(format)`. Ein String, der wie ein Datum aussieht, wird geparst und formatiert (Standard `dd.MM.yyyy`), andere Strings werden als Zahlen geparst. `null` schreibt einen leeren String. Die Zahl `0` wird wie jede andere Zahl formatiert.\n\nExample: Zahlen und Datumswerte\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nWählt einen Text anhand einer Zahl.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Die Zahl. |\n| `zero` | `String` | yes |  | Text für 0. |\n| `one` | `String` | yes |  | Text für 1. |\n| `few` | `String` | yes |  | Text für 2 bis 4. |\n| `other` | `String` | yes |  | Text für andere Zahlen. |\n\nReturns: `String`\n\nRuft `Number.pluralize()` auf. `#` im Text wird durch die Zahl ersetzt.\n\nExample: Elemente\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nSchreibt einen Standardtext für einen leeren Wert.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Der Wert. |\n| `def` | `String` | no | `---` | Der Text für einen leeren Wert. |\n\nReturns: `String`\n\nEin nicht leerer Wert wird kodiert. Der Alias ist `def`.\n\nExample: Standard\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nFormatiert eine Zahl als Währung.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Der Betrag. |\n| `currency` | `String` | no |  | Der Schlüssel in `DEF.currencies`. |\n\nReturns: `String`\n\nRuft `Number.currency(currency)` auf, das in `DEF.currencies` registrierte Formatierer verwendet (den Schlüssel `default`, wenn `currency` leer ist). Ohne Formatierer schreibt es die Zahl mit zwei Dezimalstellen. Andere Typen schreiben einen leeren String.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nKonvertiert ein Objekt in ein Array von `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Das Objekt. |\n\nReturns: `Array`\n\n`foreach` verwendet es, wenn der Wert ein Objekt ist, sodass du über die Schlüssel eines Objekts iterieren kannst.\n\nExample: Über ein Objekt iterieren\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jafjhv3Pg60f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers y Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers y Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompila y renderiza una plantilla de Tangular en un solo paso.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | La plantilla. |\n| `model` | `Object` | no | `{}` | Los datos. |\n| `repository` | `Object` | no |  | Datos extra disponibles como `$`. |\n| `helpers` | `Object` | no |  | Helpers privados para esta llamada. |\n\nReturns: `String` La salida.\n\nEl framework carga Tangular (v5) al arrancar como las globales `Tangular` y `Ta`. En la plantilla, `{{ name }}` escribe un valor codificado del modelo, `{{ $.key }}` lee el repositorio y `{{ value | helper(args) }}` pasa el valor por helpers. Usa `compile()` cuando renderizas la misma plantilla varias veces.\n\nExample: Renderizar\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompila una plantilla en una función reutilizable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | La plantilla. |\n| `tagbeg` | `String` | no | `{{` | La etiqueta de apertura (código de expresión regular). |\n| `tagend` | `String` | no | `}}` | La etiqueta de cierre. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nLa función tiene la firma `fn(model, [repository], [helpers])`. Los errores de la plantilla se escriben en la consola y la función devuelve `undefined`. `tagbeg` y `tagend` reemplazan `{{` y `}}`; se usan en una expresión regular, así que escapa los caracteres especiales.\n\nExample: Reutilizar una plantilla\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Etiquetas propias\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nRegistra un helper global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | El nombre del helper. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | El helper. |\n\nReturns: `Object` `Tangular`.\n\nEl helper recibe el valor pasado como primer argumento y los argumentos del helper después; `this` es el modelo. Lo mismo que `Thelpers[name] = fn`.\n\nExample: Helper de mayúsculas\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nEl objeto de helpers globales de Tangular.\n\nReturns: `Object`\n\nTambién disponible como `Tangular.helpers`. Helpers integrados: `encode`, `raw`, `format`, `pluralize`, `empty` (alias `def`) y `currency`. Un valor sin helper pasa por `encode`; un helper que falta escribe un aviso y devuelve el valor.\n\nExample: Añadir un helper\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nCodifica un valor para HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n| `type` | `String|Function` | no |  | La codificación. |\n\nReturns: `String`\n\nSin `type`, escapa `&`, `<`, `>` y `\"`. Tipos: `json`, `json2` (JSON con sangría), `url` o `urlencoded`, `querify`, o una función que hace la codificación.\n\nExample: JSON en un atributo\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nEscribe el valor sin codificar.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n\nReturns: `Object`\n\nÚsalo solo para HTML de confianza.\n\nExample: HTML de confianza\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormatea un número o una fecha.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | El valor. |\n| `format` | `Number|String` | no |  | Decimales para los números, un patrón para las fechas. |\n| `a` | `String` | no |  | El separador de miles para los números. |\n| `b` | `String` | no |  | El separador decimal para los números. |\n\nReturns: `String`\n\nLos números llaman a `Number.format(decimals, separator, decimalSeparator)` y las fechas a `Date.format(format)`. Un string que parece una fecha se analiza y se formatea (por defecto `dd.MM.yyyy`); los demás strings se analizan como números. `null` escribe un string vacío. El número `0` se formatea como cualquier otro número.\n\nExample: Números y fechas\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nElige un texto según un número.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | El número. |\n| `zero` | `String` | yes |  | Texto para 0. |\n| `one` | `String` | yes |  | Texto para 1. |\n| `few` | `String` | yes |  | Texto para 2 a 4. |\n| `other` | `String` | yes |  | Texto para los demás números. |\n\nReturns: `String`\n\nLlama a `Number.pluralize()`. `#` en el texto se reemplaza por el número.\n\nExample: Elementos\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nEscribe un texto por defecto para un valor vacío.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | El valor. |\n| `def` | `String` | no | `---` | El texto para un valor vacío. |\n\nReturns: `String`\n\nUn valor no vacío se codifica. El alias es `def`.\n\nExample: Valor por defecto\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nFormatea un número como moneda.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | El importe. |\n| `currency` | `String` | no |  | La clave en `DEF.currencies`. |\n\nReturns: `String`\n\nLlama a `Number.currency(currency)`, que usa los formateadores registrados en `DEF.currencies` (la clave `default` cuando `currency` está vacío). Sin formateador, escribe el número con dos decimales. Los otros tipos escriben un string vacío.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nConvierte un objeto en un array de `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | El objeto. |\n\nReturns: `Array`\n\n`foreach` lo usa cuando el valor es un objeto, así puedes recorrer las claves de un objeto.\n\nExample: Recorrer un objeto\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jafjhv3Pg60f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers et Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers et Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompile et rend un template Tangular en une seule étape.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Le template. |\n| `model` | `Object` | no | `{}` | Les données. |\n| `repository` | `Object` | no |  | Données supplémentaires disponibles sous `$`. |\n| `helpers` | `Object` | no |  | Helpers privés pour cet appel. |\n\nReturns: `String` Le résultat.\n\nLe framework charge Tangular (v5) au démarrage sous les variables globales `Tangular` et `Ta`. Dans le template, `{{ name }}` écrit une valeur encodée du modèle, `{{ $.key }}` lit le repository, `{{ value | helper(args) }}` fait passer la valeur par des helpers. Utilise `compile()` lorsque tu rends le même template plusieurs fois.\n\nExample: Rendu\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompile un template en une fonction réutilisable.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Le template. |\n| `tagbeg` | `String` | no | `{{` | La balise d'ouverture (source d'expression régulière). |\n| `tagend` | `String` | no | `}}` | La balise de fermeture. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nLa fonction a la signature `fn(model, [repository], [helpers])`. Les erreurs du template sont écrites dans la console et la fonction renvoie `undefined`. `tagbeg` et `tagend` remplacent `{{` et `}}` ; ils sont utilisés dans une expression régulière, échappe donc les caractères spéciaux.\n\nExample: Réutiliser un template\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Balises personnalisées\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nEnregistre un helper global.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Le nom du helper. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | Le helper. |\n\nReturns: `Object` `Tangular`.\n\nLe helper reçoit la valeur transmise par le pipe comme premier argument, puis les arguments du helper ; `this` est le modèle. Identique à `Thelpers[name] = fn`.\n\nExample: Helper de mise en majuscules\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nL'objet des helpers Tangular globaux.\n\nReturns: `Object`\n\nÉgalement disponible sous `Tangular.helpers`. Helpers intégrés : `encode`, `raw`, `format`, `pluralize`, `empty` (alias `def`) et `currency`. Une valeur sans helper passe par `encode` ; un helper manquant écrit un avertissement et renvoie la valeur.\n\nExample: Ajouter un helper\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nEncode une valeur pour le HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n| `type` | `String|Function` | no |  | L'encodage. |\n\nReturns: `String`\n\nSans `type`, elle échappe `&`, `<`, `>` et `\"`. Types : `json`, `json2` (JSON indenté), `url` ou `urlencoded`, `querify`, ou une fonction qui effectue l'encodage.\n\nExample: JSON dans un attribut\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nÉcrit la valeur sans encodage.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n\nReturns: `Object`\n\nUtilise-le uniquement pour du HTML de confiance.\n\nExample: HTML de confiance\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormate un nombre ou une date.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | La valeur. |\n| `format` | `Number|String` | no |  | Les décimales pour les nombres, un motif pour les dates. |\n| `a` | `String` | no |  | Le séparateur de milliers pour les nombres. |\n| `b` | `String` | no |  | Le séparateur décimal pour les nombres. |\n\nReturns: `String`\n\nLes nombres appellent `Number.format(decimals, separator, decimalSeparator)`, les dates appellent `Date.format(format)`. Une chaîne qui ressemble à une date est analysée puis formatée (par défaut `dd.MM.yyyy`), les autres chaînes sont analysées comme des nombres. `null` écrit une chaîne vide. Le nombre `0` est formaté comme n'importe quel autre nombre.\n\nExample: Nombres et dates\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nChoisit un texte en fonction d'un nombre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Le nombre. |\n| `zero` | `String` | yes |  | Texte pour 0. |\n| `one` | `String` | yes |  | Texte pour 1. |\n| `few` | `String` | yes |  | Texte pour 2 à 4. |\n| `other` | `String` | yes |  | Texte pour les autres nombres. |\n\nReturns: `String`\n\nAppelle `Number.pluralize()`. `#` dans le texte est remplacé par le nombre.\n\nExample: Éléments\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nÉcrit un texte par défaut pour une valeur vide.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | La valeur. |\n| `def` | `String` | no | `---` | Le texte pour une valeur vide. |\n\nReturns: `String`\n\nUne valeur non vide est encodée. L'alias est `def`.\n\nExample: Valeur par défaut\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nFormate un nombre comme une devise.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Le montant. |\n| `currency` | `String` | no |  | La clé dans `DEF.currencies`. |\n\nReturns: `String`\n\nAppelle `Number.currency(currency)`, qui utilise les formateurs enregistrés dans `DEF.currencies` (la clé `default` lorsque `currency` est vide). Sans formateur, il écrit le nombre avec deux décimales. Les autres types écrivent une chaîne vide.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nConvertit un objet en un tableau de `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'objet. |\n\nReturns: `Array`\n\n`foreach` l'utilise lorsque la valeur est un objet ; tu peux ainsi boucler sur les clés d'un objet.\n\nExample: Boucler sur un objet\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jafjhv3Pg60f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers e Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers e Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nCompila e renderizza un template Tangular in un solo passaggio.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Il template. |\n| `model` | `Object` | no | `{}` | I dati. |\n| `repository` | `Object` | no |  | Dati aggiuntivi disponibili come `$`. |\n| `helpers` | `Object` | no |  | Helper privati per questa chiamata. |\n\nReturns: `String` L'output.\n\nIl framework carica Tangular (v5) all'avvio come variabili globali `Tangular` e `Ta`. Nel template, `{{ name }}` scrive un valore codificato del modello, `{{ $.key }}` legge il repository, `{{ value | helper(args) }}` passa il valore attraverso degli helper. Usa `compile()` quando renderizzi lo stesso template più volte.\n\nExample: Render\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nCompila un template in una funzione riutilizzabile.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Il template. |\n| `tagbeg` | `String` | no | `{{` | Il tag di apertura (sorgente di un'espressione regolare). |\n| `tagend` | `String` | no | `}}` | Il tag di chiusura. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nLa funzione ha la firma `fn(model, [repository], [helpers])`. Gli errori nel template vengono scritti nella console e la funzione restituisce `undefined`. `tagbeg` e `tagend` sostituiscono `{{` e `}}`; vengono usati in un'espressione regolare, quindi esegui l'escape dei caratteri speciali.\n\nExample: Riutilizzare un template\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Tag personalizzati\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nRegistra un helper globale.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Il nome dell'helper. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | L'helper. |\n\nReturns: `Object` `Tangular`.\n\nL'helper riceve il valore passato come primo argomento e gli argomenti dell'helper dopo di esso; `this` è il modello. Uguale a `Thelpers[name] = fn`.\n\nExample: Helper per il maiuscolo\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nL'oggetto degli helper globali di Tangular.\n\nReturns: `Object`\n\nDisponibile anche come `Tangular.helpers`. Helper integrati: `encode`, `raw`, `format`, `pluralize`, `empty` (alias `def`) e `currency`. Un valore senza helper passa attraverso `encode`; un helper mancante scrive un avviso e restituisce il valore.\n\nExample: Aggiungere un helper\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nCodifica un valore per HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n| `type` | `String|Function` | no |  | La codifica. |\n\nReturns: `String`\n\nSenza `type` esegue l'escape di `&`, `<`, `>` e `\"`. Tipi: `json`, `json2` (JSON indentato), `url` o `urlencoded`, `querify`, oppure una funzione che esegue la codifica.\n\nExample: JSON in un attributo\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nScrive il valore senza codifica.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n\nReturns: `Object`\n\nUsalo solo per HTML affidabile.\n\nExample: HTML affidabile\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormatta un numero o una data.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | Il valore. |\n| `format` | `Number|String` | no |  | Decimali per i numeri, un pattern per le date. |\n| `a` | `String` | no |  | Il separatore delle migliaia per i numeri. |\n| `b` | `String` | no |  | Il separatore decimale per i numeri. |\n\nReturns: `String`\n\nI numeri chiamano `Number.format(decimals, separator, decimalSeparator)`, le date chiamano `Date.format(format)`. Una stringa che sembra una data viene analizzata e formattata (predefinito `dd.MM.yyyy`), le altre stringhe vengono analizzate come numeri. `null` scrive una stringa vuota. Il numero `0` viene formattato come qualsiasi altro numero.\n\nExample: Numeri e date\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nSceglie un testo in base a un numero.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Il numero. |\n| `zero` | `String` | yes |  | Testo per 0. |\n| `one` | `String` | yes |  | Testo per 1. |\n| `few` | `String` | yes |  | Testo per da 2 a 4. |\n| `other` | `String` | yes |  | Testo per gli altri numeri. |\n\nReturns: `String`\n\nChiama `Number.pluralize()`. `#` nel testo viene sostituito dal numero.\n\nExample: Elementi\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nScrive un testo predefinito per un valore vuoto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Il valore. |\n| `def` | `String` | no | `---` | Il testo per un valore vuoto. |\n\nReturns: `String`\n\nUn valore non vuoto viene codificato. L'alias è `def`.\n\nExample: Predefinito\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nFormatta un numero come valuta.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | L'importo. |\n| `currency` | `String` | no |  | La chiave in `DEF.currencies`. |\n\nReturns: `String`\n\nChiama `Number.currency(currency)`, che usa i formattatori registrati in `DEF.currencies` (la chiave `default` quando `currency` è vuoto). Senza formattatore scrive il numero con due decimali. Gli altri tipi scrivono una stringa vuota.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nConverte un oggetto in un array di `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | L'oggetto. |\n\nReturns: `Array`\n\n`foreach` la usa quando il valore è un oggetto, così puoi ciclare sulle chiavi di un oggetto.\n\nExample: Ciclo su un oggetto\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jafjhv3Pg60f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/tangular/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Tangular","summary":"Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers a Tangular.toArray().","markdown":"---\ntitle: Tangular\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/tangular/\nupdated: 2026-11-18T16:57:49.579Z\n---\n\n# Tangular\n\n> Tangular.render(), Tangular.compile(), Tangular.register(), Thelpers a Tangular.toArray().\n\n## API\n\n### Tangular.render(template, [model], [repository], [helpers])\n\nType: `method`\n\nSkompiluje a vyrenderuje šablónu Tangular v jednom kroku.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Šablóna. |\n| `model` | `Object` | no | `{}` | Dáta. |\n| `repository` | `Object` | no |  | Ďalšie dáta dostupné ako `$`. |\n| `helpers` | `Object` | no |  | Súkromné pomocné funkcie pre toto volanie. |\n\nReturns: `String` Výstup.\n\nFramework pri štarte načíta Tangular (v5) ako globálne `Tangular` a `Ta`. V šablóne `{{ name }}` vypíše zakódovanú hodnotu z modelu, `{{ $.key }}` načíta repository a `{{ value | helper(args) }}` pošle hodnotu cez pomocné funkcie. Keď renderuješ tú istú šablónu viackrát, použi `compile()`.\n\nExample: Renderovanie\n```js\nvar html = Tangular.render('<h1>{{ name }}</h1>{{ foreach m in items }}<b>{{ m.name }}</b>{{ end }}', { name: 'Products', items: [{ name: 'A' }, { name: 'B' }] });\n```\n\n### Tangular.compile(template, [tagbeg], [tagend])\n\nType: `method`\n\nSkompiluje šablónu do opakovane použiteľnej funkcie.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `template` | `String` | yes |  | Šablóna. |\n| `tagbeg` | `String` | no | `{{` | Otvárací tag (zdroj regulárneho výrazu). |\n| `tagend` | `String` | no | `}}` | Zatvárací tag. |\n\nReturns: `Function(model, [repository], [helpers])`\n\nFunkcia má signatúru `fn(model, [repository], [helpers])`. Chyby v šablóne sa vypíšu do konzoly a funkcia vráti `undefined`. `tagbeg` a `tagend` nahrádzajú `{{` a `}}`; používajú sa v regulárnom výraze, preto escapuj špeciálne znaky.\n\nExample: Opakované použitie šablóny\n```js\nvar row = Tangular.compile('<tr><td>{{ name }}</td><td>{{ price | format(2) }}</td></tr>');\nvar html = products.map(p => row(p)).join('');\n```\n\nExample: Vlastné tagy\n```js\nvar fn = Tangular.compile('Hello [[ name ]]', '\\\\[\\\\[', '\\\\]\\\\]');\nfn({ name: 'Peter' });\n```\n\n### Tangular.register(name, fn)\n\nType: `method`\n\nZaregistruje globálnu pomocnú funkciu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `name` | `String` | yes |  | Názov pomocnej funkcie. |\n| `fn` | `Function(value, [a], [b], ...)` | yes |  | Pomocná funkcia. |\n\nReturns: `Object` `Tangular`.\n\nPomocná funkcia dostane poslanú hodnotu ako prvý argument a za ňou argumenty pomocnej funkcie; `this` je model. To isté ako `Thelpers[name] = fn`.\n\nExample: Pomocná funkcia pre veľké písmená\n```js\nTangular.register('upper', function(value) {\n\treturn (value + '').toUpperCase();\n});\n\nTangular.render('{{ name | upper }}', { name: 'peter' }); // PETER\n```\n\n### Thelpers\n\nType: `property`\n\nObjekt globálnych pomocných funkcií Tangular.\n\nReturns: `Object`\n\nDostupný aj ako `Tangular.helpers`. Vstavané pomocné funkcie: `encode`, `raw`, `format`, `pluralize`, `empty` (alias `def`) a `currency`. Hodnota bez pomocnej funkcie prejde cez `encode`; chýbajúca pomocná funkcia vypíše varovanie a vráti hodnotu.\n\nExample: Pridanie pomocnej funkcie\n```js\nThelpers.yesno = function(value) {\n\treturn value ? 'Yes' : 'No';\n};\n```\n\n### Thelpers.encode(value, [type])\n\nType: `method`\n\nZakóduje hodnotu pre HTML.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `type` | `String|Function` | no |  | Kódovanie. |\n\nReturns: `String`\n\nBez `type` escapuje `&`, `<`, `>` a `\"`. Typy: `json`, `json2` (odsadený JSON), `url` alebo `urlencoded`, `querify` alebo funkcia, ktorá kódovanie vykoná.\n\nExample: JSON v atribúte\n```html\n<div data-model=\"{{ item | encode('json') | encode }}\"></div>\n```\n\n### Thelpers.raw(value)\n\nType: `method`\n\nVypíše hodnotu bez zakódovania.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n\nReturns: `Object`\n\nPoužívaj ju iba pre dôveryhodné HTML.\n\nExample: Dôveryhodné HTML\n```html\n<div>{{ body | raw }}</div>\n```\n\n### Thelpers.format(value, [format], [a], [b])\n\nType: `method`\n\nFormátuje číslo alebo dátum.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|Date|String` | yes |  | Hodnota. |\n| `format` | `Number|String` | no |  | Desatinné miesta pre čísla, vzor pre dátumy. |\n| `a` | `String` | no |  | Oddeľovač tisícov pre čísla. |\n| `b` | `String` | no |  | Desatinný oddeľovač pre čísla. |\n\nReturns: `String`\n\nČísla volajú `Number.format(decimals, separator, decimalSeparator)`, dátumy volajú `Date.format(format)`. Reťazec, ktorý vyzerá ako dátum, sa sparsuje a naformátuje (predvolene `dd.MM.yyyy`), ostatné reťazce sa parsujú ako čísla. `null` vypíše prázdny reťazec. Číslo `0` sa formátuje ako akékoľvek iné číslo.\n\nExample: Čísla a dátumy\n```html\n<td>{{ price | format(2) }}</td>\n<td>{{ dtcreated | format('yyyy-MM-dd HH:mm') }}</td>\n```\n\n### Thelpers.pluralize(value, zero, one, few, other)\n\nType: `method`\n\nVyberie text podľa čísla.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Číslo. |\n| `zero` | `String` | yes |  | Text pre 0. |\n| `one` | `String` | yes |  | Text pre 1. |\n| `few` | `String` | yes |  | Text pre 2 až 4. |\n| `other` | `String` | yes |  | Text pre ostatné čísla. |\n\nReturns: `String`\n\nVolá `Number.pluralize()`. `#` v texte sa nahradí číslom.\n\nExample: Položky\n```html\n{{ count | pluralize('no items', '# item', '# items', '# items') }}\n```\n\n### Thelpers.empty(value, [def])\n\nType: `method`\n\nVypíše predvolený text pre prázdnu hodnotu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Object` | yes |  | Hodnota. |\n| `def` | `String` | no | `---` | Text pre prázdnu hodnotu. |\n\nReturns: `String`\n\nNeprázdna hodnota sa zakóduje. Alias je `def`.\n\nExample: Predvolená hodnota\n```html\n<td>{{ phone | empty('not set') }}</td>\n```\n\n### Thelpers.currency(value, [currency])\n\nType: `method`\n\nNaformátuje číslo ako menu.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `value` | `Number|String` | yes |  | Suma. |\n| `currency` | `String` | no |  | Kľúč v `DEF.currencies`. |\n\nReturns: `String`\n\nVolá `Number.currency(currency)`, ktorá používa formátovače registrované v `DEF.currencies` (kľúč `default`, keď je `currency` prázdne). Bez formátovača vypíše číslo s dvoma desatinnými miestami. Ostatné typy vypíšu prázdny reťazec.\n\nExample: Euro\n```js\nDEF.currencies.eur = function(val) {\n\treturn val.format(2) + ' EUR';\n};\n\nTangular.render('{{ price | currency(\\'eur\\') }}', { price: 10 }); // 10.00 EUR\n```\n\n### Tangular.toArray(obj)\n\nType: `method`\n\nPrevedie objekt na pole `{ key, value }`.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `obj` | `Object` | yes |  | Objekt. |\n\nReturns: `Array`\n\n`foreach` ju používa, keď je hodnota objekt, takže môžeš prechádzať cyklom cez kľúče objektu.\n\nExample: Cyklus cez objekt\n```html\n{{ foreach m in headers }}<b>{{ m.key }}</b>: {{ m.value }}<br />{{ end }}\n```\n","entries":[{"type":"method","name":"Tangular.render()","signature":"Tangular.render(template, [model], [repository], [helpers])","since":"","deprecated":false},{"type":"method","name":"Tangular.compile()","signature":"Tangular.compile(template, [tagbeg], [tagend])","since":"","deprecated":false},{"type":"method","name":"Tangular.register()","signature":"Tangular.register(name, fn)","since":"","deprecated":false},{"type":"property","name":"Thelpers","signature":"Thelpers","since":"","deprecated":false},{"type":"method","name":"Thelpers.encode()","signature":"Thelpers.encode(value, [type])","since":"","deprecated":false},{"type":"method","name":"Thelpers.raw()","signature":"Thelpers.raw(value)","since":"","deprecated":false},{"type":"method","name":"Thelpers.format()","signature":"Thelpers.format(value, [format], [a], [b])","since":"","deprecated":false},{"type":"method","name":"Thelpers.pluralize()","signature":"Thelpers.pluralize(value, zero, one, few, other)","since":"","deprecated":false},{"type":"method","name":"Thelpers.empty()","signature":"Thelpers.empty(value, [def])","since":"","deprecated":false},{"type":"method","name":"Thelpers.currency()","signature":"Thelpers.currency(value, [currency])","since":"","deprecated":false},{"type":"method","name":"Tangular.toArray()","signature":"Tangular.toArray(obj)","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-18T16:57:49.579Z"}
{"id":"Jabj7W1eN61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"en","title":"Command line (total4)","summary":"Every command of the total4 command-line tool.","markdown":"---\ntitle: Command line (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Command line (total4)\n\n> Every command of the total4 command-line tool.\n\nThe `total4` tool is installed with `npm install -g total4`. The guide [Command line (total4)](../../guides/command-line/) explains the commands with examples; this page lists every command, its arguments and its output.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nThe command-line tool of the total4 package.\n\nInstalled with `npm install -g total4` (the `bin` entry of the package). The first argument is the command; `name`, `-name` and `--name` are the same command. Each run prints a header box with the version first. Without a command it prints `Use \"total4 help\" to list all commands.`, and an unknown command prints `Command \"...\" is invalid`.\n\nExample: Install and list the commands\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nPrints the list of all commands.\n\nAliases: `h`, `-h`, `--help`. Prints one line for each command with its arguments and a short description.\n\nExample: Show the help\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nPrints only the header with the version.\n\nAliases: `-v`, `--version`. The tool prints its header box, which contains the version of the framework, and ends.\n\nExample: Show the version\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nServes the current directory as static files on the given port.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | The port of the HTTP server. |\n\nThe number must be the first argument. The server runs in debug mode on `0.0.0.0`. A directory returns its `index.html`, or a generated directory listing with file sizes when there is none. HTML, scripts and styles are sent without compilation; `.less` files are served as `text/less`. Temporary files go to the temporary directory of the system. Stop it with `Ctrl+C`.\n\nExample: Serve a static site\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nPrints the list of official project templates.\n\nDownloads the list from GitHub and prints the name and description of each template. Without a connection it prints `Total.js templates are currently unavailable.`\n\nExample: List templates\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nMakes a bundle of the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | The name of the bundle file, with the `.bundle` extension. |\n\nWrites all files of the current directory into one `.bundle` file and prints the directory, the file name, the number of files and the size. Excluded: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` with their `.json` and `.pid` files, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` and the output file. See [Application structure](../../guides/application-structure/) for how bundles are loaded.\n\nExample: Bundle an application\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nMakes a .package file of the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | The name of the package file, with the `.package` extension. |\n\nWorks like `bundle`. Excluded: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` and the output file. Copy the result to `/packages/` of an application.\n\nExample: Make a package\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nExtracts a bundle or a package into the current directory.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The `.bundle` or `.package` file. |\n\nWrites every file of the archive into the current directory, overwriting files with the same path, and prints the number of files and the size.\n\nExample: Extract a bundle\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifies a .js, .css or .html file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | The file to minify. |\n\nAliases: `-compress`, `-compile` (with one or two dashes). The file name is the last argument. Writes `<name>.min.<extension>` next to the file and prints `Minified: <path>`; other extensions are not written. A missing file prints `File not found`.\n\nExample: Minify a script\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nCollects localizable texts of the application into translate.resource.\n\nAlias: `-t`. Reads `.html` and `.js` files (and files with `sitemap` in their path) of the current directory and all its subdirectories. Collects `@(text)` markers (texts that start with `#` and a non-space character are skipped) and, in `.js` files, keys from `$.invalid('key')`, `.error('key')` and `.err('key')`. Writes `translate.resource` grouped by `// filename` comments and prints the number of texts. See [Localization](../../guides/localization/).\n\nExample: Create a resource\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nPrints the resource line for one text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | The text to translate. |\n\nWhen the argument is not an existing file, the tool prints the key (`T` and the base-36 hash of the text) and the text, ready to paste into a resource file.\n\nExample: Key of one text\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nCreates translate.resource from the lines of a text file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | A text file with one text per line. |\n\nEach non-empty line of the file becomes one entry with a `T` hash key. The result is `translate.resource` in the current directory.\n\nExample: Resource from a list of texts\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nCollects localizable texts into translate.csv.\n\nAlias: `-c`. Reads `.html` and `.js` files of the current directory and its subdirectories and writes each unique `@(text)` marker as a row of `translate.csv` with the columns `Hash;Text;Translation`.\n\nExample: CSV for a translator\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nConverts a resource with old numeric keys to Total.js 4 keys.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The old resource file. |\n\nAlias: `-4`. Keys like `T123` and `T-123` become `T` and the base-36 form of the number; other lines stay. The output name is the argument with `-new` inserted before its first dot.\n\nExample: Convert an old resource\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nWrites the differences between two resource files.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The complete resource, for example from `translate`. |\n| `target` | `String` | yes |  | The resource to check. |\n\nWrites `<target>-diff.txt` next to the target with two sections: the keys of `source` that `target` misses (\"Add to\") and the keys of `target` that `source` does not have (\"Remove from\"), with their comments. Prints the counts and the output file.\n\nExample: Find new texts\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nMerges the texts of one resource into another.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The resource with new texts. |\n| `target` | `String` | yes |  | The resource to update. |\n\nGoes through `target` and replaces the text of each key that `source` also has. Keys missing in `source` keep their text; keys only in `source` are not added. Writes `<target>-merged.txt` next to the target and prints the number of merged keys.\n\nExample: Take translated texts\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nAligns the keys of a resource file.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | The resource file. |\n\nPads all keys to one column and keeps comments and empty lines. Writes `<source>-cleaned.txt` next to the file.\n\nExample: Tidy a resource\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nConnects the current directory to the Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | The URL of the project in the Code Editor, with `?id=project`. |\n\nAlias: `-e`. Opens a WebSocket connection to the project URL (`http` becomes `ws`) and lets the editor browse, read, create, save, rename, upload and remove files of the current directory and read its logs. Reconnects every 10 seconds. Prints `404 project not found` while the project does not exist and stops with `409 project is already open`.\n\nExample: Open a project\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nThe resource file written by the translate commands.\n\nStarts with `// Total.js translation file` and the creation time. Each line is `key : text`; `total4 translate` groups the lines under `// filename` comments that list the files using the text. Rename it to `<language>.resource` and put it in `/resources/`.\n\nExample: Content\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nThe CSV file written by total4 translatecsv.\n\nThe first row is `Hash;Text;Translation`. Each next row has the key, the text in double quotes and an empty translation.\n\nExample: Content\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabj7W1eN61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"de","title":"Kommandozeile (total4)","summary":"Jeder Befehl des Kommandozeilenwerkzeugs total4.","markdown":"---\ntitle: Kommandozeile (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Kommandozeile (total4)\n\n> Jeder Befehl des Kommandozeilenwerkzeugs total4.\n\nDas Werkzeug `total4` wird mit `npm install -g total4` installiert. Der Leitfaden [Kommandozeile (total4)](../../guides/command-line/) erklärt die Befehle mit Beispielen; diese Seite listet jeden Befehl, seine Argumente und seine Ausgabe auf.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nDas Kommandozeilenwerkzeug des Pakets total4.\n\nInstalliert mit `npm install -g total4` (der `bin`-Eintrag des Pakets). Das erste Argument ist der Befehl; `name`, `-name` und `--name` sind derselbe Befehl. Jeder Aufruf gibt zuerst einen Kopfkasten mit der Version aus. Ohne Befehl gibt es `Use \"total4 help\" to list all commands.` aus, und ein unbekannter Befehl gibt `Command \"...\" is invalid` aus.\n\nExample: Installieren und die Befehle auflisten\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nGibt die Liste aller Befehle aus.\n\nAliase: `h`, `-h`, `--help`. Gibt für jeden Befehl eine Zeile mit seinen Argumenten und einer kurzen Beschreibung aus.\n\nExample: Die Hilfe anzeigen\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nGibt nur den Kopf mit der Version aus.\n\nAliase: `-v`, `--version`. Das Werkzeug gibt seinen Kopfkasten aus, der die Version des Frameworks enthält, und endet.\n\nExample: Die Version anzeigen\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nStellt das aktuelle Verzeichnis als statische Dateien auf dem angegebenen Port bereit.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Der Port des HTTP-Servers. |\n\nDie Zahl muss das erste Argument sein. Der Server läuft im Debug-Modus auf `0.0.0.0`. Ein Verzeichnis gibt seine `index.html` zurück oder, wenn es keine gibt, eine erzeugte Verzeichnisliste mit Dateigrößen. HTML, Skripte und Styles werden ohne Kompilierung gesendet; `.less`-Dateien werden als `text/less` ausgeliefert. Temporäre Dateien landen im temporären Verzeichnis des Systems. Halte ihn mit `Ctrl+C` an.\n\nExample: Eine statische Website bereitstellen\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nGibt die Liste der offiziellen Projektvorlagen aus.\n\nLädt die Liste von GitHub herunter und gibt Name und Beschreibung jeder Vorlage aus. Ohne Verbindung gibt es `Total.js templates are currently unavailable.` aus.\n\nExample: Vorlagen auflisten\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nErstellt ein Bundle aus dem aktuellen Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Der Name der Bundle-Datei, mit der Endung `.bundle`. |\n\nSchreibt alle Dateien des aktuellen Verzeichnisses in eine einzelne `.bundle`-Datei und gibt das Verzeichnis, den Dateinamen, die Anzahl der Dateien und die Größe aus. Ausgeschlossen: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` mit ihren `.json`- und `.pid`-Dateien, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` und die Ausgabedatei. Siehe [Anwendungsstruktur](../../guides/application-structure/), wie Bundles geladen werden.\n\nExample: Eine Anwendung bündeln\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nErstellt eine .package-Datei aus dem aktuellen Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | Der Name der Paketdatei, mit der Endung `.package`. |\n\nFunktioniert wie `bundle`. Ausgeschlossen: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` und die Ausgabedatei. Kopiere das Ergebnis nach `/packages/` einer Anwendung.\n\nExample: Ein Paket erstellen\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nEntpackt ein Bundle oder ein Paket in das aktuelle Verzeichnis.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die `.bundle`- oder `.package`-Datei. |\n\nSchreibt jede Datei des Archivs in das aktuelle Verzeichnis, überschreibt dabei Dateien mit demselben Pfad und gibt die Anzahl der Dateien und die Größe aus.\n\nExample: Ein Bundle entpacken\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifiziert eine .js-, .css- oder .html-Datei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Die zu minifizierende Datei. |\n\nAliase: `-compress`, `-compile` (mit einem oder zwei Bindestrichen). Der Dateiname ist das letzte Argument. Schreibt `<name>.min.<extension>` neben die Datei und gibt `Minified: <path>` aus; andere Endungen werden nicht geschrieben. Eine fehlende Datei gibt `File not found` aus.\n\nExample: Ein Skript minifizieren\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nSammelt lokalisierbare Texte der Anwendung in translate.resource.\n\nAlias: `-t`. Liest `.html`- und `.js`-Dateien (und Dateien mit `sitemap` im Pfad) des aktuellen Verzeichnisses und aller seiner Unterverzeichnisse. Sammelt `@(text)`-Markierungen (Texte, die mit `#` und einem Nicht-Leerzeichen beginnen, werden übersprungen) und, in `.js`-Dateien, Schlüssel aus `$.invalid('key')`, `.error('key')` und `.err('key')`. Schreibt `translate.resource`, gruppiert nach `// filename`-Kommentaren, und gibt die Anzahl der Texte aus. Siehe [Lokalisierung](../../guides/localization/).\n\nExample: Eine Ressource erstellen\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nGibt die Ressourcenzeile für einen Text aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | Der zu übersetzende Text. |\n\nWenn das Argument keine vorhandene Datei ist, gibt das Werkzeug den Schlüssel (`T` und den Basis-36-Hash des Textes) und den Text aus, bereit zum Einfügen in eine Ressourcendatei.\n\nExample: Schlüssel eines Textes\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nErstellt translate.resource aus den Zeilen einer Textdatei.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Eine Textdatei mit einem Text pro Zeile. |\n\nJede nicht leere Zeile der Datei wird zu einem Eintrag mit einem `T`-Hash-Schlüssel. Das Ergebnis ist `translate.resource` im aktuellen Verzeichnis.\n\nExample: Ressource aus einer Liste von Texten\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nSammelt lokalisierbare Texte in translate.csv.\n\nAlias: `-c`. Liest `.html`- und `.js`-Dateien des aktuellen Verzeichnisses und seiner Unterverzeichnisse und schreibt jede eindeutige `@(text)`-Markierung als Zeile von `translate.csv` mit den Spalten `Hash;Text;Translation`.\n\nExample: CSV für einen Übersetzer\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nWandelt eine Ressource mit alten numerischen Schlüsseln in Total.js 4-Schlüssel um.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die alte Ressourcendatei. |\n\nAlias: `-4`. Schlüssel wie `T123` und `T-123` werden zu `T` und der Basis-36-Form der Zahl; andere Zeilen bleiben erhalten. Der Ausgabename ist das Argument mit `-new` vor dem ersten Punkt.\n\nExample: Eine alte Ressource umwandeln\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nSchreibt die Unterschiede zwischen zwei Ressourcendateien.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die vollständige Ressource, zum Beispiel aus `translate`. |\n| `target` | `String` | yes |  | Die zu prüfende Ressource. |\n\nSchreibt `<target>-diff.txt` neben das Ziel, mit zwei Abschnitten: den Schlüsseln von `source`, die in `target` fehlen (\"Add to\"), und den Schlüsseln von `target`, die `source` nicht hat (\"Remove from\"), jeweils mit ihren Kommentaren. Gibt die Anzahlen und die Ausgabedatei aus.\n\nExample: Neue Texte finden\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nFührt die Texte einer Ressource in eine andere zusammen.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die Ressource mit neuen Texten. |\n| `target` | `String` | yes |  | Die zu aktualisierende Ressource. |\n\nGeht `target` durch und ersetzt den Text jedes Schlüssels, den auch `source` hat. Schlüssel, die in `source` fehlen, behalten ihren Text; Schlüssel, die nur in `source` stehen, werden nicht hinzugefügt. Schreibt `<target>-merged.txt` neben das Ziel und gibt die Anzahl der zusammengeführten Schlüssel aus.\n\nExample: Übersetzte Texte übernehmen\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nRichtet die Schlüssel einer Ressourcendatei aus.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Die Ressourcendatei. |\n\nFüllt alle Schlüssel auf eine Spalte auf und behält Kommentare und leere Zeilen. Schreibt `<source>-cleaned.txt` neben die Datei.\n\nExample: Eine Ressource aufräumen\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nVerbindet das aktuelle Verzeichnis mit dem Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | Die URL des Projekts im Code Editor, mit `?id=project`. |\n\nAlias: `-e`. Öffnet eine WebSocket-Verbindung zur Projekt-URL (`http` wird zu `ws`) und lässt den Editor die Dateien des aktuellen Verzeichnisses durchsuchen, lesen, erstellen, speichern, umbenennen, hochladen und entfernen sowie seine Logs lesen. Verbindet sich alle 10 Sekunden neu. Gibt `404 project not found` aus, solange das Projekt nicht existiert, und hält mit `409 project is already open` an.\n\nExample: Ein Projekt öffnen\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nDie Ressourcendatei, die die translate-Befehle schreiben.\n\nBeginnt mit `// Total.js translation file` und dem Erstellungszeitpunkt. Jede Zeile ist `key : text`; `total4 translate` gruppiert die Zeilen unter `// filename`-Kommentaren, die die Dateien aufführen, die den Text verwenden. Benenne sie in `<language>.resource` um und lege sie in `/resources/` ab.\n\nExample: Inhalt\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nDie CSV-Datei, die total4 translatecsv schreibt.\n\nDie erste Zeile ist `Hash;Text;Translation`. Jede weitere Zeile hat den Schlüssel, den Text in doppelten Anführungszeichen und eine leere Übersetzung.\n\nExample: Inhalt\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabj7W1eN61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"es","title":"Línea de comandos (total4)","summary":"Todos los comandos de la herramienta de línea de comandos total4.","markdown":"---\ntitle: \"Línea de comandos (total4)\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Línea de comandos (total4)\n\n> Todos los comandos de la herramienta de línea de comandos total4.\n\nLa herramienta `total4` se instala con `npm install -g total4`. La guía [Línea de comandos (total4)](../../guides/command-line/) explica los comandos con ejemplos; esta página lista cada comando, sus argumentos y su salida.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nLa herramienta de línea de comandos del paquete total4.\n\nSe instala con `npm install -g total4` (la entrada `bin` del paquete). El primer argumento es el comando; `name`, `-name` y `--name` son el mismo comando. Cada ejecución imprime primero un recuadro de cabecera con la versión. Sin comando imprime `Use \"total4 help\" to list all commands.`, y un comando desconocido imprime `Command \"...\" is invalid`.\n\nExample: Instalar y listar los comandos\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nImprime la lista de todos los comandos.\n\nAlias: `h`, `-h`, `--help`. Imprime una línea por cada comando con sus argumentos y una breve descripción.\n\nExample: Mostrar la ayuda\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nImprime solo la cabecera con la versión.\n\nAlias: `-v`, `--version`. La herramienta imprime su recuadro de cabecera, que contiene la versión del framework, y termina.\n\nExample: Mostrar la versión\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nSirve el directorio actual como archivos estáticos en el puerto indicado.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | El puerto del servidor HTTP. |\n\nEl número debe ser el primer argumento. El servidor se ejecuta en modo debug en `0.0.0.0`. Un directorio devuelve su `index.html`, o un listado generado del directorio con los tamaños de los archivos si no lo hay. El HTML, los scripts y los estilos se envían sin compilar; los archivos `.less` se sirven como `text/less`. Los archivos temporales van al directorio temporal del sistema. Detenlo con `Ctrl+C`.\n\nExample: Servir un sitio estático\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nImprime la lista de plantillas oficiales de proyecto.\n\nDescarga la lista desde GitHub e imprime el nombre y la descripción de cada plantilla. Sin conexión imprime `Total.js templates are currently unavailable.`\n\nExample: Listar las plantillas\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrea un bundle del directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | El nombre del archivo del bundle, con la extensión `.bundle`. |\n\nEscribe todos los archivos del directorio actual en un archivo `.bundle` e imprime el directorio, el nombre del archivo, el número de archivos y el tamaño. Excluidos: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` con sus archivos `.json` y `.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` y el archivo de salida. Consulta [Estructura de la aplicación](../../guides/application-structure/) para ver cómo se cargan los bundles.\n\nExample: Crear el bundle de una aplicación\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nCrea un archivo .package del directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | El nombre del archivo del paquete, con la extensión `.package`. |\n\nFunciona como `bundle`. Excluidos: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` y el archivo de salida. Copia el resultado en `/packages/` de una aplicación.\n\nExample: Crear un paquete\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nExtrae un bundle o un paquete en el directorio actual.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo `.bundle` o `.package`. |\n\nEscribe cada archivo del archivo comprimido en el directorio actual, sobrescribiendo los archivos con la misma ruta, e imprime el número de archivos y el tamaño.\n\nExample: Extraer un bundle\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifica un archivo .js, .css o .html.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | El archivo que minificar. |\n\nAlias: `-compress`, `-compile` (con uno o dos guiones). El nombre del archivo es el último argumento. Escribe `<name>.min.<extension>` junto al archivo e imprime `Minified: <path>`; las demás extensiones no se escriben. Un archivo inexistente imprime `File not found`.\n\nExample: Minificar un script\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nRecoge los textos localizables de la aplicación en translate.resource.\n\nAlias: `-t`. Lee los archivos `.html` y `.js` (y los archivos con `sitemap` en su ruta) del directorio actual y de todos sus subdirectorios. Recoge los marcadores `@(text)` (se omiten los textos que empiezan por `#` y un carácter que no es un espacio) y, en los archivos `.js`, las claves de `$.invalid('key')`, `.error('key')` y `.err('key')`. Escribe `translate.resource` agrupado por comentarios `// filename` e imprime el número de textos. Consulta [Localización](../../guides/localization/).\n\nExample: Crear un recurso\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nImprime la línea de recurso de un texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | El texto que traducir. |\n\nCuando el argumento no es un archivo existente, la herramienta imprime la clave (`T` y el hash en base 36 del texto) y el texto, listos para pegar en un archivo de recursos.\n\nExample: Clave de un texto\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nCrea translate.resource a partir de las líneas de un archivo de texto.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un archivo de texto con un texto por línea. |\n\nCada línea no vacía del archivo se convierte en una entrada con una clave hash `T`. El resultado es `translate.resource` en el directorio actual.\n\nExample: Recurso a partir de una lista de textos\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nRecoge los textos localizables en translate.csv.\n\nAlias: `-c`. Lee los archivos `.html` y `.js` del directorio actual y de sus subdirectorios y escribe cada marcador `@(text)` único como una fila de `translate.csv` con las columnas `Hash;Text;Translation`.\n\nExample: CSV para un traductor\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nConvierte un recurso con claves numéricas antiguas a claves de Total.js 4.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El archivo de recursos antiguo. |\n\nAlias: `-4`. Las claves como `T123` y `T-123` pasan a ser `T` y la forma en base 36 del número; las demás líneas se mantienen. El nombre de salida es el argumento con `-new` insertado antes de su primer punto.\n\nExample: Convertir un recurso antiguo\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nEscribe las diferencias entre dos archivos de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El recurso completo, por ejemplo de `translate`. |\n| `target` | `String` | yes |  | El recurso que comprobar. |\n\nEscribe `<target>-diff.txt` junto al destino con dos secciones: las claves de `source` que le faltan a `target` (\"Add to\") y las claves de `target` que `source` no tiene (\"Remove from\"), con sus comentarios. Imprime los totales y el archivo de salida.\n\nExample: Encontrar textos nuevos\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nFusiona los textos de un recurso en otro.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El recurso con los textos nuevos. |\n| `target` | `String` | yes |  | El recurso que actualizar. |\n\nRecorre `target` y sustituye el texto de cada clave que también tiene `source`. Las claves que faltan en `source` conservan su texto; las claves que solo están en `source` no se añaden. Escribe `<target>-merged.txt` junto al destino e imprime el número de claves fusionadas.\n\nExample: Tomar los textos traducidos\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nAlinea las claves de un archivo de recursos.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | El archivo de recursos. |\n\nRellena todas las claves hasta una misma columna y conserva los comentarios y las líneas vacías. Escribe `<source>-cleaned.txt` junto al archivo.\n\nExample: Ordenar un recurso\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nConecta el directorio actual con Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | La URL del proyecto en Code Editor, con `?id=project`. |\n\nAlias: `-e`. Abre una conexión WebSocket a la URL del proyecto (`http` pasa a ser `ws`) y permite que el editor explore, lea, cree, guarde, renombre, suba y elimine archivos del directorio actual y lea sus logs. Se reconecta cada 10 segundos. Imprime `404 project not found` mientras el proyecto no existe y se detiene con `409 project is already open`.\n\nExample: Abrir un proyecto\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nEl archivo de recursos que escriben los comandos de traducción.\n\nEmpieza con `// Total.js translation file` y la hora de creación. Cada línea es `key : text`; `total4 translate` agrupa las líneas bajo comentarios `// filename` que listan los archivos que usan el texto. Renómbralo a `<language>.resource` y ponlo en `/resources/`.\n\nExample: Contenido\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nEl archivo CSV que escribe total4 translatecsv.\n\nLa primera fila es `Hash;Text;Translation`. Cada fila siguiente tiene la clave, el texto entre comillas dobles y una traducción vacía.\n\nExample: Contenido\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabj7W1eN61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"fr","title":"Ligne de commande (total4)","summary":"Toutes les commandes de l'outil en ligne de commande total4.","markdown":"---\ntitle: Ligne de commande (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Ligne de commande (total4)\n\n> Toutes les commandes de l'outil en ligne de commande total4.\n\nL'outil `total4` s'installe avec `npm install -g total4`. Le guide [Ligne de commande (total4)](../../guides/command-line/) explique les commandes avec des exemples ; cette page liste chaque commande, ses arguments et sa sortie.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nL'outil en ligne de commande du paquet total4.\n\nInstallé avec `npm install -g total4` (l'entrée `bin` du paquet). Le premier argument est la commande ; `name`, `-name` et `--name` sont la même commande. Chaque exécution affiche d'abord un encadré d'en-tête avec la version. Sans commande, il affiche `Use \"total4 help\" to list all commands.`, et une commande inconnue affiche `Command \"...\" is invalid`.\n\nExample: Installer et lister les commandes\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nAffiche la liste de toutes les commandes.\n\nAlias : `h`, `-h`, `--help`. Affiche une ligne par commande avec ses arguments et une courte description.\n\nExample: Afficher l'aide\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nAffiche uniquement l'en-tête avec la version.\n\nAlias : `-v`, `--version`. L'outil affiche son encadré d'en-tête, qui contient la version du framework, et se termine.\n\nExample: Afficher la version\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nSert le répertoire courant sous forme de fichiers statiques sur le port indiqué.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Le port du serveur HTTP. |\n\nLe nombre doit être le premier argument. Le serveur s'exécute en mode debug sur `0.0.0.0`. Un répertoire renvoie son `index.html`, ou un listing du répertoire généré avec les tailles des fichiers s'il n'y en a pas. Le HTML, les scripts et les styles sont envoyés sans compilation ; les fichiers `.less` sont servis en `text/less`. Les fichiers temporaires vont dans le répertoire temporaire du système. Arrête-le avec `Ctrl+C`.\n\nExample: Servir un site statique\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nAffiche la liste des templates de projet officiels.\n\nTélécharge la liste depuis GitHub et affiche le nom et la description de chaque template. Sans connexion, il affiche `Total.js templates are currently unavailable.`\n\nExample: Lister les templates\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrée un bundle du répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Le nom du fichier bundle, avec l'extension `.bundle`. |\n\nÉcrit tous les fichiers du répertoire courant dans un seul fichier `.bundle` et affiche le répertoire, le nom du fichier, le nombre de fichiers et la taille. Exclus : `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` avec leurs fichiers `.json` et `.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` et le fichier de sortie. Voir [Structure de l'application](../../guides/application-structure/) pour savoir comment les bundles sont chargés.\n\nExample: Créer le bundle d'une application\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nCrée un fichier .package du répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | Le nom du fichier paquet, avec l'extension `.package`. |\n\nFonctionne comme `bundle`. Exclus : `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` et le fichier de sortie. Copie le résultat dans `/packages/` d'une application.\n\nExample: Créer un paquet\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nExtrait un bundle ou un paquet dans le répertoire courant.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier `.bundle` ou `.package`. |\n\nÉcrit chaque fichier de l'archive dans le répertoire courant, en écrasant les fichiers ayant le même chemin, et affiche le nombre de fichiers et la taille.\n\nExample: Extraire un bundle\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifie un fichier .js, .css ou .html.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Le fichier à minifier. |\n\nAlias : `-compress`, `-compile` (avec un ou deux tirets). Le nom du fichier est le dernier argument. Écrit `<name>.min.<extension>` à côté du fichier et affiche `Minified: <path>` ; les autres extensions ne sont pas écrites. Un fichier manquant affiche `File not found`.\n\nExample: Minifier un script\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nCollecte les textes localisables de l'application dans translate.resource.\n\nAlias : `-t`. Lit les fichiers `.html` et `.js` (et les fichiers dont le chemin contient `sitemap`) du répertoire courant et de tous ses sous-répertoires. Collecte les marqueurs `@(text)` (les textes qui commencent par `#` et un caractère autre qu'un espace sont ignorés) et, dans les fichiers `.js`, les clés de `$.invalid('key')`, `.error('key')` et `.err('key')`. Écrit `translate.resource` regroupé par des commentaires `// filename` et affiche le nombre de textes. Voir [Localisation](../../guides/localization/).\n\nExample: Créer une ressource\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nAffiche la ligne de ressource pour un seul texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | Le texte à traduire. |\n\nLorsque l'argument n'est pas un fichier existant, l'outil affiche la clé (`T` et le hash en base 36 du texte) et le texte, prêts à être collés dans un fichier de ressources.\n\nExample: Clé d'un seul texte\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nCrée translate.resource à partir des lignes d'un fichier texte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un fichier texte avec un texte par ligne. |\n\nChaque ligne non vide du fichier devient une entrée avec une clé de hash `T`. Le résultat est `translate.resource` dans le répertoire courant.\n\nExample: Ressource à partir d'une liste de textes\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nCollecte les textes localisables dans translate.csv.\n\nAlias : `-c`. Lit les fichiers `.html` et `.js` du répertoire courant et de ses sous-répertoires et écrit chaque marqueur `@(text)` unique comme une ligne de `translate.csv` avec les colonnes `Hash;Text;Translation`.\n\nExample: CSV pour un traducteur\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nConvertit une ressource aux anciennes clés numériques en clés Total.js 4.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | L'ancien fichier de ressources. |\n\nAlias : `-4`. Les clés comme `T123` et `T-123` deviennent `T` suivi de la forme en base 36 du nombre ; les autres lignes restent. Le nom de sortie est l'argument avec `-new` inséré avant son premier point.\n\nExample: Convertir une ancienne ressource\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nÉcrit les différences entre deux fichiers de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | La ressource complète, par exemple issue de `translate`. |\n| `target` | `String` | yes |  | La ressource à vérifier. |\n\nÉcrit `<target>-diff.txt` à côté de la cible avec deux sections : les clés de `source` qui manquent dans `target` (\"Add to\") et les clés de `target` que `source` ne possède pas (\"Remove from\"), avec leurs commentaires. Affiche les nombres et le fichier de sortie.\n\nExample: Trouver les nouveaux textes\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nFusionne les textes d'une ressource dans une autre.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | La ressource contenant les nouveaux textes. |\n| `target` | `String` | yes |  | La ressource à mettre à jour. |\n\nParcourt `target` et remplace le texte de chaque clé que `source` possède aussi. Les clés absentes de `source` gardent leur texte ; les clés présentes uniquement dans `source` ne sont pas ajoutées. Écrit `<target>-merged.txt` à côté de la cible et affiche le nombre de clés fusionnées.\n\nExample: Reprendre les textes traduits\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nAligne les clés d'un fichier de ressources.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Le fichier de ressources. |\n\nComplète toutes les clés pour les aligner sur une colonne et conserve les commentaires et les lignes vides. Écrit `<source>-cleaned.txt` à côté du fichier.\n\nExample: Mettre en ordre une ressource\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nConnecte le répertoire courant au Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL du projet dans le Code Editor, avec `?id=project`. |\n\nAlias : `-e`. Ouvre une connexion WebSocket vers l'URL du projet (`http` devient `ws`) et permet à l'éditeur de parcourir, lire, créer, enregistrer, renommer, téléverser et supprimer les fichiers du répertoire courant et de lire ses logs. Se reconnecte toutes les 10 secondes. Affiche `404 project not found` tant que le projet n'existe pas et s'arrête avec `409 project is already open`.\n\nExample: Ouvrir un projet\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nLe fichier de ressources écrit par les commandes de traduction.\n\nCommence par `// Total.js translation file` et la date de création. Chaque ligne est `key : text` ; `total4 translate` regroupe les lignes sous des commentaires `// filename` qui listent les fichiers utilisant le texte. Renomme-le en `<language>.resource` et place-le dans `/resources/`.\n\nExample: Contenu\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nLe fichier CSV écrit par total4 translatecsv.\n\nLa première ligne est `Hash;Text;Translation`. Chaque ligne suivante contient la clé, le texte entre guillemets doubles et une traduction vide.\n\nExample: Contenu\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabj7W1eN61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"it","title":"Riga di comando (total4)","summary":"Tutti i comandi dello strumento da riga di comando total4.","markdown":"---\ntitle: Riga di comando (total4)\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Riga di comando (total4)\n\n> Tutti i comandi dello strumento da riga di comando total4.\n\nLo strumento `total4` si installa con `npm install -g total4`. La guida [Riga di comando (total4)](../../guides/command-line/) spiega i comandi con esempi; questa pagina elenca ogni comando, i suoi argomenti e il suo output.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nLo strumento da riga di comando del pacchetto total4.\n\nSi installa con `npm install -g total4` (la voce `bin` del pacchetto). Il primo argomento è il comando; `name`, `-name` e `--name` sono lo stesso comando. Ogni esecuzione stampa prima un riquadro di intestazione con la versione. Senza un comando stampa `Use \"total4 help\" to list all commands.`, e un comando sconosciuto stampa `Command \"...\" is invalid`.\n\nExample: Installare ed elencare i comandi\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nStampa l'elenco di tutti i comandi.\n\nAlias: `h`, `-h`, `--help`. Stampa una riga per ogni comando con i suoi argomenti e una breve descrizione.\n\nExample: Mostrare l'aiuto\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nStampa solo l'intestazione con la versione.\n\nAlias: `-v`, `--version`. Lo strumento stampa il suo riquadro di intestazione, che contiene la versione del framework, e termina.\n\nExample: Mostrare la versione\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nServe la directory corrente come file statici sulla porta indicata.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | La porta del server HTTP. |\n\nIl numero deve essere il primo argomento. Il server gira in modalità debug su `0.0.0.0`. Una directory restituisce il suo `index.html`, oppure un elenco della directory generato con le dimensioni dei file quando non c'è. HTML, script e stili vengono inviati senza compilazione; i file `.less` vengono serviti come `text/less`. I file temporanei finiscono nella directory temporanea del sistema. Fermalo con `Ctrl+C`.\n\nExample: Servire un sito statico\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nStampa l'elenco dei template di progetto ufficiali.\n\nScarica l'elenco da GitHub e stampa il nome e la descrizione di ogni template. Senza connessione stampa `Total.js templates are currently unavailable.`\n\nExample: Elencare i template\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nCrea un bundle della directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Il nome del file del bundle, con l'estensione `.bundle`. |\n\nScrive tutti i file della directory corrente in un unico file `.bundle` e stampa la directory, il nome del file, il numero di file e la dimensione. Esclusi: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` con i loro file `.json` e `.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` e il file di output. Vedi [Struttura dell'applicazione](../../guides/application-structure/) per come vengono caricati i bundle.\n\nExample: Creare il bundle di un'applicazione\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nCrea un file .package della directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | Il nome del file del pacchetto, con l'estensione `.package`. |\n\nFunziona come `bundle`. Esclusi: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` e il file di output. Copia il risultato in `/packages/` di un'applicazione.\n\nExample: Creare un pacchetto\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nEstrae un bundle o un pacchetto nella directory corrente.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file `.bundle` o `.package`. |\n\nScrive ogni file dell'archivio nella directory corrente, sovrascrivendo i file con lo stesso percorso, e stampa il numero di file e la dimensione.\n\nExample: Estrarre un bundle\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifica un file .js, .css o .html.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Il file da minificare. |\n\nAlias: `-compress`, `-compile` (con uno o due trattini). Il nome del file è l'ultimo argomento. Scrive `<name>.min.<extension>` accanto al file e stampa `Minified: <path>`; le altre estensioni non vengono scritte. Un file mancante stampa `File not found`.\n\nExample: Minificare uno script\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nRaccoglie i testi localizzabili dell'applicazione in translate.resource.\n\nAlias: `-t`. Legge i file `.html` e `.js` (e i file con `sitemap` nel percorso) della directory corrente e di tutte le sue sottodirectory. Raccoglie i marcatori `@(text)` (i testi che iniziano con `#` e un carattere diverso da uno spazio vengono saltati) e, nei file `.js`, le chiavi di `$.invalid('key')`, `.error('key')` e `.err('key')`. Scrive `translate.resource` raggruppato da commenti `// filename` e stampa il numero di testi. Vedi [Localizzazione](../../guides/localization/).\n\nExample: Creare una risorsa\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nStampa la riga di risorsa per un singolo testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | Il testo da tradurre. |\n\nQuando l'argomento non è un file esistente, lo strumento stampa la chiave (`T` e l'hash in base 36 del testo) e il testo, pronti da incollare in un file di risorse.\n\nExample: Chiave di un singolo testo\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nCrea translate.resource dalle righe di un file di testo.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Un file di testo con un testo per riga. |\n\nOgni riga non vuota del file diventa una voce con una chiave hash `T`. Il risultato è `translate.resource` nella directory corrente.\n\nExample: Risorsa da un elenco di testi\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nRaccoglie i testi localizzabili in translate.csv.\n\nAlias: `-c`. Legge i file `.html` e `.js` della directory corrente e delle sue sottodirectory e scrive ogni marcatore `@(text)` univoco come riga di `translate.csv` con le colonne `Hash;Text;Translation`.\n\nExample: CSV per un traduttore\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nConverte una risorsa con vecchie chiavi numeriche in chiavi di Total.js 4.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Il vecchio file di risorse. |\n\nAlias: `-4`. Le chiavi come `T123` e `T-123` diventano `T` più la forma in base 36 del numero; le altre righe restano invariate. Il nome di output è l'argomento con `-new` inserito prima del suo primo punto.\n\nExample: Convertire una vecchia risorsa\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nScrive le differenze tra due file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | La risorsa completa, per esempio da `translate`. |\n| `target` | `String` | yes |  | La risorsa da verificare. |\n\nScrive `<target>-diff.txt` accanto al target con due sezioni: le chiavi di `source` che mancano in `target` (\"Add to\") e le chiavi di `target` che `source` non ha (\"Remove from\"), con i loro commenti. Stampa i conteggi e il file di output.\n\nExample: Trovare i nuovi testi\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nUnisce i testi di una risorsa in un'altra.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | La risorsa con i nuovi testi. |\n| `target` | `String` | yes |  | La risorsa da aggiornare. |\n\nScorre `target` e sostituisce il testo di ogni chiave presente anche in `source`. Le chiavi mancanti in `source` mantengono il loro testo; le chiavi presenti solo in `source` non vengono aggiunte. Scrive `<target>-merged.txt` accanto al target e stampa il numero di chiavi unite.\n\nExample: Prendere i testi tradotti\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nAllinea le chiavi di un file di risorse.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Il file di risorse. |\n\nAllinea tutte le chiavi su una colonna e mantiene commenti e righe vuote. Scrive `<source>-cleaned.txt` accanto al file.\n\nExample: Riordinare una risorsa\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nCollega la directory corrente al Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | L'URL del progetto nel Code Editor, con `?id=project`. |\n\nAlias: `-e`. Apre una connessione WebSocket all'URL del progetto (`http` diventa `ws`) e permette all'editor di sfogliare, leggere, creare, salvare, rinominare, caricare e rimuovere i file della directory corrente e di leggerne i log. Si riconnette ogni 10 secondi. Stampa `404 project not found` finché il progetto non esiste e si ferma con `409 project is already open`.\n\nExample: Aprire un progetto\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nIl file di risorse scritto dai comandi di traduzione.\n\nInizia con `// Total.js translation file` e l'ora di creazione. Ogni riga è `key : text`; `total4 translate` raggruppa le righe sotto commenti `// filename` che elencano i file che usano il testo. Rinominalo in `<language>.resource` e mettilo in `/resources/`.\n\nExample: Contenuto\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nIl file CSV scritto da total4 translatecsv.\n\nLa prima riga è `Hash;Text;Translation`. Ogni riga successiva contiene la chiave, il testo tra virgolette doppie e una traduzione vuota.\n\nExample: Contenuto\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"Jabj7W1eN61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/command-line/","project":"total-js-v4","version":"0-0-99","section":"reference","language":"sk","title":"Príkazový riadok (total4)","summary":"Všetky príkazy nástroja príkazového riadku total4.","markdown":"---\ntitle: \"Príkazový riadok (total4)\"\nproject: Total.js V4\nversion: 0.0.99\nsection: reference\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/reference/command-line/\nupdated: 2026-11-16T15:41:10.817Z\n---\n\n# Príkazový riadok (total4)\n\n> Všetky príkazy nástroja príkazového riadku total4.\n\nNástroj `total4` sa inštaluje cez `npm install -g total4`. Príručka [Príkazový riadok (total4)](../../guides/command-line/) vysvetľuje príkazy s príkladmi; táto stránka uvádza každý príkaz, jeho argumenty a výstup.\n\n## API\n\n### total4 <command> [arguments]\n\nType: `command`\n\nNástroj príkazového riadku balíka total4.\n\nInštaluje sa cez `npm install -g total4` (položka `bin` balíka). Prvý argument je príkaz; `name`, `-name` a `--name` sú ten istý príkaz. Každé spustenie najprv vypíše hlavičku s verziou. Bez príkazu vypíše `Use \"total4 help\" to list all commands.` a neznámy príkaz vypíše `Command \"...\" is invalid`.\n\nExample: Inštalácia a výpis príkazov\n```bash\nnpm install -g total4\ntotal4 help\n```\n\n### total4 help\n\nType: `command`\n\nVypíše zoznam všetkých príkazov.\n\nAliasy: `h`, `-h`, `--help`. Pre každý príkaz vypíše jeden riadok s jeho argumentmi a krátkym popisom.\n\nExample: Zobrazenie pomocníka\n```bash\ntotal4 help\n```\n\n### total4 version\n\nType: `command`\n\nVypíše len hlavičku s verziou.\n\nAliasy: `-v`, `--version`. Nástroj vypíše svoju hlavičku, ktorá obsahuje verziu frameworku, a skončí.\n\nExample: Zobrazenie verzie\n```bash\ntotal4 -v\n```\n\n### total4 <port>\n\nType: `command`\n\nObslúži aktuálny adresár ako statické súbory na zadanom porte.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `port` | `Number` | yes |  | Port HTTP servera. |\n\nČíslo musí byť prvým argumentom. Server beží v režime debug na `0.0.0.0`. Adresár vráti svoj `index.html` alebo vygenerovaný výpis adresára s veľkosťami súborov, keď `index.html` neexistuje. HTML, skripty a štýly sa posielajú bez kompilácie; súbory `.less` sa posielajú ako `text/less`. Dočasné súbory idú do dočasného adresára systému. Zastavíš ho cez `Ctrl+C`.\n\nExample: Obsluha statického webu\n```bash\ncd ~/www/landing\ntotal4 8000\n# open http://127.0.0.1:8000/\n```\n\n### total4 templates\n\nType: `command`\n\nVypíše zoznam oficiálnych šablón projektov.\n\nStiahne zoznam z GitHubu a vypíše názov a popis každej šablóny. Bez pripojenia vypíše `Total.js templates are currently unavailable.`\n\nExample: Výpis šablón\n```bash\ntotal4 templates\n```\n\n### total4 bundle [filename]\n\nType: `command`\n\nVytvorí bundle z aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `app.bundle` | Názov súboru bundlu s príponou `.bundle`. |\n\nZapíše všetky súbory aktuálneho adresára do jedného súboru `.bundle` a vypíše adresár, názov súboru, počet súborov a veľkosť. Vylúčené: `/bundle.json`, `/debug.js`, `/release.js`, `/index.js` s ich súbormi `.json` a `.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.src/`, `/.git/` a výstupný súbor. Ako sa bundly načítavajú, pozri v časti [Štruktúra aplikácie](../../guides/application-structure/).\n\nExample: Bundle aplikácie\n```bash\ncd ~/projects/eshop\ntotal4 --bundle eshop.bundle\n# copy eshop.bundle to /bundles/ of another application\n```\n\n### total4 package [filename]\n\nType: `command`\n\nVytvorí súbor .package z aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | no | `noname.package` | Názov súboru balíka s príponou `.package`. |\n\nFunguje ako `bundle`. Vylúčené: `/bundle.json`, `/debug.js`, `/release.js`, `/debug.pid`, `/package.json`, `/readme.md`, `/license.txt`, `/bundles/`, `/tmp/`, `/.git/` a výstupný súbor. Výsledok skopíruj do `/packages/` aplikácie.\n\nExample: Vytvorenie balíka\n```bash\ncd ~/packages/reports\ntotal4 package reports.package\n```\n\n### total4 extract <filename>\n\nType: `command` · Since: `0.0.89`\n\nRozbalí bundle alebo balík do aktuálneho adresára.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor `.bundle` alebo `.package`. |\n\nZapíše každý súbor archívu do aktuálneho adresára, prepíše súbory s rovnakou cestou a vypíše počet súborov a veľkosť.\n\nExample: Rozbalenie bundlu\n```bash\nmkdir restored && cd restored\ntotal4 --extract ../eshop.bundle\n```\n\n### total4 minify <filename>\n\nType: `command`\n\nMinifikuje súbor .js, .css alebo .html.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Súbor na minifikáciu. |\n\nAliasy: `-compress`, `-compile` (s jednou alebo dvoma pomlčkami). Názov súboru je posledný argument. Zapíše `<name>.min.<extension>` vedľa súboru a vypíše `Minified: <path>`; iné prípony sa nezapíšu. Chýbajúci súbor vypíše `File not found`.\n\nExample: Minifikácia skriptu\n```bash\ntotal4 minify public/js/app.js\n# writes public/js/app.min.js\n```\n\n### total4 translate\n\nType: `command`\n\nZozbiera lokalizovateľné texty aplikácie do translate.resource.\n\nAlias: `-t`. Číta súbory `.html` a `.js` (a súbory so `sitemap` v ceste) aktuálneho adresára a všetkých jeho podadresárov. Zozbiera značky `@(text)` (texty, ktoré začínajú `#` a znakom, ktorý nie je medzera, sa preskočia) a v súboroch `.js` kľúče z `$.invalid('key')`, `.error('key')` a `.err('key')`. Zapíše `translate.resource` zoskupený podľa komentárov `// filename` a vypíše počet textov. Pozri [Lokalizácia](../../guides/localization/).\n\nExample: Vytvorenie zdroja\n```bash\ncd ~/projects/eshop\ntotal4 translate\ncp translate.resource resources/sk.resource\n```\n\n### total4 translate \"TEXT\"\n\nType: `command`\n\nVypíše riadok zdroja pre jeden text.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `TEXT` | `String` | yes |  | Text na preklad. |\n\nKeď argument nie je existujúci súbor, nástroj vypíše kľúč (`T` a hash textu v sústave so základom 36) a text, pripravené na vloženie do súboru zdroja.\n\nExample: Kľúč jedného textu\n```bash\ntotal4 translate \"Add to cart\"\n```\n\n### total4 translate <filename>\n\nType: `command`\n\nVytvorí translate.resource z riadkov textového súboru.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `filename` | `String` | yes |  | Textový súbor s jedným textom na riadok. |\n\nKaždý neprázdny riadok súboru sa stane jedným záznamom s kľúčom v tvare hashu `T`. Výsledkom je `translate.resource` v aktuálnom adresári.\n\nExample: Zdroj zo zoznamu textov\n```bash\ntotal4 translate texts.txt\n```\n\n### total4 translatecsv\n\nType: `command`\n\nZozbiera lokalizovateľné texty do translate.csv.\n\nAlias: `-c`. Číta súbory `.html` a `.js` aktuálneho adresára a jeho podadresárov a každú jedinečnú značku `@(text)` zapíše ako riadok súboru `translate.csv` so stĺpcami `Hash;Text;Translation`.\n\nExample: CSV pre prekladateľa\n```bash\ntotal4 translatecsv\n# send translate.csv to the translator\n```\n\n### total4 translate4 <source>\n\nType: `command`\n\nPrevedie zdroj so starými číselnými kľúčmi na kľúče Total.js 4.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Starý súbor zdroja. |\n\nAlias: `-4`. Kľúče ako `T123` a `T-123` sa zmenia na `T` a tvar čísla v sústave so základom 36; ostatné riadky zostanú. Výstupný názov je argument s `-new` vloženým pred jeho prvú bodku.\n\nExample: Prevod starého zdroja\n```bash\ncd resources\ntotal4 translate4 sk.resource\n# writes sk-new.resource\n```\n\n### total4 diff <source> <target>\n\nType: `command`\n\nZapíše rozdiely medzi dvoma súbormi zdrojov.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Úplný zdroj, napríklad z `translate`. |\n| `target` | `String` | yes |  | Zdroj na kontrolu. |\n\nZapíše `<target>-diff.txt` vedľa cieľa s dvoma sekciami: kľúče zo `source`, ktoré v `target` chýbajú (\"Add to\"), a kľúče z `target`, ktoré `source` nemá (\"Remove from\"), spolu s ich komentármi. Vypíše počty a výstupný súbor.\n\nExample: Nájdenie nových textov\n```bash\ntotal4 translate\ntotal4 diff translate.resource resources/sk.resource\n# read resources/sk-diff.txt\n```\n\n### total4 merge <source> <target>\n\nType: `command`\n\nZlúči texty jedného zdroja do iného.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Zdroj s novými textami. |\n| `target` | `String` | yes |  | Zdroj na aktualizáciu. |\n\nPrejde `target` a nahradí text každého kľúča, ktorý má aj `source`. Kľúče, ktoré v `source` chýbajú, si ponechajú svoj text; kľúče, ktoré sú len v `source`, sa nepridajú. Zapíše `<target>-merged.txt` vedľa cieľa a vypíše počet zlúčených kľúčov.\n\nExample: Prevzatie preložených textov\n```bash\ntotal4 merge sk-from-translator.resource resources/sk.resource\n# writes resources/sk-merged.txt\n```\n\n### total4 clean <source>\n\nType: `command`\n\nZarovná kľúče súboru zdroja.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `source` | `String` | yes |  | Súbor zdroja. |\n\nDoplní všetky kľúče do jedného stĺpca a ponechá komentáre a prázdne riadky. Zapíše `<source>-cleaned.txt` vedľa súboru.\n\nExample: Upratanie zdroja\n```bash\ntotal4 clean resources/sk.resource\n# writes resources/sk-cleaned.txt\n```\n\n### total4 edit <url>\n\nType: `command` · Since: `0.0.46`\n\nPripojí aktuálny adresár k Total.js Code Editor.\n\n| Parameter | Type | Required | Default | Description |\n| --- | --- | --- | --- | --- |\n| `url` | `String` | yes |  | URL projektu v Code Editor, s `?id=project`. |\n\nAlias: `-e`. Otvorí spojenie WebSocket na URL projektu (`http` sa zmení na `ws`) a umožní editoru prechádzať, čítať, vytvárať, ukladať, premenovávať, nahrávať a odstraňovať súbory aktuálneho adresára a čítať jeho logy. Každých 10 sekúnd sa znova pripojí. Vypisuje `404 project not found`, kým projekt neexistuje, a skončí s `409 project is already open`.\n\nExample: Otvorenie projektu\n```bash\ncd ~/projects/eshop\ntotal4 edit \"https://code.example.com/?id=eshop\"\n```\n\n### translate.resource\n\nType: `type`\n\nSúbor zdroja, ktorý zapisujú prekladové príkazy.\n\nZačína `// Total.js translation file` a časom vytvorenia. Každý riadok má tvar `key : text`; `total4 translate` zoskupuje riadky pod komentáre `// filename`, ktoré uvádzajú súbory používajúce daný text. Premenuj ho na `<language>.resource` a vlož ho do `/resources/`.\n\nExample: Obsah\n```text\n// Total.js translation file\n// Created: 2024-05-10 09:30\n\n// views/index.html\nT1x9c0ks     : Add to cart\nT3jf0a2      : Checkout\n```\n\n### translate.csv\n\nType: `type`\n\nSúbor CSV, ktorý zapisuje total4 translatecsv.\n\nPrvý riadok je `Hash;Text;Translation`. Každý ďalší riadok má kľúč, text v dvojitých úvodzovkách a prázdny preklad.\n\nExample: Obsah\n```text\nHash;Text;Translation\nT1x9c0ks;\"Add to cart\";\nT3jf0a2;\"Checkout\";\n```\n","entries":[{"type":"command","name":"total4","signature":"total4 <command> [arguments]","since":"","deprecated":false},{"type":"command","name":"total4 help","signature":"total4 help","since":"","deprecated":false},{"type":"command","name":"total4 version","signature":"total4 version","since":"","deprecated":false},{"type":"command","name":"total4 <port>","signature":"total4 <port>","since":"","deprecated":false},{"type":"command","name":"total4 templates","signature":"total4 templates","since":"","deprecated":false},{"type":"command","name":"total4 bundle","signature":"total4 bundle [filename]","since":"","deprecated":false},{"type":"command","name":"total4 package","signature":"total4 package [filename]","since":"","deprecated":false},{"type":"command","name":"total4 extract","signature":"total4 extract <filename>","since":"0.0.89","deprecated":false},{"type":"command","name":"total4 minify","signature":"total4 minify <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translate","signature":"total4 translate","since":"","deprecated":false},{"type":"command","name":"total4 translate \"TEXT\"","signature":"total4 translate \"TEXT\"","since":"","deprecated":false},{"type":"command","name":"total4 translate <filename>","signature":"total4 translate <filename>","since":"","deprecated":false},{"type":"command","name":"total4 translatecsv","signature":"total4 translatecsv","since":"","deprecated":false},{"type":"command","name":"total4 translate4","signature":"total4 translate4 <source>","since":"","deprecated":false},{"type":"command","name":"total4 diff","signature":"total4 diff <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 merge","signature":"total4 merge <source> <target>","since":"","deprecated":false},{"type":"command","name":"total4 clean","signature":"total4 clean <source>","since":"","deprecated":false},{"type":"command","name":"total4 edit","signature":"total4 edit <url>","since":"0.0.46","deprecated":false},{"type":"type","name":"translate.resource","signature":"translate.resource","since":"","deprecated":false},{"type":"type","name":"translate.csv","signature":"translate.csv","since":"","deprecated":false}],"license":"MIT","updated":"2026-11-16T15:41:10.817Z"}
{"id":"JabUK22Ex61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"en","title":"0.0.99","summary":"What changed in release 0.0.99 (2025-03-01).","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> What changed in release 0.0.99 (2025-03-01).\n\nRelease 0.0.99 of the npm package `total4`, published on 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## New\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Fixed\n\n- The `Message-ID` generator of email messages.\n- Cloning buffers in `FlowStream` (critical).\n- Decoding encoded HTML entities in the HTML parser.\n- Loading an empty flow with `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUK22Ex61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"de","title":"0.0.99","summary":"Was sich in Release 0.0.99 (2025-03-01) geändert hat.","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> Was sich in Release 0.0.99 (2025-03-01) geändert hat.\n\nRelease 0.0.99 des npm-Pakets `total4`, veröffentlicht am 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## Neu\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Behoben\n\n- Der Generator für `Message-ID` von E-Mail-Nachrichten.\n- Das Klonen von Buffern in `FlowStream` (kritisch).\n- Das Dekodieren kodierter HTML-Entities im HTML-Parser.\n- Das Laden eines leeren Flows mit `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUK22Ex61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"es","title":"0.0.99","summary":"Qué cambió en la versión 0.0.99 (2025-03-01).","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> Qué cambió en la versión 0.0.99 (2025-03-01).\n\nVersión 0.0.99 del paquete npm `total4`, publicada el 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## Novedades\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Correcciones\n\n- El generador de `Message-ID` de los mensajes de email.\n- La clonación de buffers en `FlowStream` (crítico).\n- La decodificación de entidades HTML codificadas en el parser de HTML.\n- La carga de un flow vacío con `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUK22Ex61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"fr","title":"0.0.99","summary":"Ce qui a changé dans la version 0.0.99 (2025-03-01).","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> Ce qui a changé dans la version 0.0.99 (2025-03-01).\n\nVersion 0.0.99 du paquet npm `total4`, publiée le 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## Nouveautés\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Corrections\n\n- Le générateur de `Message-ID` des e-mails.\n- Le clonage des buffers dans `FlowStream` (critique).\n- Le décodage des entités HTML encodées dans le parseur HTML.\n- Le chargement d'un flow vide avec `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUK22Ex61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"it","title":"0.0.99","summary":"Cosa è cambiato nella versione 0.0.99 (2025-03-01).","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> Cosa è cambiato nella versione 0.0.99 (2025-03-01).\n\nVersione 0.0.99 del pacchetto npm `total4`, pubblicata il 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## Novità\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Correzioni\n\n- Il generatore di `Message-ID` dei messaggi e-mail.\n- Clonazione dei buffer in `FlowStream` (critico).\n- Decodifica delle entità HTML codificate nel parser HTML.\n- Caricamento di un flow vuoto con `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUK22Ex61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-99/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"sk","title":"0.0.99","summary":"Čo sa zmenilo vo verzii 0.0.99 (2025-03-01).","markdown":"---\ntitle: 0.0.99\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-99/\nupdated: 2026-11-15T11:04:19.869Z\n---\n\n# 0.0.99\n\n> Čo sa zmenilo vo verzii 0.0.99 (2025-03-01).\n\nVerzia 0.0.99 npm balíka `total4`, zverejnená 2025-03-01.\n\n```bash\nnpm install total4@0.0.99\n```\n\n## Nové\n\n- `FILESTORAGE().clone(id, newid, [callback])`.\n\n## Opravené\n\n- Generátor `Message-ID` pre e-mailové správy.\n- Klonovanie bufferov vo `FlowStream` (kritické).\n- Dekódovanie zakódovaných HTML entít v HTML parseri.\n- Načítanie prázdneho flow cez `Flow.load()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:19.869Z"}
{"id":"JabUJx2Ax61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"en","title":"0.0.98","summary":"What changed in release 0.0.98 (2025-01-13).","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> What changed in release 0.0.98 (2025-01-13).\n\nRelease 0.0.98 of the npm package `total4`, published on 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Changed\n\n- The Markdown parser was improved.\n- The HTML parser was improved.\n\n## Fixed\n\n- Middleware declared inline (`&middleware`) in `ROUTE()`.\n- Partial validation.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJx2Ax61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"de","title":"0.0.98","summary":"Was sich in Release 0.0.98 (2025-01-13) geändert hat.","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> Was sich in Release 0.0.98 (2025-01-13) geändert hat.\n\nRelease 0.0.98 des npm-Pakets `total4`, veröffentlicht am 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Geändert\n\n- Der Markdown-Parser wurde verbessert.\n- Der HTML-Parser wurde verbessert.\n\n## Behoben\n\n- Inline deklarierte Middleware (`&middleware`) in `ROUTE()`.\n- Teilvalidierung.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJx2Ax61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"es","title":"0.0.98","summary":"Qué cambió en la versión 0.0.98 (2025-01-13).","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> Qué cambió en la versión 0.0.98 (2025-01-13).\n\nVersión 0.0.98 del paquete npm `total4`, publicada el 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Cambios\n\n- Se mejoró el parser de Markdown.\n- Se mejoró el parser de HTML.\n\n## Correcciones\n\n- Middleware declarado en línea (`&middleware`) en `ROUTE()`.\n- Validación parcial.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJx2Ax61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"fr","title":"0.0.98","summary":"Ce qui a changé dans la version 0.0.98 (2025-01-13).","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> Ce qui a changé dans la version 0.0.98 (2025-01-13).\n\nVersion 0.0.98 du paquet npm `total4`, publiée le 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Modifications\n\n- Le parseur Markdown a été amélioré.\n- Le parseur HTML a été amélioré.\n\n## Corrections\n\n- Middleware déclaré en ligne (`&middleware`) dans `ROUTE()`.\n- Validation partielle.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJx2Ax61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"it","title":"0.0.98","summary":"Cosa è cambiato nella versione 0.0.98 (2025-01-13).","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> Cosa è cambiato nella versione 0.0.98 (2025-01-13).\n\nVersione 0.0.98 del pacchetto npm `total4`, pubblicata il 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Modifiche\n\n- Il parser Markdown è stato migliorato.\n- Il parser HTML è stato migliorato.\n\n## Correzioni\n\n- Middleware dichiarato inline (`&middleware`) in `ROUTE()`.\n- Validazione parziale.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJx2Ax61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-98/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"sk","title":"0.0.98","summary":"Čo sa zmenilo vo verzii 0.0.98 (2025-01-13).","markdown":"---\ntitle: 0.0.98\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-98/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.98\n\n> Čo sa zmenilo vo verzii 0.0.98 (2025-01-13).\n\nVerzia 0.0.98 npm balíka `total4`, zverejnená 2025-01-13.\n\n```bash\nnpm install total4@0.0.98\n```\n\n## Zmenené\n\n- Vylepšený Markdown parser.\n- Vylepšený HTML parser.\n\n## Opravené\n\n- Middleware deklarovaný inline (`&middleware`) v `ROUTE()`.\n- Čiastočná validácia.\n- `Image.measureWEBP()`.\n- `RESTBuilder.promise()`.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"en","title":"0.0.97","summary":"What changed in release 0.0.97 (2024-07-30).","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> What changed in release 0.0.97 (2024-07-30).\n\nRelease 0.0.97 of the npm package `total4`, published on 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## New\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` in schema and action operations.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- The icon validator accepts the `tic` keyword.\n\n## Changed\n\n- `Number.pluralize()` was improved.\n- `DATA.query()` was improved.\n\n## Fixed\n\n- Links of email addresses and phone numbers in Markdown.\n- Formatting the number `0` with the `format` helper of Tangular.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"de","title":"0.0.97","summary":"Was sich in Release 0.0.97 (2024-07-30) geändert hat.","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> Was sich in Release 0.0.97 (2024-07-30) geändert hat.\n\nRelease 0.0.97 des npm-Pakets `total4`, veröffentlicht am 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## Neu\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` in Operations von Schemas und Actions.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- Der Icon-Validator akzeptiert das Schlüsselwort `tic`.\n\n## Geändert\n\n- `Number.pluralize()` wurde verbessert.\n- `DATA.query()` wurde verbessert.\n\n## Behoben\n\n- Links von E-Mail-Adressen und Telefonnummern in Markdown.\n- Formatierung der Zahl `0` mit dem Helfer `format` von Tangular.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"es","title":"0.0.97","summary":"Qué cambió en la versión 0.0.97 (2024-07-30).","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> Qué cambió en la versión 0.0.97 (2024-07-30).\n\nVersión 0.0.97 del paquete npm `total4`, publicada el 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## Novedades\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` en las operaciones de esquemas y acciones.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- El validador de iconos acepta la palabra clave `tic`.\n\n## Cambios\n\n- Se mejoró `Number.pluralize()`.\n- Se mejoró `DATA.query()`.\n\n## Correcciones\n\n- Enlaces de direcciones de email y números de teléfono en Markdown.\n- Formateo del número `0` con el helper `format` de Tangular.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"fr","title":"0.0.97","summary":"Ce qui a changé dans la version 0.0.97 (2024-07-30).","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> Ce qui a changé dans la version 0.0.97 (2024-07-30).\n\nVersion 0.0.97 du paquet npm `total4`, publiée le 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## Nouveautés\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` dans les opérations de schémas et d'actions.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- Le validateur d'icônes accepte le mot-clé `tic`.\n\n## Modifications\n\n- `Number.pluralize()` a été amélioré.\n- `DATA.query()` a été amélioré.\n\n## Corrections\n\n- Liens des adresses e-mail et des numéros de téléphone en Markdown.\n- Formatage du nombre `0` avec le helper `format` de Tangular.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"it","title":"0.0.97","summary":"Cosa è cambiato nella versione 0.0.97 (2024-07-30).","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> Cosa è cambiato nella versione 0.0.97 (2024-07-30).\n\nVersione 0.0.97 del pacchetto npm `total4`, pubblicata il 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## Novità\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` nelle operazioni di schemi e azioni.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- Il validatore delle icone accetta la parola chiave `tic`.\n\n## Modifiche\n\n- `Number.pluralize()` è stato migliorato.\n- `DATA.query()` è stato migliorato.\n\n## Correzioni\n\n- Link di indirizzi e-mail e numeri di telefono in Markdown.\n- Formattazione del numero `0` con l'helper `format` di Tangular.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJs26x61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-97/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"sk","title":"0.0.97","summary":"Čo sa zmenilo vo verzii 0.0.97 (2024-07-30).","markdown":"---\ntitle: 0.0.97\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-97/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.97\n\n> Čo sa zmenilo vo verzii 0.0.97 (2024-07-30).\n\nVerzia 0.0.97 npm balíka `total4`, zverejnená 2024-07-30.\n\n```bash\nnpm install total4@0.0.97\n```\n\n## Nové\n\n- `PROMISIFY(fn, [a], [b])`.\n- `$.promisify(fn, [a], [b])` v operáciách schém a akcií.\n- `FILESTORAGE().copy(id, path, [callback(err, meta)])`.\n- Validátor ikon akceptuje kľúčové slovo `tic`.\n\n## Zmenené\n\n- Vylepšené `Number.pluralize()`.\n- Vylepšené `DATA.query()`.\n\n## Opravené\n\n- Odkazy na e-mailové adresy a telefónne čísla v Markdowne.\n- Formátovanie čísla `0` helperom `format` v Tangulare.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"en","title":"0.0.96","summary":"What changed in release 0.0.96 (2024-05-03).","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> What changed in release 0.0.96 (2024-05-03).\n\nRelease 0.0.96 of the npm package `total4`, published on 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## New\n\n- `Total`: a new global variable, an alias of `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Changed\n\n- Bookmarks in Markdown were improved.\n\n## Fixed\n\n- The `Message-ID` of the SMTP sender.\n- `CLEANUP()`.\n- Unit testing.\n- Refreshing subscribers in the Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"de","title":"0.0.96","summary":"Was sich in Version 0.0.96 (2024-05-03) geändert hat.","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> Was sich in Version 0.0.96 (2024-05-03) geändert hat.\n\nVersion 0.0.96 des npm-Pakets `total4`, veröffentlicht am 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## Neu\n\n- `Total`: eine neue globale Variable, ein Alias von `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Geändert\n\n- Lesezeichen in Markdown wurden verbessert.\n\n## Behoben\n\n- Die `Message-ID` des SMTP-Senders.\n- `CLEANUP()`.\n- Unit-Tests.\n- Das Aktualisieren von Abonnenten im Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"es","title":"0.0.96","summary":"Qué cambió en la versión 0.0.96 (2024-05-03).","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> Qué cambió en la versión 0.0.96 (2024-05-03).\n\nVersión 0.0.96 del paquete npm `total4`, publicada el 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## Novedades\n\n- `Total`: una nueva variable global, alias de `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Cambios\n\n- Se mejoraron los marcadores (bookmarks) en Markdown.\n\n## Correcciones\n\n- El `Message-ID` del remitente SMTP.\n- `CLEANUP()`.\n- Pruebas unitarias.\n- La actualización de los suscriptores en Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"fr","title":"0.0.96","summary":"Ce qui a changé dans la version 0.0.96 (2024-05-03).","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> Ce qui a changé dans la version 0.0.96 (2024-05-03).\n\nVersion 0.0.96 du paquet npm `total4`, publiée le 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## Nouveautés\n\n- `Total` : une nouvelle variable globale, alias de `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Modifications\n\n- Les signets en Markdown ont été améliorés.\n\n## Corrections\n\n- Le `Message-ID` de l'expéditeur SMTP.\n- `CLEANUP()`.\n- Les tests unitaires.\n- Le rafraîchissement des abonnés dans le Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"it","title":"0.0.96","summary":"Cosa è cambiato nella versione 0.0.96 (2024-05-03).","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> Cosa è cambiato nella versione 0.0.96 (2024-05-03).\n\nVersione 0.0.96 del pacchetto npm `total4`, pubblicata il 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## Novità\n\n- `Total`: una nuova variabile globale, alias di `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Modifiche\n\n- Migliorati i segnalibri in Markdown.\n\n## Correzioni\n\n- Il `Message-ID` del mittente SMTP.\n- `CLEANUP()`.\n- Test unitari.\n- Aggiornamento dei sottoscrittori nel Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJn22x61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-96/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"sk","title":"0.0.96","summary":"Čo sa zmenilo vo verzii 0.0.96 (2024-05-03).","markdown":"---\ntitle: 0.0.96\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-96/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.96\n\n> Čo sa zmenilo vo verzii 0.0.96 (2024-05-03).\n\nVerzia 0.0.96 npm balíka `total4`, zverejnená 2024-05-03.\n\n```bash\nnpm install total4@0.0.96\n```\n\n## Nové\n\n- `Total`: nová globálna premenná, alias `F`.\n- `FlowStreamInstance.stats {Object}`.\n\n## Zmenené\n\n- Vylepšené záložky v Markdown.\n\n## Opravené\n\n- `Message-ID` odosielateľa SMTP.\n- `CLEANUP()`.\n- Unit testovanie.\n- Obnovovanie odberateľov v Total.js Message Service.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f","url":"https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"en","title":"0.0.95","summary":"What changed in release 0.0.95 (2024-02-08).","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: en\nlicense: MIT\nurl: https://totaljs.es/docs/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> What changed in release 0.0.95 (2024-02-08).\n\nRelease 0.0.95 of the npm package `total4`, published on 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## New\n\n- `Array.TfindIndex()`: an alias of `findIndex()`, because some npm packages define their own.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Custom actions in the Route API.\n- `U.ls()` has a new `unified` argument.\n\n## Changed\n\n- `jsonschemaobject.transform(data, partial, [error])` takes an `error` argument; the `callback` argument was removed.\n- Exporting a Flow schema was improved.\n\n## Fixed\n\n- Loading FlowStreams without identifiers.\n- Serializing TMS sources in the Flow module.\n- `String.args()` with keys that contain `$`.\n- Parsing `ul` lists in the Markdown parser.\n- `every` values (for example `*/5`) in the cron.\n- The `#id` selector of `FlowStreamInstance.send()`.\n- Loading `default_root` from the environment.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f-de","url":"https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"de","title":"0.0.95","summary":"Was sich in Version 0.0.95 (2024-02-08) geändert hat.","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: de\nlicense: MIT\nurl: https://totaljs.es/docs/de/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> Was sich in Version 0.0.95 (2024-02-08) geändert hat.\n\nVersion 0.0.95 des npm-Pakets `total4`, veröffentlicht am 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## Neu\n\n- `Array.TfindIndex()`: ein Alias von `findIndex()`, weil manche npm-Pakete ihr eigenes definieren.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Eigene Aktionen in der Route API.\n- `U.ls()` hat ein neues Argument `unified`.\n\n## Geändert\n\n- `jsonschemaobject.transform(data, partial, [error])` nimmt ein Argument `error`; das Argument `callback` wurde entfernt.\n- Der Export eines Flow-Schemas wurde verbessert.\n\n## Behoben\n\n- Laden von FlowStreams ohne Bezeichner.\n- Serialisierung von TMS-Quellen im Flow-Modul.\n- `String.args()` mit Schlüsseln, die `$` enthalten.\n- Parsen von `ul`-Listen im Markdown-Parser.\n- `every`-Werte (zum Beispiel `*/5`) im Cron.\n- Der `#id`-Selektor von `FlowStreamInstance.send()`.\n- Laden von `default_root` aus der Umgebung.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f-es","url":"https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"es","title":"0.0.95","summary":"Qué cambió en la versión 0.0.95 (2024-02-08).","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: es\nlicense: MIT\nurl: https://totaljs.es/docs/es/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> Qué cambió en la versión 0.0.95 (2024-02-08).\n\nVersión 0.0.95 del paquete npm `total4`, publicada el 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## Novedades\n\n- `Array.TfindIndex()`: un alias de `findIndex()`, porque algunos paquetes npm definen el suyo propio.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Acciones personalizadas en la Route API.\n- `U.ls()` tiene un nuevo argumento `unified`.\n\n## Cambios\n\n- `jsonschemaobject.transform(data, partial, [error])` recibe un argumento `error`; se eliminó el argumento `callback`.\n- Se mejoró la exportación de un esquema de Flow.\n\n## Correcciones\n\n- Carga de FlowStreams sin identificadores.\n- Serialización de fuentes TMS en el módulo Flow.\n- `String.args()` con claves que contienen `$`.\n- Análisis de listas `ul` en el parser de Markdown.\n- Valores `every` (por ejemplo `*/5`) en el cron.\n- El selector `#id` de `FlowStreamInstance.send()`.\n- Carga de `default_root` desde el entorno.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f-fr","url":"https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"fr","title":"0.0.95","summary":"Ce qui a changé dans la version 0.0.95 (2024-02-08).","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: fr\nlicense: MIT\nurl: https://totaljs.es/docs/fr/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> Ce qui a changé dans la version 0.0.95 (2024-02-08).\n\nVersion 0.0.95 du paquet npm `total4`, publiée le 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## Nouveautés\n\n- `Array.TfindIndex()` : un alias de `findIndex()`, car certains paquets npm définissent le leur.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Actions personnalisées dans la Route API.\n- `U.ls()` a un nouvel argument `unified`.\n\n## Modifications\n\n- `jsonschemaobject.transform(data, partial, [error])` accepte un argument `error` ; l'argument `callback` a été supprimé.\n- L'export d'un schéma Flow a été amélioré.\n\n## Corrections\n\n- Chargement des FlowStreams sans identifiants.\n- Sérialisation des sources TMS dans le module Flow.\n- `String.args()` avec des clés contenant `$`.\n- Analyse des listes `ul` dans le parseur Markdown.\n- Valeurs `every` (par exemple `*/5`) dans le cron.\n- Le sélecteur `#id` de `FlowStreamInstance.send()`.\n- Chargement de `default_root` depuis l'environnement.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f-it","url":"https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"it","title":"0.0.95","summary":"Cosa è cambiato nella versione 0.0.95 (2024-02-08).","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: it\nlicense: MIT\nurl: https://totaljs.es/docs/it/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> Cosa è cambiato nella versione 0.0.95 (2024-02-08).\n\nVersione 0.0.95 del pacchetto npm `total4`, pubblicata il 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## Novità\n\n- `Array.TfindIndex()`: un alias di `findIndex()`, perché alcuni pacchetti npm definiscono il proprio.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Azioni personalizzate nella Route API.\n- `U.ls()` ha un nuovo argomento `unified`.\n\n## Modifiche\n\n- `jsonschemaobject.transform(data, partial, [error])` accetta un argomento `error`; l'argomento `callback` è stato rimosso.\n- È stata migliorata l'esportazione di uno schema Flow.\n\n## Correzioni\n\n- Il caricamento di FlowStream senza identificatori.\n- La serializzazione delle sorgenti TMS nel modulo Flow.\n- `String.args()` con chiavi che contengono `$`.\n- Il parsing delle liste `ul` nel parser Markdown.\n- I valori `every` (per esempio `*/5`) nel cron.\n- Il selettore `#id` di `FlowStreamInstance.send()`.\n- Il caricamento di `default_root` dall'ambiente.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
{"id":"JabUJi1yx61f-sk","url":"https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-95/","project":"total-js-v4","version":"0-0-99","section":"changelog","language":"sk","title":"0.0.95","summary":"Čo sa zmenilo vo verzii 0.0.95 (2024-02-08).","markdown":"---\ntitle: 0.0.95\nproject: Total.js V4\nversion: 0.0.99\nsection: changelog\nlanguage: sk\nlicense: MIT\nurl: https://totaljs.es/docs/sk/total-js-v4/0-0-99/changelog/0-0-95/\nupdated: 2026-11-15T11:04:14.869Z\n---\n\n# 0.0.95\n\n> Čo sa zmenilo vo verzii 0.0.95 (2024-02-08).\n\nVerzia 0.0.95 npm balíka `total4`, publikovaná 2024-02-08.\n\n```bash\nnpm install total4@0.0.95\n```\n\n## Novinky\n\n- `Array.TfindIndex()`: alias pre `findIndex()`, pretože niektoré npm balíky definujú vlastný.\n- `String.tslash()`.\n- `FlowInstance.remove()`.\n- `FlowStreamComponentInstance.components {Object}`.\n- Vlastné akcie v Route API.\n- `U.ls()` má nový argument `unified`.\n\n## Zmeny\n\n- `jsonschemaobject.transform(data, partial, [error])` prijíma argument `error`; argument `callback` bol odstránený.\n- Export Flow schémy bol vylepšený.\n\n## Opravy\n\n- Načítanie FlowStreamov bez identifikátorov.\n- Serializácia TMS zdrojov v module Flow.\n- `String.args()` s kľúčmi, ktoré obsahujú `$`.\n- Parsovanie zoznamov `ul` v Markdown parseri.\n- Hodnoty `every` (napríklad `*/5`) v crone.\n- Selektor `#id` v `FlowStreamInstance.send()`.\n- Načítanie `default_root` z prostredia.\n","entries":[],"license":"MIT","updated":"2026-11-15T11:04:14.869Z"}
